using System;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace eDosStation
{
    /// <summary>
    /// Interaction logic for ShowEPDDose.xaml
    /// </summary>
    public partial class ShowEPDDose : Window
    {
        Station thisStation;
        EpdBaseClr.Epd2 ep;
        DispatcherTimer dispatcherTimer;
        private DateTime ResultTime;
        private User thisUser;

        public ShowEPDDose(Station curStation)
        {
            InitializeComponent();
            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;

            dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(thisStation.EPDTimeOut / 10);
            Progress.Maximum = Progress.Value = dispatcherTimer.Interval.TotalSeconds * 10;
            dispatcherTimer.Tick += CountDown;

        }

        private void CountDown(object sender, EventArgs e)
        {
            double v = (ResultTime - DateTime.Now).TotalSeconds;
            if (v > Progress.Minimum)
            {
                Progress.Value = v;
                ProgressText.Text = ((int)v).ToString();
            }
            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 {e.returnValue}");
                endPage();
            });
        }

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

        private void LoadDoses()
        {
            int rv = 0;
            rv = ep.GetAll(true);

            if (rv != 0) MessageBox.Show("Communication  error");



            isIssued.Text = ep.EPDIssued ? "Yes" : "no";
            string sPersID = ep.WearerName.Trim();
            Wearer.Text = sPersID;
            EpdVisit.Text = ep.WearerID.ToString();

            HardVersion.Text = ep.HardVersion.ToString() + '.' + ep.SoftVersion.ToString();

            if (ep.hasAlarm)
            {
                hasAlarm.Text = "Yes";
            } else
                hasAlarm.Text = "no";

            epdid.Text = ep.EpdID.ToString();
            var stype = new StringBuilder();
            if (ep.isMK3) stype.Append("MK3 "); else stype.Append("MK2 ");
            if (ep.isBG) stype.Append(" BG"); else stype.Append(" NG");
            epdtype.Text = stype.ToString();

            Decoder.AlarmToTextBox(sAlarm, ep);

            HpDose07l.Text = ep.Hp07Name;
            HpDose10l.Text = ep.Hp10Name;

            HpDose07.Text = $"{ep.Hp07:0.00} µSv";
            HpDose10.Text = $"{ep.Hp10:0.00} µSv";

            HP10AlarmDose1l.Text = "Warning "+ ep.Hp10Name;
            HP10AlarmDose2l.Text = "Alarm "+ ep.Hp10Name;
            HP07AlarmDosel.Text = "Alarm "+ ep.Hp07Name;

            HP10AlarmDose1.Text = $"{ep.Hp10THDose1:0.00} µSv";
            HP10AlarmDose2.Text = $"{ep.Hp10THDose2:0.00} µSv";
            HP07AlarmDose.Text = $"{ep.Hp07THDose:0.00} µSv";

            if (ep.isNG) { 
                lNGain.Visibility = NGain.Visibility = Visibility.Visible;
                NGain.Text = ep.NGgain.ToString();
            } else {
                lNGain.Visibility = NGain.Visibility = Visibility.Hidden;
            }
            
            

            if (!string.IsNullOrEmpty(sPersID))
            {
                try
                {
                    thisUser = thisStation.dataInterface.GetUser(string.Empty, sPersID);
                    epdUserMargin.Text = thisUser.Margin.ToString();
                }
                catch 
                {
                }

            }
            else
                epdUserMargin.Text = "--";

         
        }

       

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

        private void endPage()
        {
            dispatcherTimer?.Stop();
            try
            {
                if (ep != null)
                {
                    ep.WaitEnd();
                    ep.Dispose();
                }
            } catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            this.Close();
        }
       
        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            endPage();
        }

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