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

namespace StandardScene.ExtendDevice.ButtonBox
{
    public class LeegButtonBox : BasicButtonBox
    {
        /// <summary>
        /// LeegKey设备实例
        /// </summary>
        private LeegKeyDevice _device;

        /// <summary>
        /// 同步锁
        /// </summary>
        private readonly object _syncLock = new object();

        /// <summary>
        /// 是否已启动
        /// </summary>
        private bool _isStarted = false;

        /// <summary>
        /// 连接按钮盒
        /// </summary>
        public override void Connect()
        {
            lock (_syncLock)
            {
                if (_isStarted)
                {
                    return;
                }

                try
                {
                    UpdateState(ButtonBoxState.Connecting);

                    // 创建LeegKey设备实例
                    _device = new LeegKeyDevice(Ip, Port);

                    // 设置事件回调，使用Index作为userData
                    _device.setEventCallback(OnLeegKeyEvent, Index);
                    _device.autoHeartbeatEnable(2,5);
                    // 启动设备
                    _device.start(true);

                    _isStarted = true;
                    UpdateState(ButtonBoxState.Online);
                }
                catch (Exception ex)
                {
                    UpdateState(ButtonBoxState.Error, $"连接失败: {ex.Message}");
                    _isStarted = false;
                }
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public override void Disconnect()
        {
            lock (_syncLock)
            {
                if (!_isStarted || _device == null)
                {
                    return;
                }

                try
                {
                    _device.stop();
                    _device = null;
                    _isStarted = false;
                    UpdateState(ButtonBoxState.Offline);
                }
                catch (Exception ex)
                {
                    UpdateState(ButtonBoxState.Error, $"断开连接失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// LeegKey事件回调
        /// </summary>
        private void OnLeegKeyEvent(LeegKeyEvent evt, object msg, object userData)
        {
            try
            {
                switch (evt)
                {
                    case LeegKeyEvent.KEY_HIT:
                        HandleKeyHit((LeegKeyMsgKey)msg);
                        break;

                    case LeegKeyEvent.STATUS_REP:
                        HandleStatusReport((LeegKeyMsgStatus)msg);
                        break;

                    case LeegKeyEvent.TIME:
                        // 时间同步事件，可以用于保持连接状态
                        UpdateState(ButtonBoxState.Online);
                        break;

                    case LeegKeyEvent.LOG:
                        // 日志事件，可以用于调试
                        HandleLogEvent((LeegKeyMsgLog)msg);
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                UpdateState(ButtonBoxState.Error, $"处理事件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理按键按下事件
        /// </summary>
        private void HandleKeyHit(LeegKeyMsgKey msg)
        {
            var keyTag= msg.content.keys[0].First();
            var buttonIndexStr = keyTag.Key.Substring(3);
            if(!int.TryParse(buttonIndexStr,out var buttonIndex))
                return;
            switch (keyTag.Value)
            {
                case "up":
                    UpdateButtonState(buttonIndex,ButtonState.Released);
                    break;
                case "down":
                    UpdateButtonState(buttonIndex,ButtonState.Pressed);
                    break;
            }
        }

        /// <summary>
        /// 处理状态报告事件
        /// </summary>
        private void HandleStatusReport(LeegKeyMsgStatus msg)
        {
            // 状态报告表示设备在线
            UpdateState(ButtonBoxState.Online);
        }

        /// <summary>
        /// 处理日志事件
        /// </summary>
        private void HandleLogEvent(LeegKeyMsgLog msg)
        {
            // 可以根据日志内容更新状态
            // 这里可以根据实际需求实现
        }


        /// <summary>
        /// 设置按钮灯光
        /// </summary>
        /// <param name="buttonIndex">按钮索引</param>
        /// <param name="rgb">RGB颜色值</param>
        public void SetButtonLight(int buttonIndex, Rgb rgb)
        {
            lock (_syncLock)
            {
                if (!_isStarted || _device == null)
                {
                    return;
                }

                try
                {
                    _device.lightSet(rgb, buttonIndex);
                }
                catch (Exception ex)
                {
                    Diagnosis.Log($"设置按钮灯光失败: {ExceptionFormatter.FormatEx(ex)}", "LeegButtonBox", true);
                }
            }
        }

        /// <summary>
        /// 控制IO输出
        /// </summary>
        /// <param name="content">IO控制内容</param>
        public void ControlIO(IoctrlContent content)
        {
            lock (_syncLock)
            {
                if (!_isStarted || _device == null)
                {
                    return;
                }

                try
                {
                    _device.ioctrl(content);
                }
                catch (Exception ex)
                {
                    Diagnosis.Log($"控制IO失败: {ExceptionFormatter.FormatEx(ex)}", "LeegButtonBox", true);
                }
            }
        }

        /// <summary>
        /// 析构函数，确保资源释放
        /// </summary>
        ~LeegButtonBox()
        {
            Disconnect();
        }
    }
}
