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 VideocardHandler : IAgentMessageHandler<AgentSession>
    {
        private readonly IMongoDatabase _database;

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

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

        private async ValueTask OnVideocardsAsync(AgentSession session, List<Videocard>? videocards, 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<HostVideocardEntity>>();

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

                    var updateDefinition = Builders<HostVideocardEntity>.Update
                        .SetOnInsert(p => p.Insert, date)
                        .SetOnInsert(p => p.Host, hostEntity.Id)
                        .SetOnInsert(p => p.Name, videocard.Model)
                        .Set(p => p.Update, date)
                        .Set(p => p.Batch, batch)
                        .Set(p => p.Company, null)
                        .Set(p => p.Memory, videocard.Memory)
                        .Set(p => p.Driver, videocard.DriverVersion)
                        .Set(p => p.Date, videocard.DriverDate);

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

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

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