using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.TemplateGeneratorWorker.Settings;

namespace PARR.TemplateGeneratorWorker
{
    public class Worker : BackgroundService
    {

        private readonly MqSettings mqSettings;
        private readonly IRabbitService mqService;
        private readonly IServiceProvider serviceProvider;

        public Worker(
            MqSettings mqSettings,
            IRabbitService mqService,
            IServiceProvider serviceProvider
            )
        {
            this.mqSettings = mqSettings;
            this.mqService = mqService;
            this.serviceProvider = serviceProvider;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var isConnected = await mqService.InitConsumerAsync(mqSettings, GenerateTemplateAsync);

            if (!isConnected)
                throw new Exception("Ошибка при подключении к RabbitMq");
        }


        public override Task StopAsync(CancellationToken cancellationToken)
        {
            mqService.DisposeAsync().AsTask().Wait();

            return base.StopAsync(cancellationToken);
        }


        private async Task GenerateTemplateAsync(string msg)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var templateGenerator = scope.ServiceProvider.GetService<ITemplateGenerator>();
                if (templateGenerator == null)
                    throw new Exception($"Не найден сервис: {nameof(ITemplateGenerator)}");
                await templateGenerator.GenerateTemplateAsync(msg);
            }
        }
    }
}

