using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Vaitr.Network;

namespace Insight.Web.Network.Broker;

public class WebSession : TcpSession<IMessage>
{
    private readonly IEnumerable<IMessageHandler<WebSession>> _handlers;

    public WebSession(IEnumerable<IMessageHandler<WebSession>> handlers, ISerializer<IMessage> serializer, ILogger<WebSession> logger) : base(serializer, logger)
    {
        _handlers = handlers;
    }

    protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Web ({ep?}) connected", RemoteEndPoint);
        return default;
    }

    protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Web ({ep?}) disconnected", RemoteEndPoint);
        return default;
    }

    protected override ValueTask OnSentAsync(IPacketContext<IMessage> context, CancellationToken cancellationToken)
    {
        return base.OnSentAsync(context, cancellationToken);
    }

    protected override async ValueTask OnReceivedAsync(IPacketContext<IMessage> context, CancellationToken cancellationToken)
    {
        await base.OnReceivedAsync(context, cancellationToken);

        foreach (var handler in _handlers)
        {
            try
            {
                await handler.HandleAsync(this, context.Packet, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Web ({ep?}) {ex}", RemoteEndPoint, ex.ToString());
            }
        }
    }

    protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Web ({ep?}) Heartbeat", RemoteEndPoint);
        return default;
    }
}