using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Enums;
using PARR.JobAutoControl.Settings;

namespace PARR.JobAutoControl
{
    internal class JobAutoControlManager : IJobAutoControlManager
    {
        private readonly WorkerSettings workerSettings;
        private readonly ILogger<JobAutoControlManager> logger;
        private readonly IIntervalService intervalService;
        private readonly IServiceProvider serviceProvider;
        private readonly MqSettings mqSettings;

        public JobAutoControlManager(
            WorkerSettings workerSettings,
            ILogger<JobAutoControlManager> logger,
            IIntervalService intervalService,
            IServiceProvider serviceProvider,
            MqSettings mqSettings
            )
        {
            this.workerSettings = workerSettings;
            this.logger = logger;
            this.intervalService = intervalService;
            this.serviceProvider = serviceProvider;
            this.mqSettings = mqSettings;
        }

        public async Task StartAsync()
        {
            logger.LogInformation("Запуск сервиса управления авто-контролем РР (JobAutoControl)");

            await intervalService.IntervalInitAsync(async () =>
            {
                await using (var scope = serviceProvider.CreateAsyncScope())
                //using (var scope = serviceProvider.CreateScope())
                {
                    var jobAutoControlService = scope.ServiceProvider.GetService<IJobAutoControlRepository>();
                    var mqService = scope.ServiceProvider.GetService<IRabbitService>();

                    if (jobAutoControlService == null || mqService == null)
                        throw new Exception($"Не смог получить серивс {nameof(IJobAutoControlRepository)} или {nameof(IRabbitService)}");

                    await HandlerAsync(jobAutoControlService, mqService);
                }
            }, workerSettings.RepeatEvery);
        }


        private async Task HandlerAsync(IJobAutoControlRepository jobAutoControlService, IRabbitService mqService)
        {
            var jobsWithAutoControl = await jobAutoControlService.Get().Where(t => t.IsEnable).ToListAsync();

            logger.LogInformation($"Работ с включенным авто-контролем: {jobsWithAutoControl.Count} шт.");

            if (jobsWithAutoControl.Count == 0)
                return;


            // формируем сообщения
            var msgList = jobsWithAutoControl.Select(t => new TemplateMatcherMq
            {
                Action = TemplateMatcherActionEnum.Sync,
                EntityType = SyncTaskEntityTypeEnum.Job,
                Id = t.JobId,
                Initiator = new HistoryInitiator
                {
                    InitiatorComment = $"Инициатор авто-контроль, периодичность: {workerSettings.RepeatEvery}",
                    InitiatorIp = null,
                    InitiatorParrComponentId = ParrComponentsEnum.JobAutoControl
                }
            }).ToList();

            //var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));

            // отправляем задания в очередь template matcher`a
            //var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgStrList.ToArray());
            var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgList.ToList<object>());

            if (!sendResult.IsSuccess)
                logger.LogError($"Ошибка при отправке сообщений ({msgList.Count()} шт.) в очередь.");
            else
                logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgList.Count()} шт.");
        }

    }
}
