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

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

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

        private async ValueTask OnMemoryAsync(AgentSession session, List<Memory> memory, 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<HostMemoryEntity>>();

            if (memory is not null && memory.Any())
            {
                foreach (var mem in memory)
                {
                    var filterDefinition = Builders<HostMemoryEntity>.Filter.And(new List<FilterDefinition<HostMemoryEntity>>
                        {
                            Builders<HostMemoryEntity>.Filter.Eq(x => x.Host, hostEntity.Id),
                            Builders<HostMemoryEntity>.Filter.Eq(x => x.Index, mem.Index)
                        });

                    var updateDefinition = Builders<HostMemoryEntity>.Update
                        .SetOnInsert(p => p.Insert, date)
                        .SetOnInsert(p => p.Host, hostEntity.Id)
                        .SetOnInsert(p => p.Index, mem.Index)
                        .Set(p => p.Update, date)
                        .Set(p => p.Batch, batch)
                        .Set(p => p.Company, mem.Manufacturer)
                        .Set(p => p.Name, mem.Model)
                        .Set(p => p.Tag, mem.Tag)
                        .Set(p => p.Location, mem.Location)
                        .Set(p => p.Serial, mem.Serial)
                        .Set(p => p.Capacity, mem.Capacity)
                        .Set(p => p.Clock, mem.Speed)
                        .Set(p => p.CurrentClock, mem.ConfiguredSpeed)
                        .Set(p => p.Voltage, mem.Voltage)
                        .Set(p => p.CurrentVoltage, mem.ConfiguredVoltage);

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

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

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