using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Domain.Entities;
using PARR.Domain.Settings;
using PARR.EsppSync;
using PARR.EsppTemplateSync.Domain;
using PARR.EsppTemplateSync.Settings;

namespace PARR.EsppTemplateSync
{
    internal class TemplateMQSyncer : ITemplateSyncer
    {
        private readonly ILogger<TemplateMQSyncer> logger;
        private readonly GlobalSettings globalSettings;
        private readonly IRabbitService mqService;
        private readonly SettingsFromDb settingsFromDb;
        private readonly ISyncService<EsppObjectTemplate> syncService;


        public TemplateMQSyncer(
            ILogger<TemplateMQSyncer> logger,
            GlobalSettings globalSettings,
            IRabbitService mqService,
            SettingsFromDb settingsFromDb,
            ISyncService<EsppObjectTemplate> syncService
            )
        {
            this.logger = logger;
            this.globalSettings = globalSettings;
            this.mqService = mqService;
            this.settingsFromDb = settingsFromDb;
            this.syncService = syncService;

            if (globalSettings.MqSettings == null)
            {
                logger.LogError("Нет секции настроек хранилища. MqSettings, EsppTemplates");
                throw new Exception("Нет секции настроек хранилища. MqSettings, EsppTemplates");
            }
        }

        public async Task StartAsync()
        {
            var isConnected = await mqService.InitConsumerAsync(globalSettings!.MqSettings!, SyncTemplateAsync);

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

            logger.LogInformation("Запущена проверка очереди {QueueName}.", globalSettings.MqSettings!.QueueName);
        }

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

            logger.LogInformation("=== === === Соединение с очередью {QueueName} закрыто === === ===", globalSettings.MqSettings!.QueueName);
        }


        private async Task SyncTemplateAsync(string str)
        {
            await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj);
        }


        /// <summary>
        /// Преобразование модели БД в модель для сравнения
        /// </summary>
        /// <param name="template">template должен обязательно содержать в себе информацию о Job+Group и Unit+BaseFields</param>
        /// <returns></returns>
        private EsppObjectTemplate ConvertDbObjToEsppObj(Template template)
        {
            var templateFromDb = new EsppObjectTemplate
            {
                TemplateName = template.Name.ToUpper(),
                IsActive = template.IsActiveTemplate,
                //WorkGroup = template.Host!.WorkGroup!,
                //WorkGroup = template.Unit!.BaseFields!.WorkGroup!,
                WorkGroup = template.Job!.WorkGroupMask,
                //ShortDescription = Normalize(template.Job.Group.ShortDescription.ApplyShortcode(Constants.Shortcodes.ShortcodeEnum.EK,template.Unit.Name)),
                ShortDescription = template.Job!.Group!.ShortDescription,//TODO Вынести в переменную
                //ResponseArea = template.Host!.ResponseArea!.Name,
                ////ЗО берем РГ а не хоста
                //ResponseArea = template.Unit!.BaseFields!.ResponseArea!,
                ResponseArea = template.Job.ResponseAreaMask,
                Duration = template.Job.Group.TemplateDuration,
                EK = template.Unit!.Name,
                FullDescription = template.Job.Group.FullDescription,
                Solution = template.Job.Group.Solution,
                Process = template.Job.Tnk!.Subprocess!.Process!.Name,
                SubProcess = template.Job.Tnk.Subprocess.Name,
                //TNK = template.Job.Tnk.Name.ApplyShortcode(Constants.Shortcodes.ShortcodeEnum.EK, template.Unit.Name),
                TNK = template.Job.Tnk.Name,
                Work = template.Job.WorkName,
                Initiator = settingsFromDb.Initiator,
                // Исполнитель, мы хотим чтобы он всегда был пустой
                Worker = string.Empty
            };

            return templateFromDb;
        }


        /// <summary>
        /// Парсинг из строки в модель для сравнения
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private EsppObjectTemplate? ParseStrToEsppObject(string str)
        {
            var splittedContent = str.Split(globalSettings.ParsingSeparator);
            if (splittedContent.Length != 17)
            {
                logger.LogError("Входная строка после сплита не содержит 17 объектов (факт: {Length}).", splittedContent.Length);
                return null;
            }

            var templateName = splittedContent[0].Trim();

            var currentCulture = Thread.CurrentThread.CurrentCulture;

            //if (!string.IsNullOrEmpty(settingsFromDb.TemplatePrefixName) || !templateName.StartsWith(settingsFromDb.TemplatePrefixName, true, currentCulture))
            if (string.IsNullOrEmpty(settingsFromDb.TemplatePrefixWithoutVariable) || !templateName.Contains(settingsFromDb.TemplatePrefixWithoutVariable)) // , StringComparison.CurrentCultureIgnoreCase
            {
                logger.LogWarning("Имя шаблона не соответствует обязательному префиксу({Prefix}). Шаблон {TemplateName} игнорирован", settingsFromDb.TemplatePrefixWithoutVariable, templateName);
                return null;
            }

            bool.TryParse(splittedContent[1].Trim(), out var isActive);

            var workGroup = splittedContent[2].Trim();
            var shortDescription = splittedContent[3].Trim();
            var category = splittedContent[4].Trim();
            var responseArea = splittedContent[5].Trim();
            var duration = splittedContent[6].Trim();
            var ek = splittedContent[7].Trim();
            var initiator = splittedContent[8].Trim();

            var fullDescription = splittedContent[9].Trim();
            var closingCode = splittedContent[10].Trim();
            var solution = splittedContent[11].Trim();
            var process = splittedContent[12].Trim();
            var subProcess = splittedContent[13].Trim();
            var tnk = splittedContent[14].Trim();
            var work = splittedContent[15].Trim();
            var worker = splittedContent[16].Trim();

            var templateFromEspp = new EsppObjectTemplate
            {
                TemplateName = templateName.ToUpper(),
                IsActive = isActive,
                WorkGroup = workGroup,
                ShortDescription = shortDescription,
                //Category = category,
                ResponseArea = responseArea,
                Duration = duration,
                EK = ek,
                Initiator = initiator,
                FullDescription = fullDescription,
                //ClosingCode = closingCode,
                Solution = solution,
                Process = process,
                SubProcess = subProcess,
                TNK = tnk,
                Work = work,
                Worker = worker
            };

            return templateFromEspp;
        }
    }
}