using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace eDosStation
{
    /// <summary>
    /// Interaction logic for ShowEPDDose.xaml
    /// </summary>
    public partial class EpdExit: Window
    {
        DataInterface dataInterface;
        Station thisStation;
        EpdBaseClr.Epd2 ep;
        bool EpdFound = false;
        DispatcherTimer dispatcherTimer;
        int Search;
        SolidColorBrush GreenBrush = new SolidColorBrush(Colors.LightGreen);
        SolidColorBrush AlarmBrush = new SolidColorBrush(Colors.LightCoral);

#if SimulateEPD
        public SimulateData simulData = new SimulateData();
#endif
        public EpdExit(EpdBaseClr.Epd2 curEP, Station curStation)
        {
            InitializeComponent();
            ep = curEP;
            thisStation = curStation;
            dataInterface = curStation.dataInterface;
        }

        private void ShowAlarm()
        {
       

        }


        private void LoadDoses()
        {

            if (dispatcherTimer == null)
            {
                dispatcherTimer = new DispatcherTimer();
                dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
            } else
            {
                dispatcherTimer.Tick -= DispatcherTimer_IsEPDFound;
                dispatcherTimer.Stop();
            }
            dispatcherTimer.Tick += DispatcherTimer_WindowTimeoutAndClose; ;

            int rv= ep.GetStatus();
            if (rv != 1)
            {
                int er= ep.GetStatusError;
                MessageBox.Show($"GetStatus {rv} error {er}");
            }

#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

            if (!ep.Issued)
            {
                MessageBox.Show("This EPD is not issued","EDP",MessageBoxButton.OK,MessageBoxImage.Hand,MessageBoxResult.OK,MessageBoxOptions.ServiceNotification);
                this.Close();
                return;
            } else if (ep.EpdID==0)
            {
                MessageBox.Show("This EPD is not read", "EDP", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
            }

            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.ReadExtraStatus();  //D1 BaseD1 ...
            if (rv != 1)
            {
                MessageBox.Show($"ReadExtraStatus {rv}");
            }

            Wearer.Text = $"Wearer: {ep.WearerName}";
            EpdVisit.Text = $"Visit: {ep.WearerID}";
            rv = ep.GetDoses();
            if (rv != 1)
            {
                rv = ep.GetDoses(); //try again
                if (rv != 1)
                    MessageBox.Show($"GetDoses {rv} er:{ep.GetDosesError}");
            }

            HpDose07.Text = $"Hp07: {ep.Hp07:0.00} µSv ";
            HpDose10.Text = $"Hp10: {ep.Hp10:0.00} µSv";
            if (int.TryParse(ep.WearerID, out int EpdVisitID))
            {
                bool isBG = (ep.epdType == 3);
                rv = ep.SetDeIssued(); //includes close
                if (rv != 1)
                {
                    MessageBox.Show($"DeIssueerror {rv}");
                }

#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();
            }
            if (!NoTimeout) dispatcherTimer.Start();  //Knop hide

            //int? EpdVisitID = LocalRemote.LastID();
            //if (EpdVisitID.HasValue)
            //{
            //    ep.WearerName = "Hallo";
            //    ep.WearerID = EpdVisitID.Value.ToString(); ;
            //    ep.Hp07 = 123;
            //    ep.Hp10 = 124;
            //    Wearer.Text = $"Wearer: {ep.WearerName}";
            //    EpdVisit.Text = $"Visit: {ep.WearerID}";
            //    HpDose07.Text = $"Hp07: {ep.Hp07:0.00} µSv ";
            //    HpDose10.Text = $"Hp10: {ep.Hp10:0.00} µSv";
            //    LocalRemote.VisitExit(EpdVisitID.Value, ep);
            //}

            return;
        }

        private void DispatcherTimer_WindowTimeoutAndClose(object sender, EventArgs e)
        {
            dispatcherTimer.Stop();
            this.Close();
        }


        private void StartScan()
        {
            EpdFound = false;
            //ep = new EpdBaseClr.Epd2(thisStation.ComPort);
            int rv = ep.Connect(false);
            System.Diagnostics.Debug.WriteLine($"Connect {rv} error {ep.ConnectError}");
            if (rv==1 && ep.DeviceCount >0 && ep.b.CurrentDeviceID>0)
            {
                EpdFound = true;
                statusEPD.Content = $"StartScan : EPD: {ep.b.CurrentDeviceID}";
                LoadDoses();
            }
            if (!EpdFound)
            {
                statusEPD.Content = $"EPD:  Wait ";
                Search = 100;
                dispatcherTimer = new DispatcherTimer();
                dispatcherTimer.Tick += DispatcherTimer_IsEPDFound;
                dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
                dispatcherTimer.Start();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Wait.IsSelected = true;
            EpdFound = false;
            Dispatcher.InvokeAsync(StartScan);
        }

        private void DispatcherTimer_IsEPDFound(object sender, EventArgs e)
        {
            dispatcherTimer.Stop();
            EpdFound = false;
            
            int rv = ep.Connect(false);
            if (rv==1 && ep.DeviceCount > 0 && ep.b.CurrentDeviceID>0)
            {
                EpdFound = true;
                statusEPD.Content = $"EPD:  {ep.b.CurrentDeviceID}";
                LoadDoses();
            }
            if (!EpdFound)
            {   Search--;
                if (Search > 0)
                {
                    statusEPD.Content = $"Search {Search}";
                    dispatcherTimer.Start();
                }  else
                {
                    statusEPD.Content = $"Search Timeout";
                }
            }
        }

        private void BCloseExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BConfirmAlarm_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (dispatcherTimer?.IsEnabled == true) dispatcherTimer.IsEnabled = false;
            dispatcherTimer = null;
        }
    }
}
