using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Microsoft.Extensions.Logging;
using Vaitr.Network;

namespace Insight.Server.Network.Web;

public class WebSession : TcpSession<IMessage>
{
    public string? Id { get; set; }

    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 async ValueTask OnConnectedAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Web ({ep?}) connected", RemoteEndPoint);
    }

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

    protected override async ValueTask OnSentAsync(IPacketContext<IMessage> context, CancellationToken cancellationToken)
    {
        await 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 async ValueTask OnHeartbeatAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Web ({ep?}) Heartbeat", RemoteEndPoint);
    }
}