using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleCore.Library;

namespace StandardScene.ExtendDevice.ButtonBox
{
    /// <summary>
    /// 按钮状态枚举
    /// </summary>
    public enum ButtonState
    {
        /// <summary>
        /// 未按下
        /// </summary>
        Released = 0,
        
        /// <summary>
        /// 已按下
        /// </summary>
        Pressed = 1,
        
        /// <summary>
        /// 未知状态
        /// </summary>
        Unknown = 2
    }

    /// <summary>
    /// 按钮盒状态枚举
    /// </summary>
    public enum ButtonBoxState
    {
        /// <summary>
        /// 离线
        /// </summary>
        Offline = 0,
        
        /// <summary>
        /// 在线
        /// </summary>
        Online = 1,
        
        /// <summary>
        /// 连接中
        /// </summary>
        Connecting = 2,
        
        /// <summary>
        /// 错误
        /// </summary>
        Error = 3
    }

    /// <summary>
    /// 基础按钮盒类，包含状态机
    /// </summary>
    public abstract class BasicButtonBox
    {
        /// <summary>
        /// 按钮盒索引
        /// </summary>
        public int Index { get; set; }

        /// <summary>
        /// IP地址
        /// </summary>
        public string Ip { get; set; } = string.Empty;

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// 按钮盒状态
        /// </summary>
        public ButtonBoxState State { get; protected set; } = ButtonBoxState.Offline;

        /// <summary>
        /// 是否在线
        /// </summary>
        public bool IsOnline => State == ButtonBoxState.Online;

        /// <summary>
        /// 按钮状态字典，键为按钮索引
        /// </summary>
        public Dictionary<int, ButtonState> ButtonStates { get; protected set; } = new Dictionary<int, ButtonState>();

        /// <summary>
        /// 按钮配置信息字典，键为按钮索引
        /// </summary>
        public Dictionary<int, ButtonModel> ButtonConfigs { get; protected set; } = new Dictionary<int, ButtonModel>();

        /// <summary>
        /// 按钮动作执行后清零对应寄存器：默认空实现，具体盒型（如 Azowie）按需重写。
        /// 用于解耦 ButtonMission 对具体盒型的 is 判断，便于驱动外移至卫星 dll。
        /// </summary>
        public virtual void ClearButtonRegister(int buttonIndex)
        {
        }

        /// <summary>
        /// 最后更新时间
        /// </summary>
        public DateTime LastUpdateTime { get; protected set; } = DateTime.Now;

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMessage { get; protected set; } = string.Empty;

        /// <summary>
        /// 更新按钮盒状态
        /// </summary>
        public virtual void UpdateState(ButtonBoxState newState, string errorMessage = "")
        {
            State = newState;
            ErrorMessage = errorMessage;
            LastUpdateTime = DateTime.Now;
        }

        /// <summary>
        /// 更新按钮状态
        /// </summary>
        /// <param name="buttonIndex">按钮索引</param>
        /// <param name="state">按钮状态</param>
        public virtual void UpdateButtonState(int buttonIndex, ButtonState state)
        {
            bool hadPrev = ButtonStates.TryGetValue(buttonIndex, out var previous);
            if (hadPrev && previous == state)
                return;

            ButtonStates[buttonIndex] = state;
            if (hadPrev)
                Diagnosis.Post($"按钮盒{Index}_按钮{buttonIndex}:状态变更为{state}", "ButtonBox", false);
            LastUpdateTime = DateTime.Now;
        }

        /// <summary>
        /// 获取按钮状态
        /// </summary>
        /// <param name="buttonIndex">按钮索引</param>
        /// <returns>按钮状态，如果不存在则返回Unknown</returns>
        public virtual ButtonState GetButtonState(int buttonIndex)
        {
            return ButtonStates.TryGetValue(buttonIndex, out var state) ? state : ButtonState.Unknown;
        }

        /// <summary>
        /// 初始化按钮状态
        /// </summary>
        /// <param name="buttonIndices">按钮索引列表</param>
        public virtual void InitializeButtons(List<int> buttonIndices)
        {
            ButtonStates.Clear();
            foreach (var index in buttonIndices)
            {
                ButtonStates[index] = ButtonState.Released;
            }
        }

        /// <summary>
        /// 初始化按钮配置信息
        /// </summary>
        /// <param name="buttonConfigs">按钮配置列表</param>
        public virtual void InitializeButtonConfigs(List<ButtonModel> buttonConfigs)
        {
            ButtonConfigs.Clear();
            if (buttonConfigs != null)
            {
                foreach (var config in buttonConfigs)
                {
                    ButtonConfigs[config.Index] = new ButtonModel
                    {
                        Index = config.Index,
                        TriggerMission = config.TriggerMission,
                        TriggerMethod = config.TriggerMethod,
                        TriggerMethodParams = config.TriggerMethodParams,
                        TriggerState = config.TriggerState,
                        TriggerDelay = config.TriggerDelay
                    };
                }
            }
        }

        /// <summary>
        /// 更新按钮配置信息
        /// </summary>
        /// <param name="buttonConfigs">按钮配置列表</param>
        public virtual void UpdateButtonConfigs(List<ButtonModel> buttonConfigs)
        {
            if (buttonConfigs == null)
            {
                ButtonConfigs.Clear();
                return;
            }

            // 创建配置字典
            var configDict = buttonConfigs.ToDictionary(b => b.Index);

            // 删除配置中不存在的按钮
            var toRemove = ButtonConfigs.Keys.Where(k => !configDict.ContainsKey(k)).ToList();
            foreach (var key in toRemove)
            {
                ButtonConfigs.Remove(key);
            }

            // 添加或更新按钮配置
            foreach (var config in buttonConfigs)
            {
                ButtonConfigs[config.Index] = new ButtonModel
                {
                    Index = config.Index,
                    TriggerMission = config.TriggerMission,
                    TriggerMethod = config.TriggerMethod,
                    TriggerMethodParams = config.TriggerMethodParams,
                    TriggerState = config.TriggerState,
                    TriggerDelay = config.TriggerDelay
                };
            }
        }

        /// <summary>
        /// 获取按钮配置信息
        /// </summary>
        /// <param name="buttonIndex">按钮索引</param>
        /// <returns>按钮配置信息，如果不存在则返回null</returns>
        public virtual ButtonModel GetButtonConfig(int buttonIndex)
        {
            return ButtonConfigs.TryGetValue(buttonIndex, out var config) ? config : null;
        }

        /// <summary>
        /// 连接按钮盒
        /// </summary>
        public virtual void Connect()
        {
            UpdateState(ButtonBoxState.Connecting);
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public virtual void Disconnect()
        {
            UpdateState(ButtonBoxState.Offline);
        }

        /// <summary>
        /// 当与此按钮盒绑定的业务方法执行完成后触发的回调。
        /// 子类可重写以实现按钮灯反馈、蜂鸣等效果。
        /// </summary>
        /// <param name="buttonConfig">触发本次调用的按钮配置</param>
        /// <param name="isSuccess">业务方法是否执行成功</param>
        public virtual void OnActionExecuted(ButtonModel buttonConfig, bool isSuccess)
        {
            // 基类默认不做任何事，由具体实现按需要重写
        }
    }
}
