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.Shapes;
using FlyADBase;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using Microsoft.Win32;
using System.IO;
using Newtonsoft.Json;

namespace Flyad7_WPF
{
    /// <summary>
    /// Window_sync.xaml 的交互逻辑
    /// </summary>
    public partial class Window_sync : Window, INotifyPropertyChanged
    {
        public static bool HasOpen = false;
        IFlyADClient flyad;
        AutoSync mAutoSync;
        public Window_sync()
        {
            InitializeComponent();


        }

        public void Init(IFlyADClient flyad, AutoSync mAutoSync)
        {
            this.flyad = flyad;
            this.mAutoSync = mAutoSync;
            textBlock_pos1LCShift.DataContext = this.flyad;
            textBlock_pos2Comp.DataContext = this.flyad;
            textBlock_position2.DataContext = this.flyad;
            textBlock_marker.DataContext = this.flyad;
           
            groupBox_syncRunAtLC.DataContext = mSyncOrder_SyncRunAtLC;
            groupBox_syncOrigin.DataContext = mSyncOrder_SyncOrigin;
            groupBox_syncRunTo.DataContext = mSyncOrder_SyncRunTo;
            groupBox_syncRunToLC.DataContext = mSyncOrder_SyncRunToLC;
            groupBox_syncWait.DataContext = mSyncOrder_SyncWait;

            groupBox9.DataContext = this;

            listView1.ItemsSource = flyad.SyncOrders;


            //自动..........................

            tabItem2.DataContext = mAutoSync;
            stackpanel_SamplePos_Backw.DataContext = mAutoSync.SamplePos_Backw;
            stackpanel_SamplePos_Forw.DataContext = mAutoSync.SamplePos_Forw;
        }



        #region 参数



        public int Pos1LCShift { get; set; }



        public int Position2 { get; set; }
        

        public int Pos2Shift { get; set; }

        public float Pos2Comp { get; set; }


        public int Distance { get; set; }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        private void button_setPos1LCShift_Click(object sender, RoutedEventArgs e)
        {
            flyad.Pos1LCShift = Pos1LCShift;
            MessageBox.Show("flyad.Pos1LCShift = " + Pos1LCShift.ToString());
        }

        private void button_setPosition2_Click(object sender, RoutedEventArgs e)
        {
            flyad.Position2 = Position2;
            MessageBox.Show("flyad.Position2 = " + Position2.ToString());
        }

        private void button_setPos2Shift_Click(object sender, RoutedEventArgs e)
        {
            flyad.SetPos2Offset(Pos2Shift);
            MessageBox.Show("flyad.SetPos2Offset( " + Pos2Shift.ToString() + ")");
        }

        private void button_setPos2At01_Click(object sender, RoutedEventArgs e)
        {
            bool i = (bool)checkbox_immediately.IsChecked;
            flyad.SetPos2At01(Position2, i);
            MessageBox.Show("flyad.SetPos2At01(" + Position2 + ")");
        }

        private void button_pos2comp_Click(object sender, RoutedEventArgs e)
        {
            flyad.Pos2Comp = Pos2Comp;
            MessageBox.Show("flyad.Pos2Comp = " + Pos2Comp.ToString() );
        }




        private void button_clear_Click(object sender, RoutedEventArgs e)
        {
            flyad.SyncClear();
            MessageBox.Show("flyad.SyncClear()");
        }

        private void button_syncBegin_Click(object sender, RoutedEventArgs e)
        {
            flyad.SyncBegin(Distance);
            MessageBox.Show("flyad.SyncBegin(" + Distance.ToString()+")");
        }

        private void button_syncEnd_Click(object sender, RoutedEventArgs e)
        {
            flyad.SyncEnd();
            MessageBox.Show("flyad.SyncEnd()");
        }

        private void button_pos2clear_Click(object sender, RoutedEventArgs e)
        {
            flyad.SyncPos2Clear();
            MessageBox.Show("flyad.SyncPos2Clear()");
        }

        private void button_begin2_Click(object sender, RoutedEventArgs e)
        {
            flyad.SyncBegin();
            MessageBox.Show("flyad.SyncBegin()");
        }



        #region 手动指令
        SyncOrder_SyncRunAtLC mSyncOrder_SyncRunAtLC = new SyncOrder_SyncRunAtLC();
        SyncOrder_SyncOrigin mSyncOrder_SyncOrigin = new SyncOrder_SyncOrigin();
        SyncOrder_SyncRunTo mSyncOrder_SyncRunTo = new SyncOrder_SyncRunTo();
        SyncOrder_SyncRunToLC mSyncOrder_SyncRunToLC = new SyncOrder_SyncRunToLC();
        SyncOrder_SyncWait mSyncOrder_SyncWait = new SyncOrder_SyncWait();

        private void button_addSyncRunAtLC_Click(object sender, RoutedEventArgs e)
        {
            mSyncOrder_SyncRunAtLC.Add(flyad);
        }

        private void button_addSyncOrigin_Click(object sender, RoutedEventArgs e)
        {
            mSyncOrder_SyncOrigin.Add(flyad);
        }

        private void button_addSyncWait_Click(object sender, RoutedEventArgs e)
        {
            mSyncOrder_SyncWait.Add(flyad);
        }

        private void button_addSyncRunTo_Click(object sender, RoutedEventArgs e)
        {
            mSyncOrder_SyncRunTo.Add(flyad);
        }

        private void button_addSyncRunToLC_Click(object sender, RoutedEventArgs e)
        {
            mSyncOrder_SyncRunToLC.Add(flyad);
        }
        #endregion

        #region 自动指令
        private void button_init_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.InitSyncParam();
        }

        private void button_go_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.Start();
        }
        private void button_pos2sync1_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.SetVSensor();
        }
        private void button_pos2sync0_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.ClearVSensor();
        }
        #endregion

        private void button_graph_Click(object sender, RoutedEventArgs e)
        {
            Window_sync_graph w = new Window_sync_graph();
            w.Init(flyad);
            w.Show();
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            HasOpen = true;
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            HasOpen = false;
        }

        private void button_save_autosync_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.Save();
        }

        private void button_stop_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.Stop();
        }

        private void button_test_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.StartTest();
        }

        private void button_teststop_Click(object sender, RoutedEventArgs e)
        {
            mAutoSync.StopTest();
        }

        private void button_save_Click(object sender, RoutedEventArgs e)
        {
            if (flyad.SyncOrders.Count() == 0)
            {
                MessageBox.Show("没有任何一条指令","错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var syncOrderJsonDBs =
                (from o in flyad.SyncOrders
                 select
                     new SyncOrderJsonDB()
                     {
                         type = o.GetType().Name,
                         syncOrderJson = Newtonsoft.Json.JsonConvert.SerializeObject(o)
                     }).ToList();

            if (!Directory.Exists("sync_order_list"))
            {
                Directory.CreateDirectory("sync_order_list");
            }

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = System.Environment.CurrentDirectory + @"\sync_order_list";
            sfd.AddExtension = true;
            sfd.DefaultExt = ".json";
            if (sfd.ShowDialog() == true)
            {
                try
                {
                    File.WriteAllText(sfd.FileName, JsonConvert.SerializeObject(syncOrderJsonDBs, Formatting.Indented));

                }
                catch(Exception _e)
                {
                    //异常，没有json 编码失败
                    MessageBox.Show(_e.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                MessageBox.Show($"保存 {syncOrderJsonDBs.Count()}条同步指令 到 {sfd.FileName}", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            
        }

        private void button_load_Click(object sender, RoutedEventArgs e)
        {
            List<Type> ordertypes = new List<Type> {
                typeof(SyncOrder_SyncRunAtLC),
                typeof(SyncOrder_SyncOrigin),
                typeof(SyncOrder_SyncRunTo),
                typeof(SyncOrder_SyncRunToLC),
                typeof(SyncOrder_SyncWait)
            };

            if (!Directory.Exists("sync_order_list"))
            {
                Directory.CreateDirectory("sync_order_list");
            }

            OpenFileDialog ofd = new OpenFileDialog();
            
            ofd.InitialDirectory = System.Environment.CurrentDirectory+@"\sync_order_list";
            ofd.Filter = "json|*.json";
            if (ofd.ShowDialog() == true)
            {
                try
                {
                    List<SyncOrder> syncorders = new List<SyncOrder>();
                    string json = File.ReadAllText(ofd.FileName);
                    var syncOrderJsonDBs = JsonConvert.DeserializeObject<List<SyncOrderJsonDB>>(json);
                    foreach(var syncOrderJsonDB in syncOrderJsonDBs)
                    {
                        Type t = ordertypes.Find(type => type.Name == syncOrderJsonDB.type);
                        if (t == null)
                        {
                            MessageBox.Show($"{syncOrderJsonDB.type} 不能识别", "异常", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        var syncorder = JsonConvert.DeserializeObject(syncOrderJsonDB.syncOrderJson, t) as SyncOrder;
                        syncorders.Add(syncorder);
                    }


                    flyad.SyncClear();
                    foreach (var syncorder in syncorders)
                    {
                        syncorder.Add(flyad);
                    }
                    MessageBox.Show($"加载 {syncorders.Count()}条同步指令", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                catch(Exception _e)
                {
                    //异常，没有json 解码失败
                    MessageBox.Show($"{_e.Message}", "异常", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
        }
    }

    public class SyncOrderJsonDB
    {
        public string type;
        public string syncOrderJson;
    }




}

