using MessagePack;
using SHH.Contracts;
using System.Diagnostics;

namespace SHH.CameraDashboard.Services.Processors
{
    /// <summary>
    /// [协议处理器] 处理来自服务端的反向指令 (COMMAND)
    /// 场景：服务端主动要求客户端执行某些动作（如弹出实时画面、同步系统配置等）
    /// </summary>
    public class CommandProcessor : IProtocolProcessor
    {
        public string ProtocolType => "COMMAND";
        private readonly CommandBusClient _bus;

        public CommandProcessor(CommandBusClient bus)
        {
            _bus = bus;
        }

        public void Process(byte[] identity, byte[] payloadBytes)
        {
            try
            {
                // 1. 反序列化指令载体
                var payload = MessagePackSerializer.Deserialize<CommandPayload>(payloadBytes);
                if (payload == null) return;

                // 2. 核心：触发总线上的指令接收事件
                // 让监听该事件的 ViewModel 或全局管理器去执行具体业务
                _bus.RaiseCommandReceived(payload);

                Debug.WriteLine($"[Bus] 收到服务端反向指令: {payload.CmdCode}, 目标: {payload.TargetId}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[Bus-Err] CommandProcessor 解析异常: {ex.Message}");
            }
        }
    }
}