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

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

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

        private async ValueTask OnServicesAsync(AgentSession session, List<Service> services, 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<HostServiceEntity>>();

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

                    var updateDefinition = Builders<HostServiceEntity>.Update
                        .SetOnInsert(p => p.Insert, date)
                        .SetOnInsert(p => p.Host, hostEntity.Id)
                        .SetOnInsert(p => p.Name, service.Name)
                        .Set(p => p.Update, date)
                        .Set(p => p.Batch, batch)
                        .Set(p => p.DisplayName, service.Display)
                        .Set(p => p.Description, service.Description)
                        .Set(p => p.StartMode, service.StartMode.ToString())
                        .Set(p => p.State, service.Status.ToString())
                        .Set(p => p.ProcessId, service.ProcessId)
                        .Set(p => p.Delay, service.Delay)
                        .Set(p => p.Path, service.PathName)
                        .Set(p => p.Account, service.Account);

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

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

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