using System;
using System.Collections.Generic;
using Fleck;

public class WebSocketServerManager
{
    private List<IWebSocketConnection> _clients = new List<IWebSocketConnection>();
    private WebSocketServer _server;

    public void Start()
    {
        _server = new WebSocketServer("ws://0.0.0.0:5000");
        _server.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                Console.WriteLine("Client connected.");
                _clients.Add(socket);
            };
            socket.OnClose = () =>
            {
                Console.WriteLine("Client disconnected.");
                _clients.Remove(socket);
            };
            socket.OnMessage = message =>
            {
                Console.WriteLine("Received message: " + message);
                // Optionally echo back or handle messages
            };
            socket.OnError = error =>
            {
                Console.WriteLine("Socket error: " + error.Message);
            };
        });

        Console.WriteLine("WebSocket server started on ws://0.0.0.0:5000");
    }

    public void BroadcastMessage(string message)
    {
        foreach (var client in _clients)
        {
            if (client.IsAvailable)
            {
                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error sending message: " + ex.Message);
                }
            }
        }
    }

    public void Stop()
    {
        foreach (var client in _clients)
        {
            client.Close();
        }
        _server.Dispose();
        Console.WriteLine("WebSocket server stopped.");
    }
}
