using System.Net;
using System.Net.Sockets;
using InnovEnergy.Lib.Utils;
using InnovEnergy.Lib.Utils.Net;

namespace InnovEnergy.Logging;

public class Logger
{
    private UdpClient UpdSocket  { get; set; }
    private IPEndPoint EndPoint { get; }

    public Logger(IPEndPoint endPoint)
    {
        EndPoint = endPoint;
        ResetUdpClient();
    }

    private void ResetUdpClient()
    {
        UpdSocket?.Dispose();
        UpdSocket = new UdpClient();
    }

    public void Log<E>(E exception) where E : Exception
    {
        exception.Serialize()
            .TryApply(SendDatagram)
            .Catch(ErrorToStdOut);
    }

    private static Int32 ErrorToStdOut(Exception e)
    {
        Console.WriteLine(e.ToString());
        return 0;
    }

    private Int32 SendDatagram(Byte[] bytes) => UpdSocket.SendDatagram(bytes, EndPoint);
}