using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.BLL.Contracts;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.DAL.Models;
using PARR.GeneratorTemplates.Services;
using PARR.GeneratorTemplates.Settings;
using System.Threading.Tasks;

namespace PARR.GeneratorTemplates
{
    internal class GeneratorTemplate : IGeneratorTemplate
    {
        private readonly MqSettings mqSettings;
        private readonly IMqService mqService;
        private readonly ILogger<GeneratorTemplate> logger;
        private readonly ITransformService transformService;
        private readonly IValidatorService validatorService;
        private readonly IServiceProvider serviceProvider;

        public GeneratorTemplate(
            MqSettings mqSettings,
            IMqService mqService,
            ILogger<GeneratorTemplate> logger,
            ITransformService transformService,
            IValidatorService validatorService,
            IServiceProvider serviceProvider
            )
        {
            this.mqSettings = mqSettings;
            this.mqService = mqService;
            this.logger = logger;
            this.transformService = transformService;
            this.validatorService = validatorService;
            this.serviceProvider = serviceProvider;
        }

        public async Task StartAsync()
        {
            #region test
            // string msg = "{\"WorkId\":\"91219bec-e5f7-4a1a-b4c9-c135035d2498\",\"ApplicationId\":\"13044a1f-fa0c-476f-b501-2b8d06bac9f8\",\"Action\":\"create\",\"Ek\":\"ВРТ*ДВС\",\"StatusEk\":0}";
            // string msg = "{\"WorkId\":\"91219bec-e5f7-4a1a-b4c9-c135035d2498\",\"ApplicationId\":\"13044a1f-fa0c-476f-b501-2b8d06bac9f8\",\"Action\":\"deactivate\",\"Ek\":\"ВРТ*ДВС\",\"StatusEk\":0}";

            // await GenerateTemplates(msg);
            #endregion

            var isConnected = await mqService.InitConsumerAsync(mqSettings, GenerateTemplates);

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

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


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

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

            if (!await validatorService.IsValidApplicationAndWorksAsync(query.ApplicationId, query.WorkId))
            {
                logger.LogError($"Не валидны параметры {nameof(query.ApplicationId)}: {query.ApplicationId}, " +
                    $"{nameof(query.WorkId)}: {query.WorkId}," +
                    $" нет таких значений или они не связаны в таблице ${nameof(ApplicationsInWork)}");
                return;
            }

            Enum.TryParse(typeof(GenerateTemplateActionsEnum), query.Action, true, out var action);

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

                switch (action)
                {
                    case GenerateTemplateActionsEnum.create:
                        await templateManager.CreateTemplates(query);
                        break;

                    case GenerateTemplateActionsEnum.deactivate:
                        await templateManager.DeactivateTemplates(query);
                        break;

                    default:
                        logger.LogError($"Во входящем запросе, поле {nameof(query.Action)} не содержит допустимых значений");
                        return;
                }
            }
        }

    }
}
