using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telepathy;
using TPServer = Telepathy.Server;
using PhilExampleCrawler.Common.TCP.Utils;
using PhilExampleCrawler.Common.TCP.Packets;

namespace PhilExampleCrawler.TCPAPI
{
    internal class TCPServer
    {
        private readonly TPServer _s = new();

        private bool _running;

        public event EventHandler<int>? OnUserConnected;
        public event EventHandler<(int connectionID, BasePacket bp)>? OnDataReceived;
        public event EventHandler<int>? OnUserDisconnected;


        public void StartReceiveLoop(int port)
        {
            if (_running)
                return;

            _running = true;

            _s.Start(port);
            Console.WriteLine("ReceiveLoop started. Now listening for incoming messages on port " + port + "...");

            Task.Run(() =>
            {
                while (_running)
                {
                    while (_s.GetNextMessage(out Message msg))
                        switch (msg.eventType)
                        {
                            case EventType.Connected:
                                OnUserConnected?.Invoke(this, msg.connectionId);
                                break;
                            case EventType.Data:
                                OnDataReceived?.Invoke(this, (msg.connectionId, msg.data.Deserialize()));
                                break;
                            case EventType.Disconnected:
                                OnUserDisconnected?.Invoke(this, msg.connectionId);
                                break;
                        }
                }
            });
        }

        public bool Send(int connectionID, BasePacket bp)
        {
            return _s.Send(connectionID, bp.Serialize());
        }

        public void Stop()
        {
            _running = false;
            _s.Stop();
        }
    }
}
