using FLY.OBJComponents.Common;
using FLY.OBJComponents.IService;
using FObjBase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.OBJComponents.Server
{
    /// <summary>
    /// 报警管理系统
    /// </summary>
    public class WarningSystem2 : IWarningSystem2Service
    {
        public event PropertyChangedEventHandler PropertyChanged;

        #region  IWarningSystem2Service

        /// <summary>
        /// 使能
        /// </summary>
        public bool Enable { get; set; }
        /// <summary>
        /// 正在响铃
        /// </summary>
        public bool IsRinging { get; private set; }
        /// <summary>
        /// 当前正在报警的！！！！！！
        /// </summary>
        public FlyData_WarningHistory[] ReasonList { get; private set; }

        /// <summary>
        /// 最后一条数据Id
        /// </summary>
        public long LastId { get; set; }



        #endregion

        /// <summary>
        /// ReasonList 的原始数据， errors 与 ReasonList 需要同步
        /// </summary>
        private List<FlyData_WarningHistory> errors = new List<FlyData_WarningHistory>();
        /// <summary>
        /// 保存到SQL数据库的集成工具
        /// </summary>
        BufferError errorBuffer;
        public WarningSystem2()
        {
            Enable = true;
        }

        public void Init(BufferError errorBuffer) 
        {
            this.errorBuffer = errorBuffer;
            Misc.BindingOperations.SetBinding(this.errorBuffer, nameof(this.errorBuffer.LastId), this, nameof(LastId));
        }

        public void Reset()
        {
            errors.Clear();
            updateReasonList();
        }

        public void Silence()
        {
            IsRinging = false;
        }

        #region IWarningServiceSimple
        public void Add(int errcode, string description)
        {
            Add(errcode, description, ERR_STATE.ON);
        }

        public void Add(int errcode, string description, string accessory)
        {
            Add(errcode, description, ERR_STATE.ON, accessory, false);
        }
        
        public void Add(int errcode, string description, ERR_STATE state)
        {
            Add(errcode, description, state, "", false );
        }


        public void Update(int errcode, string description)
        {
            Update(errcode, description, "");
        }
        public void Update(int errcode, string description, string accessory)
        {
            Add(errcode, description, ERR_STATE.ON, accessory, true);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="errcode">报警码</param>
        /// <param name="description">描述</param>
        /// <param name="state">状态，ON or OFF</param>
        /// <param name="accessory">附加信息</param>
        /// <param name="isUpdate">就算已经存在，也有刷新</param>
        public void Add(int errcode, string description, ERR_STATE state, string accessory, bool isUpdate)
        {
            if (!Enable)
                return;

            if (state == ERR_STATE.OFF)
            {
                Remove(errcode);
                return;
            }

            if (errors.Count > 0)
            {
                //查找是否已经存在
                var error = errors.Find(err => err.ErrCode == errcode);
                if (error != null) {
                    //已经有了
                    if (!isUpdate)
                    {
                        //不需要刷新
                        return;
                    }
                    else {
                        //需要刷新
                        //先把它删除
                        errors.Remove(error);
                    }
                }
            }
            {
                //这是新的记录
                FlyData_WarningHistory error = new FlyData_WarningHistory
                {
                    Time = DateTime.Now,

                    ErrCode = errcode,
                    Description = description,
                    State = state,
                    Accessory = accessory
                };
                errors.Add(error);
                updateReasonList();

                errorBuffer.Add(error);
            }
        }

        void updateReasonList() {
            if (errors.Count() > 0)
                ReasonList = errors.ToArray();
            else
                ReasonList = null;

            IsRinging = errors.Count > 0;
        }
        
        public void Remove(int errcode) {
 

            FlyData_WarningHistory error = null;
            if (errors.Count()==0)
                return;

            //删除！！！！！
            error = errors.Find(err => err.ErrCode == errcode);
            if (error == null)
                return;
            errors.Remove(error);

            updateReasonList();

            errorBuffer.Add(new FlyData_WarningHistory
            {
                Time = DateTime.Now,
                ErrCode = errcode,
                Description = error.Description,
                State = ERR_STATE.OFF
            });
        }
        #endregion


        /// <summary>
        /// 获取纵向趋势图
        /// </summary>
        /// <param name="request"></param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        public void GetTrend(
            Pack_GetTrendRequest request,
            AsyncCBHandler asyncDelegate, object asyncContext)
        {
            errorBuffer.GetTrend(request, asyncDelegate, asyncContext);
        }
    }
}
