using HBLConsole.DialogWindow.View;
using HBLConsole.Interface;
using HBLConsole.Model;
using HBLConsole.Service;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using BPA.Message.Enum;

namespace HBLConsole.ViewModel
{
    public class DeviceManageViewModel : ViewModelBase
    {
        public DeviceManageViewModel()
        {
            WindowName = "设备管理";

            foreach (var item in Enum.GetNames(typeof(DeviceClientType)))
            {
                ClientDevices.Add(item);
            }

            NewConnectCommand = new RelayCommand(() => { NewConnect(); });

            SaveDeviceData();



            ActionOperate.GetInstance.Register(new Func<object, object>((p) =>
            {
                if (p is DeviceManagermentResult dm)
                {
                    return Json<CommunicationPar>.Data.communicationSets.FirstOrDefault(s => s.DeviceName.ToUpper() == dm.DeviceName.ToUpper()) == null;
                }
                return false;
            }), "AddDeviceVerify");
            ClientDeviceType = Json<SetPar>.Data.ClientDeviceType;
        }

        static DeviceManageViewModel()
        {
            VisibleDeviceData();
        }

        private void SaveDeviceData()
        {
            ActionOperate.GetInstance.Register(new Action(() =>
            {
                var rr = Json<CommunicationPar>.Data.communicationSets.Where(p => p.ClientDeviceType != GVL.GeneralConfig.DeviceType.ToString()).ToList();
                if (rr != null)
                {
                    Json<CommunicationPar>.Data.communicationSets.Clear();
                    rr.ForEach((o) =>
                    {
                        Json<CommunicationPar>.Data.communicationSets.Add(o);
                    });
                }

                foreach (var item in communicationSets)
                {
                    item.RemoveAction = null;
                    Json<CommunicationPar>.Data.communicationSets.Add(item);
                }
                Json<CommunicationPar>.Save();

            }), "DataSave");

        }

        private static void VisibleDeviceData()
        {
            if (communicationSets.Count <= 0)
            {
                Json<CommunicationPar>.Read();
                foreach (var item in Json<CommunicationPar>.Data.communicationSets)
                {
                    if (item.ClientDeviceType == GVL.GeneralConfig.DeviceType.ToString())
                    {
                        item.RemoveAction = RemoveDevice;
                        communicationSets.Add(item);
                    }
                }
            }

        }


        public string ClientDeviceType
        {
            get { return _mClientDeviceType; }
            set { _mClientDeviceType = value; OnPropertyChanged(); Json<SetPar>.Data.ClientDeviceType = value; }
        }
        private string _mClientDeviceType;


        public static ObservableCollection<CommunicationSet> communicationSets { get; set; } = new ObservableCollection<CommunicationSet>();

        public ObservableCollection<string> ClientDevices { get; set; } = new ObservableCollection<string>();

        public RelayCommand NewConnectCommand { get; set; }

        public RelayCommand SaveConnectSetCommand { get; set; }

        /// <summary>
        /// 创建新连接
        /// </summary>
        private void NewConnect()
        {
            DeviceManagermentSetView deviceManagermentSetView = new DeviceManagermentSetView();
            var result = deviceManagermentSetView.ShowDialog();
            var ResultTag = deviceManagermentSetView.Tag as DeviceManagermentResult;
            if (ResultTag != null && result != null)
            {
                if ((bool)result)
                {
                    var obj = communicationSets.FirstOrDefault(p => p.DeviceName == ResultTag.DeviceName);
                    if (obj == null)
                    {
                        CommunicationSet communicationObj = new CommunicationSet();
                        EDeviceType eDeviceType = (EDeviceType)Enum.Parse(typeof(EDeviceType), ResultTag.DeviceType);
                        foreach (var item in Enum.GetNames(typeof(EDeviceTypeSort)))
                        {
                            var res = DeviceTypeSort.GetInstance.DevceTypes[item].FirstOrDefault(p => p == ResultTag.DeviceType);
                            if (res != null)
                            {
                                string device = string.Empty;
                                switch ((EDeviceTypeSort)Enum.Parse(typeof(EDeviceTypeSort), item))
                                {
                                    case EDeviceTypeSort.Siemens:
                                        device = EDeviceType.Siemens.ToString();
                                        break;
                                    case EDeviceTypeSort.TCP:
                                        device = EDeviceType.ModbusTcp.ToString();
                                        break;
                                    case EDeviceTypeSort.Serial:
                                        device = EDeviceType.ModbusRtu.ToString();
                                        break;
                                    default:
                                        break;
                                }

                                string NameSpace = "HBLConsole.Model";//Load 加载的是dll的名称，GetType获取的是全命名空间下的类
                                var type = Assembly.Load(NameSpace)?.GetType($"{NameSpace}.{device}");
                                if (type != null)
                                {
                                    communicationObj.Device = Activator.CreateInstance(type) as IDeviceType;
                                }
                                communicationObj.DeviceName = $"{ResultTag.DeviceName}【{eDeviceType}】";
                                communicationObj.deviceType = eDeviceType;
                                communicationObj.RemoveAction = RemoveDevice;
                                communicationObj.ClientDeviceType = GVL.GeneralConfig.DeviceType.ToString();
                                communicationSets.Add(communicationObj);
                                return;
                            }
                        }


                        //}

                    }
                }
            }
            deviceManagermentSetView = null;
        }

        private static void RemoveDevice(object o)
        {
            int index = Array.FindIndex(communicationSets.ToArray(), p => p.DeviceName == o.ToString());
            if (index >= 0 && index < communicationSets.Count)
            {
                communicationSets.RemoveAt(index);
            }
            //var result = communicationSets.FirstOrDefault(p => p.DeviceName == o.ToString());
            //if (result != null)
            //{
            //    communicationSets.Remove(result);
            //}
        }



    }
}
