using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using HBLConsole.Model;
using HBLConsole.Service;

namespace HBLConsole.ViewModel
{
    internal class VariableConfig : ObservableObject
    {
        public VariableConfig()
        {
            ActionOperate.GetInstance.Register(new Action(() => { SaveDataAsync(); }), "VariableSave");
            ActionOperate.GetInstance.Register(new Action<object>((o) =>
            {
                if (o is int p)
                {
                    if ((p - 1) >= 0)
                    {
                        if (varialeInfos?.Count >= p)
                        {
                            if (varialeInfos.ElementAt(p - 1).VarName != null)
                            {
                                if (varialeInfos.ElementAt(p - 1).VarName.Length > 0)
                                {
                                    if (varialeInfos.Count == p) AddRow();
                                }
                            }
                        }
                    }
                }
            }), "VarNameChanged");

        }

        static VariableConfig()
        {
            GetLocalDataAsync();
        }

        /// <summary>
        /// 异步获取本地数据
        /// </summary>
        private static Task<bool> GetLocalDataAsync()
        {
            var DataList = SqlHelper.GetInstance.GetData();
            App.Current.Dispatcher.Invoke(new Action(() => { varialeInfos.Clear(); }));
            foreach (var item in DataList)
            {
                PropBindInfo propBindInfo = new PropBindInfo();
                propBindInfo.ID = item.ID;
                propBindInfo.VarName = item.VarName;
                propBindInfo.Address = item.Address;
                propBindInfo.DataType = item.DataType;
                propBindInfo.IsEnableAlarm = item.IsEnableAlarm;
                propBindInfo.CurrentValue = item.CurrentValue;
                var result = item.AlarmSetProp.AnalogAlarmModels.Where(p => p.AlarmSetId == item.ID).ToList();
                result = result?.OrderBy(p => p.SortTag).ToList();
                propBindInfo.AlarmSetProp.AnalogAlarmModels.Clear();
                result?.ForEach(p => { propBindInfo.AlarmSetProp.AnalogAlarmModels.Add(p); });
                propBindInfo.AlarmSetProp.DiscreteAlarmInfoSet = item.AlarmSetProp.DiscreteAlarmInfoSet;
                App.Current?.Dispatcher.Invoke(new Action(() => { varialeInfos.Add(propBindInfo); }));
            }
            if (varialeInfos.Count <= 0) AddRow();
            return Task.FromResult(true);
        }

        /// <summary>
        /// 异步保存数据
        /// </summary>
        /// <returns></returns>
        private Task<bool> SaveDataAsync()
        {
            if (varialeInfos.Count > 0)
            {
                if (varialeInfos.ElementAt(0).VarName?.Trim()?.Length > 0)
                {
                    SqlHelper.GetInstance.DbObj.RemoveRange(SqlHelper.GetInstance.DbObj.ToArray());
                    SqlHelper.GetInstance.Save();
                    foreach (var item in varialeInfos)
                    {
                        SqlHelper.GetInstance.Add(new VariableInfo()
                        {
                            ID = item.ID,
                            VarName = item.VarName,
                            Address = item.Address,
                            DataType = item.DataType,
                            IsEnableAlarm = item.IsEnableAlarm,
                            CurrentValue = item.CurrentValue,
                            AlarmSetProp = item.AlarmSetProp,

                        });
                    }
                }
            }
            //SqlHelper.GetInstance.Save();
            return Task.FromResult(true);
        }

        /// <summary>
        /// 添加行
        /// </summary>
        private static void AddRow()
        {
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                string address = string.Empty;
                string dataType = string.Empty;
                int index = varialeInfos.Count - 2;
                if (index >= 0)
                {
                    if (int.TryParse(varialeInfos[varialeInfos.Count - 2].Address, out int res))
                    {
                        res++;
                        address = res.ToString();
                    }
                    dataType = varialeInfos[index].DataType;
                }
                if (varialeInfos.Count > 0)
                {
                    varialeInfos[varialeInfos.Count - 1].Address = address;
                    varialeInfos[varialeInfos.Count - 1].DataType = dataType;
                }
                varialeInfos.Add(new PropBindInfo()
                {
                    ID = varialeInfos.Count + 1,
                });
            }));

        }

        /// <summary>
        /// 变量信息
        /// </summary>
        public static ObservableCollection<PropBindInfo> varialeInfos { get; set; } = new ObservableCollection<PropBindInfo>();

    }
}
