using BOB.Singleton;
using DeviceCommand.Device;
using Logger;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;

namespace BOB.ViewModels.Dialogs
{
    public class IOBoardViewModel : BindableBase, IDialogAware
    {
        public enum Address : ushort
        {
            ushort0 = 0,
            ushort1 = 1,
            ushort2 = 2,
            ushort3 = 3,
            ushort4 = 4,
            ushort5 = 5,
            ushort6 = 6,
            ushort7 = 7,
            ushort8 = 8,
            ushort9 = 9,
            ushort10 = 10,
            ushort11 = 11,
            ushort12 = 12,
            ushort13 = 13,
            ushort14 = 14,
            ushort15 = 15
        }
        #region 属性
        private string _title = "IO板卡";

        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        private string _offset="0";
        public string Offset
        {
            get { return _offset; }
            set { SetProperty(ref _offset, value); }
        }

        private string _batchWriteStatus;
        public string BatchWriteStatus
        {
            get { return _batchWriteStatus; }
            set { SetProperty(ref _batchWriteStatus, value); }
        }
        private Address _SelectedAddress;
        public Address SelectedAddress
        {
            get { return _SelectedAddress; }
            set { SetProperty(ref _SelectedAddress, value); }
        }
        private List<Address> _AddressList=Enum.GetValues(typeof(Address)).Cast<Address>().ToList();
        public List<Address> AddressList 
        {
            get { return _AddressList; }
            set { SetProperty(ref _AddressList, value); }
        }

        #endregion

        #region 命令

        public ICommand ConnectCommand { get; private set; }
        public ICommand DisconnectCommand { get; private set; }
        public ICommand PowerOnCommand { get; private set; }
        public ICommand PowerOffCommand { get; private set; }
        public ICommand SetCommand { get; private set; }
        public ICommand ReadCommand { get; private set; }
        public ICommand CloseCommand { get; private set; }

        #endregion


        private IEventAggregator _eventAggregator { get; set; }
        private Devices _devices { get; set; }
        private IOBoard device { get; set; }
        private GlobalVariables _globalVariables { get; set; }
        public IOBoardViewModel(IContainerProvider containerProvider)
        {
            _devices = containerProvider.Resolve<Devices>();
            _globalVariables = containerProvider.Resolve<GlobalVariables>();
            _eventAggregator = containerProvider.Resolve<IEventAggregator>();
            ConnectCommand = new AsyncDelegateCommand(OnConnect);
            DisconnectCommand = new DelegateCommand(OnDisconnect);
            PowerOnCommand = new AsyncDelegateCommand(OnPowerOn);
            PowerOffCommand = new AsyncDelegateCommand(OnPowerOff);
            SetCommand = new AsyncDelegateCommand(OnSet);
            ReadCommand = new AsyncDelegateCommand(OnRead);
            CloseCommand = new DelegateCommand(OnClose);
        }


        private async Task OnConnect()
        {
            await device.ConnectAsync();
        }

        private void OnDisconnect()
        {
            device.Close();
        }

        private async Task OnPowerOn()
        {
            await device.写输出开关(1, (ushort)SelectedAddress, true);
        }

        private async Task OnPowerOff()
        {
            await device.写输出开关(1, (ushort)SelectedAddress, false);
        }

        private async Task OnSet()
        {
            bool[] statusArray = JsonConvert.DeserializeObject<bool[]>(BatchWriteStatus);

            if (ushort.TryParse(Offset, out ushort offset))
            {
                if (statusArray==null||statusArray.Length+offset>16||statusArray.Length<=0||offset<0)
                {
                    LoggerHelper.Error("BatchWriteStatus 数组内容不符合预期");
                    return;
                }
                await device.批量写输出开关(1, offset, System.Text.Json.JsonSerializer.Deserialize<bool[]>(BatchWriteStatus));
            }
            else
            {
                LoggerHelper.Error("BatchWriteStatus 数组内容不符合预期");
            }
        }

        private async Task OnRead()
        {
            if (ushort.TryParse(Offset, out ushort offset)) 
            {
                BatchWriteStatus = System.Text.Json.JsonSerializer.Serialize( await device.批量读输出开关(1, offset, 16));
            }
            else
            {
                LoggerHelper.Error("Offset 解析失败，确保其是有效的数字！");
            }
        }
        private void OnClose()
        {
            RequestClose.Invoke();
        }
        #region dialog规范
        public DialogCloseListener RequestClose { get; set; }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            try
            {
                var a = _devices.DeviceDic["IOBoard"] as IOBoard;
                if (a != null)
                {
                    device = a;
                }
                else
                {
                    LoggerHelper.ErrorWithNotify("设备没有初始化无法打开测试界面");
                    RequestClose.Invoke();
                }
            }
            catch (Exception)
            {
                LoggerHelper.ErrorWithNotify("找不到设备无法打开测试界面");
            }

        }
        #endregion
    }
}
