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

namespace Pilz.Net;

public class TCPManager(int port) : ConnectionManagerBase(port)
{
    private readonly TcpListener listener = new TcpListener(IPAddress.Any, port);
    public int BufferSize { get; set; } = 10240;

    public override void Start()
    {
        if (!IsListening)
        {
            listener.Start();
            IsListening = true;
            Task.Run(CheckRetriveData);
        }
    }

    public override void Stop()
    {
        if (IsListening)
        {
            IsListening = false;
            listener.Stop();
        }
    }

    protected override int GetBufferSize()
    {
        return BufferSize;
    }

    private void CheckRetriveData()
    {
        while (IsListening)
        {
            if (listener.Pending())
            {
                var tcp = listener.AcceptTcpClient();
                string ip = ((IPEndPoint)tcp.Client.RemoteEndPoint!).Address.ToString();
                var Stream = tcp.GetStream();
                byte[] buf = new byte[BufferSize];

                tcp.ReceiveBufferSize = BufferSize;
                Stream.Read(buf, 0, buf.Length);

                tcp.Close();

                ProcessRetrivedData(ip, buf);
            }
        }
    }

    protected override void SendData(IPEndPoint ep, byte[] buf)
    {
        var tcp = new TcpClient
        {
            SendBufferSize = BufferSize
        };
        tcp.Connect(ep);

        var stream = tcp.GetStream();

        // Send Data
        stream.Write(buf, 0, buf.Length);
        stream.Flush();

        tcp.Client.Shutdown(SocketShutdown.Both);
        tcp.Close();
    }
}