using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.ComponentModel;
using FLY.Simulation.Flyad7;
using GalaSoft.MvvmLight.Command;

namespace FLY.Simulation.Calender.GuRuiShiYe.UI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        WdMainVm viewModel;

        public MainWindow()
        {
            InitializeComponent();

            viewModel = new WdMainVm();
            viewModel.Init();
            this.DataContext = viewModel;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            viewModel.Stop();
        }
    }

    public class WdMainVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public FlyADClientUI[] FlyADClientUIs { get; private set; }

        public double TimeSpan1ms { get; set; }

        public int OneSecCnt { get; set; }

        public FLY.Simulation.Calender.GuRuiShiYe.Gage Gage { get; private set; }
        FLY.Simulation.Flyad7.OBJProxy.Flyad7_OBJProxy[] flyad7objProxys;

        public RelayCommand SaveCmd { get; private set; }


        bool bClosed = false;

        public WdMainVm() {
            SaveCmd = new RelayCommand(Save);
        }


        public void Init()
        {
            FObjBase.PollModule.Current.IsAccurate = true;
            int devCnt = 3;
            while(FObjBase.FObjSys.Currents.Count()<devCnt)
                FObjBase.FObjSys.Currents.Add(new FObjBase.FObjSys());

            Gage = new FLY.Simulation.Calender.GuRuiShiYe.Gage();
            Gage.Init(devCnt);
            flyad7objProxys = new FLY.Simulation.Flyad7.OBJProxy.Flyad7_OBJProxy[devCnt];
            for (int i = 0; i < devCnt; i++) {
                flyad7objProxys[i] = new Flyad7.OBJProxy.Flyad7_OBJProxy(i, Gage.FlyAds[i]);
            }
            for (int i = 0; i < devCnt; i++)
            {
                flyad7objProxys[i].Listen();
            }
            var flyADClientUIs = new FlyADClientUI[devCnt];
            for (int i = 0; i < devCnt; i++)
            {
                
                flyADClientUIs[i] = new FlyADClientUI(Gage.FlyAds[i]);
                flyADClientUIs[i].Name = $"设备 No.{i}";
            }
            FlyADClientUIs = flyADClientUIs;

            Thread t = new Thread(OnPoll);
            t.IsBackground = true;
            t.Start();
            //FObjBase.PollModule.Current.Start();
        }

        public void Stop() {
            bClosed = true;
        }
        DateTime dt_cnt = DateTime.MinValue;
        int onesecondcnt = 0;
        TimeSpan ts_1scnt = TimeSpan.Zero;
        void Update1sCnt()
        {
            DateTime d = DateTime.Now;
            if (dt_cnt == DateTime.MinValue)
                dt_cnt = d;
            else
            {
                onesecondcnt++;
                TimeSpan ts = (d - dt_cnt);
                if (ts.TotalMilliseconds >= 1.28)
                {
                    //OneSecCnt = (int)(d - dt_cnt).TotalMilliseconds;// onesecondcnt;
                    OneSecCnt = onesecondcnt;
                    onesecondcnt = 0;
                    dt_cnt = d;
                }
                else
                {
                    ts_1scnt = d - dt_cnt;
                }

            }
        }
        void OnPoll()
        {

            while (true)
            {
                if (bClosed)
                    return;
                timer_Tick(null, null);
                //Update1sCnt();
                Thread.Sleep(0);
            }
        }
        DateTime dt = DateTime.MinValue;
        void UpdateTimeSpan1ms()
        {
            DateTime d = DateTime.Now;
            if (dt == DateTime.MinValue)
                dt = d;
            else
            {
                TimeSpan1ms = (d - dt).TotalMilliseconds;
                dt = d;
            }
        }
        void timer_Tick(object sender, EventArgs e)
        {

            FObjBase.PollModule.Current.OnPoll();
            //UpdateTimeSpan1ms();
        }


        private void Save()
        {
            foreach (var flyAd in Gage.FlyAds)
                flyAd.Save();

            MessageBox.Show("保存成功，请重启");
        }
    }

    public class IO2BinConverter : IValueConverter
    {
        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            UInt16 io = (UInt16)value;
            string str = System.Convert.ToString(io, 2);

            return str.PadLeft(12, '0');
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return 0xffff;

            else 
            {
                string str = value as string;
                UInt16 io;
                if (UInt16.TryParse(str, out io))
                    return io;
                else
                    return 0xffff;
            }

        }

        #endregion
    }


    public class EnumToIsCheckedConverter<TEnum> : IValueConverter
    where TEnum : struct
    {

        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            TEnum type = (TEnum)value;
            if (Enum.GetName(typeof(TEnum), type) == (parameter as string))
                return true;
            else
                return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((bool)value == true)
            {
                return Enum.Parse(typeof(TEnum), (parameter as string));
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
}
