using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.BLL.Helpers;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
using PARR.DAL.DomainServices.Shortcodes;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Шаблоны
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class TemplateController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly ITemplateService templateService;
        private readonly IRobotConfigurationService robotConfigurationService;
        private readonly IClientService clientService;
        private readonly ILogger<TemplateController> logger;
        private readonly IShortcodesService shortcodesService;

        public TemplateController(
            IMapper mapper,
            ITemplateService templateService,
            IRobotConfigurationService robotConfigurationService,
            IClientService clientService,
            ILogger<TemplateController> logger,
            IShortcodesService shortcodesService
            )
        {
            this.mapper = mapper;
            this.templateService = templateService;
            this.robotConfigurationService = robotConfigurationService;
            this.clientService = clientService;
            this.logger = logger;
            this.shortcodesService = shortcodesService;
        }


        /// <summary>
        /// Получить список всех шаблонов постранично
        /// </summary>
        /// <param name="paginationQuery"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Template.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] TemplateQuery filter)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<Template> query = templateService.GetWithIncludes().AsNoTracking()
                                                             .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
                                                             .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
                                                             .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
                                                             .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
                                                             .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
                                                             .Include(t => t.Orders)
                                                             .Include(t => t.StatusType)
                                                             .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
                                                             .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
                                                             .OrderBy(t => t.Name)
                                                             .AsSplitQuery();


            if (!string.IsNullOrEmpty(filter.Mask))
                query = query.Where(t => EF.Functions.Like(t.Name.ToLower(), SqlHelpers.RegexToLike(filter.Mask)));

            if (filter.JobId.HasValue)
                query = query.Where(t => t.JobId == filter.JobId);

            if (filter.StatusTypeId.HasValue)
                query = query.Where(t => t.StatusTypeId == filter.StatusTypeId);

            #region Статус синхронизации

            switch (filter.SyncStatus)
            {
                case (TemplateQuerySyncStatusEnum.Waiting):
                    query = query.Where(t => t.RobotConfigurations.Any(x => x.TaskStatusCode != (int)TaskStatusEnum.Ok));
                    break;
                case (TemplateQuerySyncStatusEnum.Complete):
                    query = query.Where(t => t.RobotConfigurations.All(x => x.TaskStatusCode == (int)TaskStatusEnum.Ok));
                    break;
                case (TemplateQuerySyncStatusEnum.Error):
                    query = query.Where(t => t.RobotConfigurations.Any(x => x.RobotStatusCode == (int)RobotStatusEnum.Error));
                    break;
                default:
                    break;
            }

            #endregion

            var templates = await templateService.GetPage(query, paginationFilter).ToListAsync();

            if (!templates.Any())
                return NoContent();

            var templateResponse = mapper.Map<List<TemplateResponse>>(templates);
            foreach (var responseItem in templateResponse)
            {
                await ApplyTemplateShortcodesAsync(responseItem, templates.First(t => t.Id == responseItem.Id));
            }

            var paginationResponse = new PagedResponse<TemplateResponse>(templateResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }

        /// <summary>
        /// Получить шаблон по id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Template.Get)]
        public async Task<IActionResult> GetById([FromRoute] Guid id)
        {
            var template = await templateService.GetWithIncludes().AsNoTracking()
                                                            .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
                                                            .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
                                                            .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
                                                            .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
                                                            .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
                                                            .Include(t => t.Orders)
                                                            .Include(t => t.StatusType)
                                                            .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
                                                            .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
                                                        .AsSplitQuery()
                                                        .FirstOrDefaultAsync(t => t.Id == id);

            if (template == null)
                return NotFound();

            var response = mapper.Map<TemplateResponse>(template);
            await ApplyTemplateShortcodesAsync(response, template);

            return Ok(new Response<TemplateResponse>(response, true));
        }


        /// <summary>
        /// Изменить статус у шаблона по ИД (активировать/деактивировать)
        /// </summary>
        /// <param name="id">ИД шаблона</param>
        /// <returns></returns>
        [HttpPut(ApiRoutes.Template.ChangeState)]
        public async Task<IActionResult> ChangeState([FromRoute] Guid id, [FromBody] TemplateChangeStateRequest request)
        {
            //TODO:!!! Возможно тут не надо сразу менять, а отправить запрос в TemplateActivator и пусть он сам занимается своей работой!!!


            var template = await templateService.GetWithIncludes()
                                                           .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
                                                           .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
                                                           .Include(t => t.Orders)
                                                           .Include(t => t.StatusType)
                                                           .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
                                                           .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
                                                       .AsSplitQuery()
                                                       .FirstOrDefaultAsync(t => t.Id == id);

            if (template == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден шаблона с id: {id}" } }));

            if (template.IsActiveTemplate != request.IsActiveTemplate)
            {
                template.IsActiveTemplate = request.IsActiveTemplate;
                //необходимо обновить шаблон
                var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, template);
                robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
            }

            if (template.IsActiveSchedule != request.IsActiveSchedule)
            {
                template.IsActiveSchedule = request.IsActiveSchedule;
                //необходимо обновить расписание
                var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
                robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
            }

            if (!await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Изменён статус шаблона/расписания", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }))
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении шаблона." } }));

            var templateToResponse = await templateService.GetWithIncludes().AsNoTracking()
                                                           .Include(t => t.Unit).ThenInclude(t => t.UnitValues).ThenInclude(t => t.Field)
                                                           .Include(t => t.Unit).ThenInclude(t => t.UnitValues).ThenInclude(t => t.Value)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
                                                           .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
                                                           .Include(t => t.Orders)
                                                           .Include(t => t.StatusType)
                                                           .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
                                                           .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
                                                       .AsSplitQuery()
                                                       .FirstAsync(t => t.Id == id);

            var response = mapper.Map<TemplateResponse>(templateToResponse);
            await ApplyTemplateShortcodesAsync(response, templateToResponse);

            return Ok(new Response<TemplateResponse>(response, true));
        }


        private async Task ApplyTemplateShortcodesAsync(TemplateResponse response, Template template)
        {
            response.WorkGroup = await shortcodesService.ApplyShortcodesAsync(template.Job.WorkGroupMask, template);
            response.ResponseArea = await shortcodesService.ApplyShortcodesAsync(template.Job.ResponseAreaMask, template);
        }

    }
}
