using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;

namespace eDosStation
{

    public partial class EpdExit : Window
    {
        DataInterface dataInterface;
        Station thisStation;
        EpdBaseClr.Epd2 ep;
        DispatcherTimer dispatcherTimer;
        SolidColorBrush GreenBrush = new SolidColorBrush(Colors.LightGreen);
        SolidColorBrush AlarmBrush = new SolidColorBrush(Colors.LightCoral);
        private DateTime ResultTime;

#if SimulateEPD
        public SimulateData simulData = new SimulateData();
#endif
        public EpdExit(Station curStation)
        {
            InitializeComponent();
            //ep = curEP;
            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;
            dataInterface = curStation.dataInterface;

            dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(thisStation.EPDTimeOut / 10);
            Progress.Maximum = Progress.Value = thisStation.EPDTimeOut / 1000;
            dispatcherTimer.Tick += DispatcherTimer_Tick;
        }

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

        private void Ep_EpdTO(EpdBaseClr.Epd2 Sender, EpdBaseClr.EpdTOEventArgs e)
        {
            Dispatcher.InvokeAsync(() => {
                MessageBox.Show($"Timeout after {e.tries} tries, ConnectTimeout={e.connecttimeout}");
                endPage();
            });
        }

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

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

        private void LoadDoses()
        {

#if SimulateEPD
            ep.epdType = simulData.EdpType;
            ep.Issued = true;
            ep.alarmStatus = 0;
            ep.otherAlarms = 0;
            ep.WearerID = simulData.WearerID;
            ep.WearerName = simulData.WearerName;
            ep.Hp07 = 1;
            ep.Hp10 = 2;
#endif
            int rv = 0;
            if (!ep.EPDIssued)
            {
                Dispatcher.InvokeAsync(() => {
                rv = ep.SetDeIssued();
                endWithMessage("This EPD is not issued");
                });
                return;
            }
            if (ep.EpdID == 0)
            {
                endWithMessage("This EPD is not found");
            }

            //bool NoTimeout = false;

            if (ep.alarmStatus != 0)
            {
                DosePanel.Background = AlarmBrush;
                Alarm.IsSelected = true;
                //NoTimeout = true;
            }
            else if ((ep.otherAlarms & 0x7f) != 0)
            {
                DosePanel.Background = AlarmBrush;
                OtherAlarm.IsSelected = true;
                //NoTimeout = true;
            }
            else
            {
                DosePanel.Background = GreenBrush;
                ok.IsSelected = true;
            }

            rv = ep.GetAllDeissue();
            if (rv != 0)
                MessageBox.Show($"GetDoses {rv} er:{ep.GetDosesError}");

            Wearer.Text = $"{ep.WearerName}";
            EpdVisit.Text = $"{ep.WearerID}";

            HpDose07.Text = $"{ep.Hp07Name}: {ep.Hp07:0.00} µSv ";
            HpDose10.Text = $"{ep.Hp10Name}: {ep.Hp10:0.00} µSv";
            if (int.TryParse(ep.WearerID, out int EpdVisitID))
            {
                bool isBG = ep.isBG;

#if SimulateEPD
                ep.CountsClock = 789;
#endif
                var l = new SqlLog();
                try
                {
                    dataInterface.VisitExit(EpdVisitID, ep);
                    l.LogCommand(DataInterface.VisitExitCommand);
                }
                catch (System.Exception ex)
                {
                    l.LogCommand(ex.Message);
                    MessageBox.Show(ex.Message);
                }
                l.Dispose();
            }
            return;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Wait.IsSelected = true;
            dispatcherTimer.Start();
            ResultTime = DateTime.Now.AddMilliseconds(thisStation.EPDTimeOut);
            Dispatcher.InvokeAsync(() => ep.Wait(thisStation.EPDTimeOut, 1), DispatcherPriority.Background);
        }

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

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

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

        public void endWithMessage(string message)
        {
            new InstMessage(message).ShowDialog();
            endPage();
        }

        public void endPage()
        {
            this.Close();
        }
    }
}
