using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Insight.Server.Network.Handlers.Agent
{
    public class PrinterHandler : IAgentMessageHandler<AgentSession>
    {
        private readonly IMongoDatabase _database;

        public PrinterHandler(IMongoDatabase database)
        {
            _database = database;
        }

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

        private async ValueTask OnPrintersAsync(AgentSession session, List<Printer> printers, CancellationToken cancellationToken)
        {
            var agentEntity = await _database.Agent().Find(Builders<AgentEntity>.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken);
            if (agentEntity is null) return;

            var hostEntity = await _database.Host().Find(Builders<HostEntity>.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken);
            if (hostEntity is null) return;

            var batch = ObjectId.GenerateNewId().ToString();
            var date = DateTime.Now;

            var bulk = new List<WriteModel<HostPrinterEntity>>();

            if (printers is not null && printers.Any())
            {
                foreach (var printer in printers)
                {
                    var filterDefinition = Builders<HostPrinterEntity>.Filter.And(new List<FilterDefinition<HostPrinterEntity>>
                        {
                            Builders<HostPrinterEntity>.Filter.Eq(x => x.Host, hostEntity.Id),
                            Builders<HostPrinterEntity>.Filter.Eq(x => x.Name, printer.Name)
                        });

                    var updateDefinition = Builders<HostPrinterEntity>.Update
                        .SetOnInsert(p => p.Insert, date)
                        .SetOnInsert(p => p.Host, hostEntity.Id)
                        .SetOnInsert(p => p.Name, printer.Name)
                        .Set(p => p.Update, date)
                        .Set(p => p.Batch, batch)
                        .Set(p => p.Port, printer.Port)
                        .Set(p => p.Location, printer.Location)
                        .Set(p => p.Comment, printer.Comment);

                    bulk.Add(new UpdateOneModel<HostPrinterEntity>(filterDefinition, updateDefinition)
                    {
                        IsUpsert = true
                    });
                }
            }

            bulk.Add(new DeleteManyModel<HostPrinterEntity>(Builders<HostPrinterEntity>.Filter.And(new List<FilterDefinition<HostPrinterEntity>>
                    {
                        Builders<HostPrinterEntity>.Filter.Eq(x => x.Host, hostEntity.Id),
                        Builders<HostPrinterEntity>.Filter.Ne(x => x.Batch, batch)
                    })));

            var result = await _database.HostPrinter().BulkWriteAsync(bulk, cancellationToken: cancellationToken);
        }
    }
}