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

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

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

        private async ValueTask OnApplicationsAsync(AgentSession session, List<Application> applications, 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<HostApplicationEntity>>();

            if (applications is not null && applications.Any())
            {
                foreach (var app in applications)
                {
                    var filterDefinition = Builders<HostApplicationEntity>.Filter.And(new List<FilterDefinition<HostApplicationEntity>>
                    {
                        Builders<HostApplicationEntity>.Filter.Eq(x => x.Host, hostEntity.Id),
                        Builders<HostApplicationEntity>.Filter.Eq(x => x.Name, app.Name),
                        Builders<HostApplicationEntity>.Filter.Eq(x => x.Architecture, app.Architecture?.ToString())
                    });

                    var updateDefinition = Builders<HostApplicationEntity>.Update
                        .SetOnInsert(p => p.Insert, date)
                        .SetOnInsert(p => p.Host, hostEntity.Id)
                        .SetOnInsert(p => p.Name, app.Name)
                        .SetOnInsert(p => p.Architecture, app.Architecture?.ToString())
                        .Set(p => p.Update, date)
                        .Set(p => p.Batch, batch)
                        .Set(p => p.Company, app.Publisher)
                        .Set(p => p.Version, app.Version)
                        .Set(p => p.InstallDate, app.InstallDate);

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

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

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