using Insight.Web.Interfaces;
using Insight.Web.Messages;
using Microsoft.Extensions.Logging;
using Vaitr.Network;

namespace Insight.Server.Network;

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

    private readonly IEnumerable<IWebMessageHandler<WebSession>> _handlers;

    public WebSession(IEnumerable<IWebMessageHandler<WebSession>> handlers, ISerializer<IWebMessage> 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<IWebMessage> context, CancellationToken cancellationToken)
    {
        await base.OnSentAsync(context, cancellationToken);
    }

    protected override async ValueTask OnReceivedAsync(IPacketContext<IWebMessage> 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);
    }
}