using Insight.Web.Interfaces;
using Insight.Web.Messages;
using Vaitr.Network;

namespace Insight.Web.Network
{
    public class WebSession : TcpSession<IWebMessage>
    {
        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 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<IWebMessage> context, CancellationToken cancellationToken)
        {
            return 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 ValueTask OnHeartbeatAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Web ({ep?}) Heartbeat", RemoteEndPoint);
            return default;
        }
    }
}