using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.TemplateUpdater.Services;
using PARR.TemplateUpdater.Settings;

namespace PARR.TemplateUpdater
{
    internal class TemplateUpdater : ITemplateUpdater
    {
        private readonly MqSettings mqSettings;
        private readonly IRabbitService mqService;
        private readonly ILogger<TemplateUpdater> logger;
        private readonly IServiceProvider serviceProvider;
        private readonly ITransformService transformService;

        public TemplateUpdater(
                    MqSettings mqSettings,
                    IRabbitService mqService,
                    ILogger<TemplateUpdater> logger,
                    IServiceProvider serviceProvider,
                    ITransformService transformService
            )
        {
            this.mqSettings = mqSettings;
            this.mqService = mqService;
            this.logger = logger;
            this.serviceProvider = serviceProvider;
            this.transformService = transformService;
        }


        public async Task StartAsync()
        {
            var isConnected = await mqService.InitConsumerAsync(mqSettings.TemplatesUpdater, UpdateTemplateAsync);

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


        public async Task StopAsync()
        {
            await mqService.DisposeAsync();
        }


        private async Task UpdateTemplateAsync(string msg)
        {
            logger.LogInformation("Получили запрос: {msg}", msg);

            var query = transformService.GetModelFromJson<TemplateUpdaterMessage>(msg);
            if (query == null)
                return;

            using (var scope = serviceProvider.CreateScope())
            {
                var service = scope.ServiceProvider.GetService<ITemplateUpdaterService>();
                if (service == null)
                    throw new Exception($"Не найден сервис: {nameof(service.GetType)}");

                await service.UpdateTemplateAsync(query);
            }
        }
    }
}
