using System.Net;
using System.Net.Sockets;

namespace SHH.MjpegPlayer
{
    /// <summary>
    /// Mjpeg 服务
    /// </summary>
    public class MjpegServer
    {
        // [修复] 静态列表管理监听器，支持优雅停止
        private static readonly List<TcpListener> _listeners = new List<TcpListener>();
        private static readonly object _lock = new object();

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="port"></param>
        public static void Start(int port)
        {
            try
            {
                // 示例：在 MjpegServer 初始化循环中调用
                TaskManager.Run($"MjpegServer-{port}", "Network", async (token) =>
                {
                    // [Modified]: 使用 TaskManager 托管，支持外部取消令牌 token
                    try
                    {
                        var cfg = MjpegStatics.Cfg;
                        IPAddress ipAddress = IPAddress.Any;

                        if (!string.IsNullOrEmpty(cfg.SvrMjpegIp) && IPAddress.TryParse(cfg.SvrMjpegIp, out var parsedIp))
                        {
                            ipAddress = parsedIp;
                        }

                        var server = new TcpListener(ipAddress, port);
                        lock (_lock) _listeners.Add(server);

                        server.Start();
                        // Logs.LogInformation...

                        try
                        {
                            // [Modified]: 检查取消令牌和全局运行状态
                            while (!token.IsCancellationRequested)
                            {
                                try
                                {
                                    // 使用 AcceptTcpClientAsync 的重载或在外部检查
                                    var client = await server.AcceptTcpClientAsync();
                                    if (client == null) continue;

                                    var session = new MjpegSession();
                                    session.Create(client);
                                }
                                catch (Exception ex)
                                {
                                    // [修复] 异常防暴
                                    await Task.Delay(1000, token);
                                }
                            }
                        }
                        finally
                        {
                            // [修复] 任务退出清理
                            try { server.Stop(); } catch { }
                            lock (_lock) _listeners.Remove(server);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Logs.LogError... 捕获初始化异常
                    }
                });
            }
            catch (Exception ex)
            {
                //Logs.LogError<MjpegServer>(ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        /// 停止所有服务 (新增)
        /// </summary>
        public static void StopAll()
        {
            lock (_lock)
            {
                foreach (var server in _listeners)
                {
                    try { server.Stop(); } catch { }
                }
                _listeners.Clear();
            }
        }
    }
}