#region << 版 本 注 释 >>

/*--------------------------------------------------------------------
* 版权所有 (c) 2026 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：Mr.Wen's MacBook Pro
* 命名空间：Sln.IntelliBelt.WebSocket
* 唯一标识：FFEDD207-020C-4D9F-90BB-9AAE56AC9C42
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2026-04-24 15:19:42
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using Fleck;
using Sln.IntelliBelt.Serilog;

namespace Sln.IntelliBelt.WebSocket;

public class WebSocketHelper
{
    private List<IWebSocketConnection> _sockets;

    private readonly SerilogHelper _logger;
    
    public delegate void ReceivedMessageRequestInfo(string msg);
    public event ReceivedMessageRequestInfo ReceivedMessageRequestInfoEvent;
    
    public WebSocketHelper(SerilogHelper serilogHelper,List<IWebSocketConnection> sockets)
    {
        _logger = serilogHelper;
        _sockets = sockets;
    }

    public void Init(int port)
    {
        var server = new Fleck.WebSocketServer($"ws://0.0.0.0:{port}");
        server.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                var data = socket.ConnectionInfo;
                _logger.Info("WebSocket Open!");
                _sockets.Add(socket);
            };

            socket.OnClose = () =>
            {
                _logger.Info("WebSocket Close!");
                _sockets.Remove(socket);
            };

            socket.OnMessage = message =>
            {
                ReceivedMessageRequestInfoEvent?.Invoke(message);
            };
        });
    }

    public void PushMsg(string msg)
    {
        try
        {
            foreach (var socket in _sockets)
            {
                socket.Send(msg);
                _logger.Info($"WebSocket推送信息:{msg}");
            }
        }
        catch (Exception ex)
        {
            _logger.Info($"WebSocket推送信息异常:{ex.Message}");
        }
    }
}