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

namespace eDosStation
{
    /// <summary>
    /// Interaction logic for EntryBadge.xaml
    /// </summary>
    public partial class EntryBadge : Window
    {
        const int PageTimeout = 10000;
        bool initialising = true;
        Station thisStation;
        EpdBaseClr.Epd2 ep;
        bool EpdFound = false;
        DispatcherTimer dispatcherTimer;
        int Search, UserSeconds;
        Boolean Inst1 = false, Inst2 = false;
        private System.Threading.Tasks.Task ReaderTask =null;
        private DataInterface dataInterface;

        public static LSWDesfirePublic.CCard dfReader;
        //System.Threading.Thread t;
        //bool nextCSN = false;
        //bool nextSite = false;
        //bool nextCode = false;
        //bool nextFinish = false;
        //string csn, site, code;
        static User _User;

        DataSet1.GetTaskInfoRow CurTaskRow;
        enum eCOE { quiz=1} ;
        

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

        public EntryBadge(EpdBaseClr.Epd2 curEP, Station curStation)
        {
            InitializeComponent();
            dataInterface = curStation.dataInterface;
            ep = curEP;
            thisStation = curStation;
            _User = null;
        }

        private bool LoadDoses()
        {
            bool rv = true;
            System.Diagnostics.Debug.WriteLine("LoadDoses: EPD GEt Status");
            int rva= ep.GetStatus();
#if SimulateEPD
            ep.CountsClock = 12345;
            ep.alarmStatus = 0;
            ep.otherAlarms = 0;
#endif
            if (rva != 1)
            {
                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.Issued)
            {
                MessageBox.Show("EPD is currently issued\nPlease take an other", "EDP", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
                this.Close();
                return false;
            }
            if (ep.alarmStatus != 0 || (ep.otherAlarms & 0x7f)!=0)
            {
                StringBuilder sb = new StringBuilder("EPD is in alarm status\n\n");
                if (ep.alarmStatus>0) sb.AppendLine("- Alarm dose");
                if (ep.OtherAlarmBatLow > 0) sb.AppendLine("- Battery Low");
                sb.AppendLine();
                sb.AppendLine("Please take another");
                MessageBox.Show(sb.ToString(), "EDP", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
                this.Close();
                return false;
            }
            bool isBG = (ep.epdType == 0);
            if (isBG != CurTaskRow.EPDRad.Equals("BG"))
            {
                MessageBox.Show("Wrong EPD Type", "EDP", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
                this.Close();
                return false;
            }
            
            rva = ep.ReadTresholds();
            if (rva != 1)
            {
                MessageBox.Show($"ReadTresholds error {ep.ReadTresholdsError}");
            }

            return rv;
        }
        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            EpdFound = false;
            dispatcherTimer.Stop();
            ep.Close();
            System.Threading.Thread.Sleep(200);
            int rv= ep.Connect(false);
            System.Diagnostics.Debug.WriteLine($"Connect {rv} error {ep.ConnectError}");
            if (ep.DeviceCount >0 && ep.b.CurrentDeviceID>0)
            {
                System.Diagnostics.Debug.WriteLine($"Devices:{ep.DeviceCount} id:{ep.b.CurrentDeviceID} {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;
            try
            {
                ID_Visit = DataInterface.NextID();
            } catch (System.Exception ex)
            {
                MessageBox.Show($"Error {ex.Message}");
            }
            if (ID_Visit.HasValue && LoadDoses())
            {
                bool 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;
               

                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();

                int rv = ep.PrepareForIssue();
                if (rv != 1)
                {
                    MessageBox.Show($"PrepareForIssue error {ep.PrepareForIssueError}");
                }
                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;

                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 (!isBG)
                    {
                        if (ep.K6 != 1310)
                        {
                            MessageBox.Show("Alarm");
                        }
                        else
                        {
                            ep.WriteCalibration();
                        }
                    }
                }

                rv = ep.SetIssued();
                if (rv != 1)
                {
                    MessageBox.Show($"SetIssued error {ep.SetIssuedError}");
                }
                bEpdDone.Visibility = Visibility.Visible;
            }
            else
                ep.Close();

        }
        private void GetEPD()
        {
            if (_User == null || CurTaskRow == null) return;

            int ok = ep.Connect(false);
            if (ok != 1) System.Diagnostics.Debug.WriteLine($"GetEpd {ok} ConnectError: {ep.ConnectError}");
            if (ep.DeviceCount == 1 && ep.b.CurrentDeviceID>0)
            {
                EpdFound = true;
                DoEPD();
            }
            if (!EpdFound)
            {
                statusEPD.Text = $"EPD:  Wait ";
                Search = 100;
                dispatcherTimer = new DispatcherTimer();
                dispatcherTimer.Tick += DispatcherTimer_Tick;
                dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
                dispatcherTimer.Start();
                return;
            }

        }
        private void SetFilter(bool isAlara)
        {
            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.MoveCurrentToFirst();
        }

        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.Normal);
                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.AccessAllow == 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.Invoke(CheckBadge);
        }

        public void endPage()
        {
            dfReader.Dispose();
            this.Close();
        }
      
        private void bClose_Click(object sender, RoutedEventArgs e)
        {
            dfReader?.Dispose(); dfReader = null;
            this.Close();
        }
        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)
            {
                tbEPD.IsSelected = true;
                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 (CurTaskRow.MinWorkerDosisMargin > _User.Margin)
                {
                    MessageBox.Show("Margin exceeded");
                }
                else
                {
                    GetEPD();
                }
            }
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var lb = sender as ListBox;
            DataRowView o = null;
            if (e.AddedItems.Count > 0)
            {
                o = e.AddedItems[0] as DataRowView;
            }
            bool exceeded = false;
            if (o != null)
            {
                exceeded = (((DataSet1.GetTaskInfoRow)o.Row).MarginExceeded);
            }
            if (_User == null) { TaskOK.Content = "Badge"; TaskOK.Tag = "B"; }
            else 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.AccessAllow == true)
                AskTask();
            else Close();
        }

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

        private void BTestPerson_Click(object sender, RoutedEventArgs e)
        {
            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)
        {
            dfReader?.Dispose(); dfReader = null;
            ep.Close();
        }

        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()
        {
            //pTestButtons
            //<Button Height="30" Content="*TP 1*" Tag="1" Name="bTestPerson1" Click="BTestPerson_Click" Margin="0,0,20,0"/>
            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);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           // dataInterface.checkCon();
            EpdFound = false;
            initialising = true;
            tbEntry.IsSelected = true;
            bEpdDone.Visibility = Visibility.Hidden;
            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();

            //string TestCSN = null; // thisStation.TestCSN;
            initialising = false;

            if (Properties.Settings.Default.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;
                }
            }
            //else {
            //    dfReader.WaitForBadge();
            //}

            
        }

        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.Invoke(new Action(() => endPage()));
        }

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