using Newtonsoft.Json;
using System.Net.Sockets;
using System.Text;

namespace SHH.MjpegPlayer
{
    /// <summary>
    /// MJPEG HTTP命令类
    /// </summary>
    public class MjpegHttpCmd
    {
        #region DoHttpCmd

        public static bool DoHttpCmd(NetworkStream stream,
            SessionInfo Info, string Cmd)
        {
            try
            {
                switch (Cmd)
                {
                    case "view":
                        Info.Message = "执行 view 命令.";
                        DoHttpCmdView(stream, Info);
                        return true;

                    case "task":
                        Info.Message = "执行 task 命令.";
                        DoHttpCmdTask(stream, Info);
                        return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                SendJson(stream, $"Command Failed: {ex.Message}", 400);
                return true;
            }
        }

        #endregion

        #region DoHttpCmdView

        private static void DoHttpCmdView(NetworkStream stream, SessionInfo Info)
        {
            var sessions = new List<SessionInfo>();
            int iSessionCount = 0;

            var allSessions = MjpegStatics.Sessions.GetAllSessionInfos();

            foreach (var sessionInfo in allSessions)
            {
                if (sessionInfo == null) continue;

                if (!string.IsNullOrEmpty(Info.DeviceId))
                {
                    if (!string.IsNullOrEmpty(sessionInfo.DeviceId)
                        && !sessionInfo.DeviceId.Equals(Info.DeviceId))
                        continue;
                }

                if (!string.IsNullOrEmpty(Info.TypeCode))
                {
                    if (!string.IsNullOrEmpty(sessionInfo.TypeCode)
                        && !sessionInfo.TypeCode.Equals(Info.TypeCode))
                        continue;
                }

                iSessionCount++;
                sessions.Add(sessionInfo);
            }

            var chns = new List<ImageChannel>();
            var imgChns = MjpegStatics.ImageChannels;
            int iImgChanCount = 0;

            foreach (var kvp in imgChns.Channels)
            {
                var imgChannel = kvp.Value;
                if (imgChannel == null) continue;

                if (!string.IsNullOrEmpty(Info.DeviceId))
                {
                    if (!imgChannel.DeviceId.ToString().Equals(Info.DeviceId))
                        continue;
                }

                if (!string.IsNullOrEmpty(Info.TypeCode))
                {
                    if (!imgChannel.Type.Equals(Info.TypeCode))
                        continue;
                }

                iImgChanCount++;
                chns.Add(imgChannel);
            }

            var result = new
            {
                webAccessCount = iSessionCount,
                deviceChannelCount = iImgChanCount,
                webAccessItems = sessions,
                deviceChannels = chns
            };

            SendJson(stream, JsonConvert.SerializeObject(result, Formatting.Indented));
        }

        #endregion

        #region DoHttpCmdTask

        private static void DoHttpCmdTask(NetworkStream stream, SessionInfo Info)
        {
            // [Optimized]: 直接从 TaskManager 获取实时任务快照，避免遍历旧的静态字典
            var activeTasks = TaskManager.RunningTasks.Values.ToList();

            int iTaskCount = activeTasks.Count;
            int iMjpegServerListenCount = activeTasks.Count(t => t.Name.Contains("MjpegServer-"));

            var result = new
            {
                taskCount = iTaskCount,
                portListenCount = iMjpegServerListenCount,
                // 映射为前端需要的格式
                taskItems = activeTasks.Select(t => new { t.Name, t.Type })
            };

            // 使用 Newtonsoft.Json 或 System.Text.Json 输出
            SendJson(stream, JsonConvert.SerializeObject(result, Formatting.Indented));
        }

        #endregion

        #region Helper

        private static void SendJson(NetworkStream stream, string json, int code = 200)
        {
            try
            {
                string statusLine = code == 200 ? "200 OK" : "400 Bad Request";

                // [修复] 添加 CORS 头，允许诊断页面跨域访问
                byte[] response = Encoding.UTF8.GetBytes(
                    $"HTTP/1.1 {statusLine}\r\n" +
                    "Access-Control-Allow-Origin: *\r\n" +
                    "Access-Control-Allow-Methods: GET, POST\r\n" +
                    "Content-Type: application/json; charset=utf-8\r\n" +
                    $"Content-Length: {Encoding.UTF8.GetByteCount(json)}\r\n\r\n" +
                    json
                );

                stream.Write(response, 0, response.Length);
                stream.Flush();
                stream.Close();
            }
            catch { }
        }

        #endregion
    }
}