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

namespace Insight.Server.Network.Handlers.Agent
{
    public class ConsoleHandler : IAgentMessageHandler<AgentSession>
    {
        private readonly TcpSessionPool<WebSession, MemPackSerializer, IWebMessage> _webPool;
        private readonly IMongoDatabase _database;
        private readonly ILogger<ConsoleHandler> _logger;

        public ConsoleHandler(
            TcpSessionPool<WebSession, MemPackSerializer, IWebMessage> webPool,
            IMongoDatabase database,
            ILogger<ConsoleHandler> logger)
        {
            _webPool = webPool;
            _database = database;
            _logger = logger;
        }

        public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
        {
            if (message is ConsoleQuery consoleQuery)
            {
                await OnConsoleQueryAsync(sender, consoleQuery, cancellationToken);
            }
        }

        private async ValueTask OnConsoleQueryAsync(AgentSession session, ConsoleQuery query, CancellationToken cancellationToken)
        {
            // check if web online
            if (_webPool.FirstOrDefault().Value is not WebSession web) return;

            await web.SendAsync(new ConsoleQueryProxy
            {
                Id = query.Id,
                HostId = query.HostId,
                Query = query.Query,
                Data = query.Data,
                Errors = query.Errors,
                HadErrors = query.HadErrors
            }, cancellationToken);
        }
    }
}