using System;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;

namespace eDosStation
{
    /// <summary>
    /// Interaction logic for EntryBadge.xaml
    /// </summary>
    public partial class EntryBadge : Window
    {
        bool taskLoading = false;
        const int PageTimeout = 10000;
        bool initialising = true;
        Station thisStation;
        EpdBaseClr.Epd2 ep;
        DispatcherTimer dispatcherTimer;
        int UserSeconds;
        Boolean Inst1 = false, Inst2 = false;
        private System.Threading.Tasks.Task ReaderTask = null;
        private DataInterface dataInterface;
        public LSWDesfirePublic.CCard dfReader = null;
        static User _User;
        DataSet1.GetTaskInfoRow CurTaskRow;
        private DateTime ResultTime;
        enum eCOE { quiz = 1 };

#if SimulateEPD
        public SimulateData simulData = new SimulateData();
#endif

        public EntryBadge(Station curStation)
        {
            InitializeComponent();
            dataInterface = curStation.dataInterface;
            ep = new EpdBaseClr.Epd2(curStation.ComPort);
            ep.SetFeedbackSound(curStation.useBeep,curStation.useBeepMK3());
            ep.EpdRead += Ep_EpdRead;
            ep.EpdError += Ep_EpdError;
            ep.EpdTO += Ep_EpdTO;
            thisStation = curStation;
            _User = null;
            taskLoading = true;
        }

        private void Ep_EpdTO(EpdBaseClr.Epd2 Sender, EpdBaseClr.EpdTOEventArgs e)
        {
            Dispatcher.InvokeAsync(() => {
                endPage();
            });
        }

        private void Ep_EpdError(EpdBaseClr.Epd2 Sender, EpdBaseClr.EpdErrorEventArgs e)
        {
            Dispatcher.InvokeAsync(() => {
                MessageBox.Show($"EPD Error {e.returnValue}");
                endPage();
            });
        }

        private void Ep_EpdRead(EpdBaseClr.Epd2 Sender, EpdBaseClr.EpdEventArgs e)
        {
            Dispatcher.InvokeAsync(() => GetEPD());
        }

        private bool LoadDoses()
        {
            bool rv = true;
            
#if SimulateEPD
            ep.CountsClock = 12345;
            ep.alarmStatus = 0;
            ep.otherAlarms = 0;
#endif
            //if (rva != 0)
            //{
            //    MessageBox.Show($"Entry GetStatus error {rva} {ep.GetStatusError}");
            //}
            System.Diagnostics.Debug.WriteLine($"LoadDoses: EPD {ep.EpdID} Type:{ep.epdType}");
            statusEPD.Text = $"EPD:  {ep.EpdID}";
            if (ep.EPDIssued)
            {
                TextBlock il = new TextBlock();
                il.Inlines.Add(new Run("This EPD is currently issued") {
                    FontSize = 36
                }); ;
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new Run("Please take an other."));
                il.HorizontalAlignment = HorizontalAlignment.Center;
                il.TextAlignment = System.Windows.TextAlignment.Center; 
                (new InstMessage(il)).ShowDialog();


                //MessageBox.Show("EPD is currently issued\nPlease take an other", "EDP", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
                endPage();
                return false;
            }
            if (ep.hasAlarm)
            {
                TextBlock il = new TextBlock();
                il.Inlines.Add(new Run("EPD is in alarm status\n\n")
                {
                    FontSize = 36
                }); ;
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                if (ep.alarmStatus > 0) il.Inlines.Add(new Run("* Dose alarm *"));
                if (ep.OtherAlarmBatLow > 0) il.Inlines.Add(new Run("* Battery Low *"));
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new Run("Please take an other."));
                il.HorizontalAlignment = HorizontalAlignment.Center;
                il.TextAlignment = System.Windows.TextAlignment.Center;
                (new InstMessage(il)).ShowDialog();
                endPage();
                return false;
            }
            if (ep.isBG != CurTaskRow.EPDRad.Equals("BG"))
            {
                string curtype = null, needdtype = string.Empty; 
                if (ep.isBG) curtype = "BG Beta-Gamma"; else curtype = "NG (Neutron)";
                if (CurTaskRow.EPDRad.Equals("BG")) needdtype = "BG (Beta-Gamma)"; else needdtype = "NG (Neutron)";

                TextBlock il = new TextBlock();
                il.Inlines.Add(new Run("This EPD is not the right type")
                {
                    FontSize = 36
                }); ;
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(InstMessage.GetFullWidthLine());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new Run($"This task needs a {needdtype} EPD,\n this is a {curtype}")
                {
                    Background = System.Windows.Media.Brushes.Yellow
                }); ;
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(InstMessage.GetFullWidthLine());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new LineBreak());
                il.Inlines.Add(new Run("Please take an other."));
                il.HorizontalAlignment = HorizontalAlignment.Center;
                il.TextAlignment = System.Windows.TextAlignment.Center;
                (new InstMessage(il)).ShowDialog();
                endPage();
                return false;
            }
            //rva = ep.ReadTresholds();
            //if (rva != 0)
            //{
            //    MessageBox.Show($"ReadTresholds error {ep.ReadTresholdsError}");
            //}
            return rv;
        }
        //private void DispatcherTimer_Tick(object sender, EventArgs e)
        //{
        //    //Was timeout 
        //    //voorlopig niet meer gebruikt
        //    EpdFound = false;
        //    dispatcherTimer.Stop();
        //    ep.Close();
        //    System.Threading.Thread.Sleep(200);
          
        //    int rv = ep.Connect(false,thisStation.EPDTimeOut);
        //    System.Diagnostics.Debug.WriteLine($"Connect {rv} error {ep.ConnectError}");
        //    if (ep.DeviceCount > 0 && ep.EpdID > 0)
        //    {
        //        System.Diagnostics.Debug.WriteLine($"Devices:{ep.DeviceCount} id:{ep.EpdID} {ep.ConnectError} ");
        //        EpdFound = true;
        //        DoEPD();
        //    }
        //    if (!EpdFound)
        //    {
        //        Search--;
        //        if (Search > 0)
        //        {
        //            statusEPD.Text = $"Searching  EPD ... {Search} ({ep.ConnectError})";
        //            dispatcherTimer.Start();
        //        }
        //        else
        //        {
        //            statusEPD.Text = $"No EPD found";
        //        }
        //    }
        //}
        private void DoEPD()
        {
            int? StationVisitID = null;
            int? ID_Visit = null;

            if (LoadDoses())
            {
                try
                {
                    ID_Visit = DataInterface.NextID();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show($"Error {ex.Message}");
                }
                if (ID_Visit.HasValue)
                {
                    bool isBG = ep.isBG; // (ep.epdType != 3);  //3 = zwarte  0=grijs
                    var co = dataInterface.getCon(true);
                    dataInterface.VisitInitCommand.Connection = co;
                    dataInterface.VisitInitCommand.Parameters["ID_Station"].Value = thisStation.ID_Station;
                    dataInterface.VisitInitCommand.Parameters["ID_Visit"].Value = ID_Visit;
                    dataInterface.VisitInitCommand.Parameters["PersID"].Value = _User.PersID;
                    dataInterface.VisitInitCommand.Parameters["ID_Task"].Value = CurTaskRow.ID_Task;
                    dataInterface.VisitInitCommand.Parameters["Inst_CODE"].Value = CurTaskRow.Inst_CODE;
                    dataInterface.VisitInitCommand.Parameters["EPD_InternalID"].Value = (int)ep.EpdID;
                    dataInterface.VisitInitCommand.Parameters["isBG"].Value = isBG;
                    dataInterface.VisitInitCommand.Parameters["ENTRY_EPD_CLOCK"].Value = ep.CountsClock;
                    dataInterface.VisitInitCommand.Parameters["epdType"].Value = (byte)ep.epdType;

                    using (var l = new SqlLog())
                        try
                        {
                            dataInterface.VisitInitCommand.ExecuteNonQuery();
                            l.LogCommand(dataInterface.VisitInitCommand);
                        }
                        catch (System.Exception ex)
                        {
                            l.LogCommand(ex.Message);
                            MessageBox.Show(ex.Message);
                        }
                    StationVisitID = (int?)dataInterface.VisitInitCommand.Parameters["EPDVisitID"].Value;
                    co.Close();
                    ep.WearerID = StationVisitID.ToString();
                    ep.WearerName = _User.PersID.ToString();

#if SimulateEPD
                simulData.EdpType = ep.epdType;
                simulData.WearerID = ep.WearerID;
                simulData.WearerName = ep.WearerName;
#endif

                ep.Hp07RateOn = CurTaskRow.HP07RateON;
                ep.Hp07RateOff = CurTaskRow.HP07RateOFF;
                ep.Hp10Rate1On = CurTaskRow.HP10Rate1ON;
                ep.Hp10Rate1Off = CurTaskRow.HP10Rate1ON;
                ep.Hp10Rate2On = CurTaskRow.HP10Rate2ON;
                ep.Hp10Rate2Off = CurTaskRow.HP10Rate2ON;
                ep.Hp10THDose1 = CurTaskRow.Hp10Dose1;
                ep.Hp10THDose2 = CurTaskRow.Hp10Dose2;
                ep.Hp07THDose = CurTaskRow.Hp07Dose;

                    ////voor Neutron K3, K4
                    //int? kx = null;
                    //if (!CurTaskRow.IsFNGain_ANGainValueNull()) kx = (int)CurTaskRow.FNGain_ANGainValue;
                    //if (kx != null && (ep.K3 != kx || ep.K4 != kx))
                    //    {
                    //        ep.K3 = ep.K4 = kx.Value;
                    //        if (!ep.isBG)
                    //        {
                    //            if (ep.K6 != 1310)
                    //            {
                    //                MessageBox.Show("Alarm");
                    //            }
                    //            else
                    //            {
                    //                ep.WriteCalibration();
                    //            }
                    //        }
                    //    }
#if DummyData
                ep.Hp07THDose = 70;
                ep.Hp10THDose1 = 11;
                ep.Hp10THDose2 = 12;
               
                ep.Hp07RateOn = 80;
                ep.Hp07RateOff = 9;
                ep.Hp10Rate1On = 13;
                ep.Hp10Rate1Off = 14;
                ep.Hp10Rate2On = 15;
                ep.Hp10Rate2Off = 16;

                ep.K3 = 3; ep.K4 = 4;
                if (!ep.isBG) 
                    ep.WriteCalibration();
                
#endif
                    
                    float gain = 100.0F;  
                    if (!CurTaskRow.IsFNGain_ANGainValueNull()) gain= (int)CurTaskRow.FNGain_ANGainValue;
                    int rv = ep.IssueAndCheck(gain);
                    if (rv != 0)
                    {
                        MessageBox.Show($"SetIssued error {rv}");
                    }
                    dispatcherTimer.Start();  //restart timer
                    panelDone.Visibility = Visibility.Visible;
                    lbHP07.Text = ep.Hp07Name;
                    lbHP10.Text = ep.Hp10Name;
                    panelWait.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void GetEPD()
        {
            if (ep.DeviceCount == 1 && ep.EpdID> 0)
            {
                statusEPD.Text = string.Empty;
                DoEPD();
            }
        }

        private void SetFilter(bool isAlara)
        {
            taskLoading = true;
            TaskOK.IsEnabled = false;

            Inst1 = (cbInst1.IsChecked == true);
            Inst2 = (cbInst2.IsChecked == true);
            StringBuilder fi = new StringBuilder();
            if (!Inst1 && !Inst2)
            {
                fi.Append(" 1=2 ");
            }
            else
            {
                if (Inst1 == true) fi.Append($"{(Inst2 ? "(" : "") } Inst_CODE = {thisStation.Inst_CODE1} ");
                if (Inst2 == true) fi.Append($" {(Inst1 ? "or" : "") } Inst_CODE={thisStation.Inst_CODE2} {(Inst1 ? ")" : "")} ");
                fi.Append($" {(Inst1 || Inst2 ? "AND" : "") } TaskType_CODE { (isAlara ? ">=" : "<")} '1000' ");
            }
            System.Windows.Data.CollectionViewSource getTaskListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("getTaskListViewSource")));
            var dv = getTaskListViewSource.View.SourceCollection as DataView;
            //if (isAlara) dv.RowFilter = "ID_Task>=1000"; else dv.RowFilter = "ID_Task<1000";
            try
            {
                dv.RowFilter = fi.ToString();
            } catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            getTaskListViewSource.View.MoveCurrentTo(null);
            taskLoading = false;
        }

        public string getCommentUnknown()
        {
            StringBuilder res = new StringBuilder();
            var r = dataInterface.GetCommentOnEventRow(3);
            res.AppendLine(r.Comment_NL).Replace("\\n", "\n");
            res.AppendLine("---");
            res.AppendLine(r.Comment_FR).Replace("\\n", "\n");
            res.AppendLine("---");
            res.AppendLine(r.Comment_EN).Replace("\\n", "\n");
            res.AppendLine("---");
            return res.ToString();
        }

        public string getCommentOnEvent(string prefix, int id)
        {
            string res = string.Empty;
            if (!string.IsNullOrWhiteSpace(prefix)) res = prefix + "\n";
            var r = dataInterface.GetCommentOnEventRow(id);
            string l = _User?.Language ?? "E";
            if (r != null)
                switch (l)
                {
                    case "N": res += r.Comment_NL; break;
                    case "F": res += r.Comment_FR; break;
                    default: res += r.Comment_EN; break;
                }
            return res.Replace("\\n", "\n");
        }

        /// <summary>
        /// Get User data
        /// </summary>
        /// <returns>doCancel</returns>
        bool ShowUserInfo()
        {
            bool doCancel = false;
            UserSeconds = 10;
            //UserScreen
            string ReasonNoAccess = string.Empty;

            if (_User.PersID == 0)
            {
                tReasonNoAccess.Text = getCommentUnknown();
                if (_User.Error > 0) tReasonNoAccess.Text = _User.ErrorMessage;
                tbNotAllowed.IsSelected = true;
                doCancel = true;
            }
            else
            {
                tbUser.IsSelected = true;
                if (_User == null || _User.VisitIDLocked > 0 || _User.AccessAllow == false)
                {
                    if (_User.VisitIDLocked > 0 || _User.AccessAllow == false)
                        ReasonNoAccess = _User.ReasonNoAccess;
                    else ReasonNoAccess = getCommentOnEvent(string.Empty, 3);
                }

                if (!string.IsNullOrEmpty(_User.UserComment))
                {
                    UserComment.Text = _User.UserComment;
                    boxComment.Visibility = Visibility.Visible;
                }
                else
                    boxComment.Visibility = Visibility.Hidden;

                if (!string.IsNullOrWhiteSpace(ReasonNoAccess)) 
                    UserAccess.Text = ReasonNoAccess;
                else 
                    //UserAccess.Text = "Welcome to eDOS";
                Username.Text = string.Concat(_User.FirstName, " ", _User.LastName);
                pUserSeconds.Maximum = UserSeconds; pUserSeconds.Value = UserSeconds;
                tReasonNoAccess.Text = ReasonNoAccess;
                dispatcherTimer = new DispatcherTimer(DispatcherPriority.Background);
                dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
                dispatcherTimer.Tick += SwitchToTask;
                dispatcherTimer.Start();
            }
            return doCancel;
        }

        private void SwitchToTask(object sender, EventArgs e)
        {
            if (--UserSeconds > 0 && (_User.AccessAllow != true || !string.IsNullOrEmpty(_User.UserComment) || !string.IsNullOrEmpty(_User.ReasonNoAccess)))
            {
                tUserSeconds.Text = UserSeconds.ToString();
                pUserSeconds.Value = UserSeconds;
            }
            else
            {
                dispatcherTimer.Stop();
                dispatcherTimer.Tick -= SwitchToTask;
                if (_User.AllOk == true)
                    AskTask();
                else Close();
            }
        }
        void AskTask()
        {
            Naam.Text = _User.FirstName + " " + _User.LastName;
            eDosStation.DataSet1 dataSet1 = ((eDosStation.DataSet1)(this.FindResource("dataSet1")));
            dataInterface.FillTaskInfo(_User, dataSet1);
            tbTask.IsSelected = true;
            bool isAlara = (cbAlara.IsChecked == true);
            SetFilter(isAlara);
        }
        void CheckBadge()
        {
            _User = dataInterface.GetUser(CSN.Text, Code.Text);
            if (ShowUserInfo()) endPage();
        }
        public void showBadge(int persID, string csn)
        {
            CSN.Text = csn;
            Site.Text = string.Empty;
            Code.Text = persID.ToString();
            Dispatcher.InvokeAsync(CheckBadge,DispatcherPriority.Background);
        }
        public void endPage()
        {
            this.Close();
        }

        private void bClose_Click(object sender, RoutedEventArgs e)
        {
            endPage();
        }

        private void BClear_Click(object sender, RoutedEventArgs e)
        {
            CSN.Text = string.Empty;
            Site.Text = string.Empty;
            Code.Text = string.Empty;
        }

        private void TaskOK_Click(object sender, RoutedEventArgs e)
        {
            
            bool isOk = false;
            switch (TaskOK.Tag)
            {
                case "A": //No access
                    break;
                case "M": //Margin
                    break;
                case "B": // Badge
                    break;
                case "L": //Locked
                    break;
                case "O": // OK
                    isOk = true;
                    break;
            }

            if (isOk)
            {
                System.Windows.Data.CollectionViewSource getTaskListViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("getTaskListViewSource")));
                var rv = getTaskListViewSource.View.CurrentItem as DataRowView;
                CurTaskRow = rv.Row as DataSet1.GetTaskInfoRow;
                
                if (_User == null || CurTaskRow == null) return;
                if (CurTaskRow.MinWorkerDosisMargin > _User.Margin)
                {
                    MessageBox.Show("Margin exceeded");
                    endPage();
                }
                else
                {
                    tb.SelectedItem = tbEPD;
                    panelDone.Visibility = Visibility.Collapsed;//1
                    panelWait.Visibility = Visibility.Visible;
                    statusEPD.Text = $"Waiting for EPD  (max {thisStation.EPDTimeOut/1000} seconds)";
                    dispatcherTimer = new DispatcherTimer(DispatcherPriority.Background);
                    dispatcherTimer.Interval = TimeSpan.FromMilliseconds(thisStation.EPDTimeOut / 10);
                    dispatcherTimer.Tick += CountDown;
                    ResultTime = DateTime.Now.AddMilliseconds(thisStation.EPDTimeOut);
                    dispatcherTimer.Start();
                    pWaitEpd.Value = pWaitEpd.Maximum = thisStation.EPDTimeOut/1000;
                    Dispatcher.InvokeAsync(new Action(() => { ep.Wait(thisStation.EPDTimeOut, 1);  }),DispatcherPriority.Background);
                }
            }
        }

        private void CountDown(object sender, EventArgs e)
        {
            double v = (ResultTime - DateTime.Now).TotalSeconds;
            if (v > pWaitEpd.Minimum)
                pWaitEpd.Value = v;
            else
            {
                dispatcherTimer.Stop();
                endPage();
            }
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (taskLoading) return;
            var lb = sender as ListBox;
            DataRowView o = null;
            if (e.AddedItems.Count > 0)
            {
                o = e.AddedItems[0] as DataRowView;
                TaskOK.IsEnabled = true;
            }
            bool exceeded = false;
            if (o != null)
            {
                exceeded = (((DataSet1.GetTaskInfoRow)o.Row).MarginExceeded);
            }
            if (_User == null) { TaskOK.Content = "Badge"; TaskOK.Tag = "B"; }
            else if (!_User.AllOk)
            {
                if (_User.AccessAllow != true) { TaskOK.Content = "No Access"; TaskOK.Tag = "A"; }
                else if (_User.VisitIDLocked > 0) { TaskOK.Content = "Locked"; TaskOK.Tag = "L"; }
                else if (exceeded == true) { TaskOK.Content = "No Margin"; TaskOK.Tag = "M"; }
            }
            else
            {
                TaskOK.Content = "OK"; TaskOK.Tag = "O";
            }
        }

        private void CbInst1_Click(object sender, RoutedEventArgs e)
        {
            Inst1 = (cbInst1.IsChecked == true);
            cbInst2.IsChecked = !Inst1;
            bool isAlara = (cbAlara.IsChecked == true);
            SetFilter(isAlara);
        }

        private void CbAlara_Click(object sender, RoutedEventArgs e)
        {
            if (!initialising)
            {
                bool isAlara = true;
                cbAlara.IsChecked = true;
                cbNormal.IsChecked = !isAlara;
                SetFilter(isAlara);
            }
        }

        private void CbNormal_Click(object sender, RoutedEventArgs e)
        {
            if (!initialising)
            {
                bool isAlara = false;
                cbAlara.IsChecked = isAlara;
                cbNormal.IsChecked = !isAlara;
                SetFilter(isAlara);
            }
        }

        private void BUserRead_Click(object sender, RoutedEventArgs e)
        {
            dispatcherTimer.Stop();
            dispatcherTimer.Tick -= SwitchToTask;
            if (_User.AllOk == true)
                AskTask();
            else Close();
        }

        private void TaskCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void BTestPerson_Click(object sender, RoutedEventArgs e)
        {
            dfReader.WaitEnd();
            Button b = sender as Button;
            _User = dataInterface.GetUser("TP"+b.Tag.ToString().ToUpper(), "");
            ShowUserInfo(); //AskTask();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                if (ep != null)
                {
                    ep.WaitEnd();
                    ep.Dispose();
                    ep = null;
                }
                if (dfReader != null)
                {
                    dfReader.WaitEnd();
                    dfReader.Dispose();
                    dfReader = null;
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        private void CbInst2_Click(object sender, RoutedEventArgs e)
        {
            Inst2 = (cbInst2.IsChecked == true);
            cbInst1.IsChecked = !Inst2;
            bool isAlara = (cbAlara.IsChecked == true);
            SetFilter(isAlara);
        }

        private void AddTestButtons()
        {
            StackPanel sp = pTestButtons;
            Button b;
            Thickness m = new Thickness(0, 0, 20, 0);
            for (int i = 1; i < 15; i++)
            {
                b = new Button();
                b.Click += BTestPerson_Click;
                b.Tag = i.ToString();
                b.Content = $"* TP {i} *";
                b.Height = 30;
                b.Margin = m;
                sp.Children.Add(b);
            }
            sp.Visibility = Visibility.Visible;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            initialising = true;
            tbEntry.IsSelected = true;
            panelDone.Visibility= Visibility.Collapsed;
            panelWait.Visibility = Visibility.Visible;
            cbAlara.IsChecked = false;

            cbInst1.Content = thisStation.Inst_Name1;
            Inst1 = true;
            cbInst1.IsChecked = Inst1;
            if (thisStation.Inst_CODE2 > 0)
            {
                cbInst2.Content = thisStation.Inst_Name2;
                cbInst2.Visibility = Visibility.Visible;
                Inst2 = false;
                cbInst2.IsChecked = Inst2;
            }

            dataInterface.FillComment();

            initialising = false;

            if (thisStation.useTestButtons) AddTestButtons();

            if (dfReader == null)
            {
                dfReader = new LSWDesfirePublic.CCard();
                dfReader.GetReaderList();
                if (dfReader.readersList.Contains(thisStation.Reader))
                {
                    dfReader.SetReader(thisStation.Reader);
                    dfReader.Badged += DFReader_Badged;
                    dfReader.BadgeTO += DfReader_BadgeTO;
                    dfReader.BadgeError += DfReader_BadgeError;
                    ReaderTask = dfReader.Wait(PageTimeout,10);
                    //dfReader.WaitForBadge();
                }
                else
                {
                    StringBuilder er = new StringBuilder($"Badgelezer \"{thisStation.Reader}\" niet gevonden!.\nDeze lezers zijn beschikbaar:\n");
                    dfReader.GetReaderList();
                    foreach (string r in dfReader.readersList) er.AppendLine($"-> {r}");
                    MessageBox.Show(er.ToString(), "Badge Lezer", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    dfReader.Dispose(); dfReader = null;
                }
            }
        }

        private void DfReader_BadgeError(LSWDesfirePublic.CCard Sender, LSWDesfirePublic.BadgeErrorEventArgs e)
        {
            endPage();
        }

        private void LeesCancel_Click(object sender, RoutedEventArgs e)
        {
            endPage();
        }
    
        private void DfReader_BadgeTO(LSWDesfirePublic.CCard Sender, EventArgs e)
        {
            this.Dispatcher.InvokeAsync(new Action(() => endPage()),DispatcherPriority.Normal);
        }

        private void DFReader_Badged(LSWDesfirePublic.CCard Sender, LSWDesfirePublic.BadgeEventArgs e)
        {
            if (e.PersID > 0)
            {
                this.Dispatcher.InvokeAsync(new Action(() => showBadge(e.PersID, e.UID)),DispatcherPriority.Background);
            }
        }
    }
}
