using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;

namespace WCS.BLL.Manager
{
    public static class WebSoceketManager
    {
        public static HttpService service;

        public static object flag = new object();
        public static void InitWebSocket()
        {
            Console.WriteLine("【启动WebSocket】开始");
            Logs.Write("【启动WebSocket】开始", LogsType.StartBoot);
            service = new HttpService();
            service.Setup(new TouchSocketConfig()//加载配置
                .SetListenIPHosts(7789)
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();
                })
                .ConfigurePlugins(a =>
                {
                    a.UseWebSocket()//添加WebSocket功能
                    .SetWSUrl("/ws")//设置url直接可以连接。
                    .UseAutoPong();//当收到ping报文时自动回应pong
                    a.Add<WebSocketServicePlugin>();//自定义插件。
                }));
            //客户端成功连接
            service.Connected = (client, e) =>
            {
                Logs.Write("[WebSocket]" + client.GetIPPort() + "成功连接！", LogsType.StartBoot);
                Console.WriteLine("[WebSocket]" + client.GetIPPort() +"成功连接！");
                return EasyTask.CompletedTask;
            };
            service.Start();
            Console.WriteLine("【启动WebSocket】结束");
            Logs.Write("【启动WebSocket】结束", LogsType.StartBoot);
        }

        //发送报警信息给前端
        public static void TrySendMessage(string IpAddress, string Message)
        {
            try
            {
                var clients = service.GetClients().Where(t => t.IP == IpAddress).ToList();
                foreach (var client in clients)
                {
                    lock (client)
                    {
                        client.WebSocket.Send(Message);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
