using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Enums;
using PARR.NextRun.Services;
using PARR.NextRun.Settings;

namespace PARR.NextRun
{
    /// <summary>
    /// Расчет nextRun по интервалу
    /// </summary>
    internal class NextRunIntervalService : INextRunIntervalService
    {
        private readonly WorkerSettings workerSettings;
        private readonly ILogger<NextRunIntervalService> logger;
        private readonly IIntervalService intervalService;
        private readonly IServiceProvider serviceProvider;

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

        public async Task StartAsync()
        {
            logger.LogInformation("Запуск сервиса рассчета времени следующего создания наряда (nextRun)");

            await intervalService.IntervalInitAsync(async () =>
            {
                using (var scope = serviceProvider.CreateScope())
                {
                    var nextRunUpdateService = scope.ServiceProvider.GetRequiredService<INextRunUpdateService>();

                    await nextRunUpdateService.UpdateNextRunForTemplatesAsync(
                            // фильтр, только просроченные шаблоны
                            query => query.Where(t => t.NextRun < DateTimeOffset.UtcNow),
                            () => new HistoryInitiator
                            {
                                InitiatorComment = "Обновлён NextRun (интервал)",
                                InitiatorParrComponentId = ParrComponentsEnum.NextRun
                            },
                            "Интервал"
                        );

                    //var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
                    //var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>();
                    //var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();

                    //await HandlerAsync(templateService, nextRunService, robotConfigurationService);
                }
            }, workerSettings.RepeatEvery);
        }

    }
}
