using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Master.Services;
using PARR.Master.Settings;

namespace PARR.Master
{
    internal class Master : IMaster
    {
        private readonly WorkerSettings settings;
        private readonly ILogger<Master> logger;
        private readonly IServiceProvider serviceProvider;
        private readonly IIntervalService intervalService;

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


        public async Task StartAsync()
        {
            logger.LogInformation("Запуск сервиса.");

            await intervalService.IntervalInitAsync(ManageOrdersAsync, settings.RepeatEvery);

            //var nextStart = DateTime.Now;

            //while (true)
            //{
            //    if (nextStart.Hour == DateTime.Now.Hour && nextStart.Minute == DateTime.Now.Minute)
            //    {
            //        logger.LogInformation("Запуск по расписанию.");

            //        await ManageOrdersAsync();

            //        nextStart = DateTime.Now.Add(settings.RepeatEvery);
            //        logger.LogInformation($"Следующая дата запуска: {nextStart}");
            //    }

            //    // Каждую минуту
            //    await Task.Delay(60 * 1000);
            // }
        }


        private async Task ManageOrdersAsync()
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var orderMasterService = scope.ServiceProvider.GetService<IOrderMasterService>();
                if (orderMasterService == null)
                    throw new Exception("Не смог получить серивс IOrderMasterService, scope.ServiceProvider.GetService<IOrderMasterService>()");

                await orderMasterService.ManageOrdersAsync();
            }
        }

    }
}
