using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.BaseRequests;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.API.Helpers;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Services.NextRunServices;
using PARR.Domain.Enums;

namespace PARR.API.Controllers.V1.Statistics
{
    public class StatTemplateAutoControlController : BaseApiController
    {
        private readonly ITemplateRepository templateService;
        private readonly ITemplateHistoryRepository templateHistoryService;
        private readonly INextRunService nextRunService;

        public StatTemplateAutoControlController(
            ITemplateRepository templateService,
            ITemplateHistoryRepository templateHistoryService,
            INextRunService nextRunService
            )
        {
            this.templateService = templateService;
            this.templateHistoryService = templateHistoryService;
            this.nextRunService = nextRunService;
        }


        /// <summary>
        /// Получить статистику авто-контроля по РР
        /// </summary>
        /// <param name="timeZoneQuery"></param>
        /// <param name="startPeriodDays"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatTemplateAutoControl.GetForPeriod)]
        public async Task<IActionResult> GetForPeriod([FromQuery] TimeZoneOffsetClient timeZoneQuery, [FromQuery] int startPeriodDays = 3)
        {
            //var endPeriod = calendarService.GetDateWithTimeZoneOffset(DateTimeOffset.Now, timeZoneQuery.TimeZoneOffsetHours);
            //var startPeriod = endPeriod.AddDays(-startPeriodDays);

            var userEndPeriod = DateTimeOffset.UtcNow.Add(timeZoneQuery.TimeZoneOffset);
            var userStartPeriod = userEndPeriod.AddDays(-startPeriodDays);

            var utcEndPeriod = userEndPeriod.UtcDateTime;
            var utcStartPeriod = userStartPeriod.UtcDateTime;

            var templates = await templateService.Get()
               .Where(t =>
                        t.InitiatorParrComponentId == ParrComponentsEnum.JobAutoControl
                        &&
                        ((
                            // измененные
                            t.DateModified.HasValue
                            //&& t.DateModified.Value.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                            //&& t.DateModified.Value.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                            && t.DateModified.Value.UtcDateTime >= utcStartPeriod
                            && t.DateModified.Value.UtcDateTime <= utcEndPeriod
                        ) || (
                            // созданные
                            //t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                            //&& t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                            t.DateCreated.UtcDateTime >= utcStartPeriod
                            && t.DateCreated.UtcDateTime <= utcEndPeriod
                            && t.InitiatorComment != null
                            && !t.InitiatorComment.Contains(TemplateActivatorActionsEnum.ActivateAllForAutoControl.ToString())
                            && !t.InitiatorComment.Contains(TemplateActivatorActionsEnum.DeactivateAllForAutoControl.ToString())
                        ))
               )
               .Select(t => new QueryResult
               {
                   //TemplateId = t.Id,
                   DateCreated = t.DateCreated,
                   DateModified = t.DateModified,
                   InitiatorComment = t.InitiatorComment,
                   //InitiatorParrComponentId = t.InitiatorParrComponentId
               })
               .ToListAsync();

            #region ищем созданные, но уже перемещенные в историю
            var createdTemplatesAndMoveToHistory = await templateService.Get().Include(t => t.TemplateHistories)
                .Where(t =>
                    //t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                    //&& t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                    t.DateCreated.UtcDateTime >= utcStartPeriod
                    && t.DateCreated.UtcDateTime <= utcEndPeriod
                    && t.TemplateHistories.Any(x => x.InitiatorParrComponentId == ParrComponentsEnum.JobAutoControl)
                )
                .ToListAsync();

            // фильтруем чтобы инициатор коммент не содержал ActivateAllForAutoControl и DeactivateAllForAutoControl, если не содержит, то остается последнее единственное - генерация
            createdTemplatesAndMoveToHistory = createdTemplatesAndMoveToHistory.Where(t =>
                    t.TemplateHistories.Any(x =>
                        x.InitiatorComment != null
                        && !x.InitiatorComment.Contains(TemplateActivatorActionsEnum.ActivateAllForAutoControl.ToString())
                        && !x.InitiatorComment.Contains(TemplateActivatorActionsEnum.DeactivateAllForAutoControl.ToString())
                        && x.InitiatorParrComponentId == ParrComponentsEnum.JobAutoControl
                        )).ToList();
            //TODO: createdTemplatesAndMoveToHistory - возможно тут ошибка. Не убираются дубли шаблонов из template
            #endregion

            var history = await templateHistoryService.Get()
                            .Where(t =>
                                    t.InitiatorParrComponentId == ParrComponentsEnum.JobAutoControl
                                    && t.DateModified.HasValue
                                    //&& t.DateModified.Value.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                                    //&& t.DateModified.Value.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                                    && t.DateModified.Value.UtcDateTime >= utcStartPeriod
                                    && t.DateModified.Value.UtcDateTime <= utcEndPeriod
                                )
                            .Select(t => new QueryResult
                            {
                                //TemplateId = t.ParentId,
                                //DateCreated = t.DateCreated,
                                DateModified = t.DateModified,
                                InitiatorComment = t.InitiatorComment,
                                //InitiatorParrComponentId = t.InitiatorParrComponentId
                            })
                            .ToListAsync();

            var objs = new List<QueryResult>();
            objs.AddRange(templates);
            objs.AddRange(history);
            objs.AddRange(createdTemplatesAndMoveToHistory.Select(t => new QueryResult { DateCreated = t.DateCreated }));

            // создано
            var creations = objs.Where(t => t.DateCreated.HasValue)
                                     //.GroupBy(t => t.DateCreated!.Value.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date)
                                     //.GroupBy(t => DateOnly.FromDateTime(t.DateCreated!.Value.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime))
                                     //.ToDictionary(t => t.Key, t => t.Count());
                                     .GroupByUserDate(t => t.DateCreated!.Value, timeZoneQuery.TimeZoneOffset);

            // активаций (сколько раз, а не сколько объектов)
            var activations = objs.Where(t => t.DateModified.HasValue && t.InitiatorComment != null && t.InitiatorComment.Contains(TemplateActivatorActionsEnum.ActivateAllForAutoControl.ToString()))
                                    //.GroupBy(t => t.DateModified!.Value.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date)
                                    //.GroupBy(t => DateOnly.FromDateTime(t.DateModified!.Value.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime))
                                    //.ToDictionary(t => t.Key, t => t.Count());
                                    .GroupByUserDate(t => t.DateModified!.Value, timeZoneQuery.TimeZoneOffset);

            // деактиваций (сколько раз, а не сколько объектов)
            var deactivations = objs.Where(t => t.DateModified.HasValue && t.InitiatorComment != null && t.InitiatorComment.Contains(TemplateActivatorActionsEnum.DeactivateAllForAutoControl.ToString()))
                                     //.GroupBy(t => t.DateModified!.Value.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date)
                                     //.GroupBy(t => DateOnly.FromDateTime(t.DateModified!.Value.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime))
                                     //.ToDictionary(t => t.Key, t => t.Count());
                                     .GroupByUserDate(t => t.DateModified!.Value, timeZoneQuery.TimeZoneOffset);

            //var daysList = calendarService.GetDatesForPeriod(startPeriod, endPeriod);
            var daysList = await nextRunService.GetWorkDaysAsync(DateOnly.FromDateTime(userStartPeriod.DateTime), DateOnly.FromDateTime(userEndPeriod.DateTime), false);

            var response = daysList.Select(date => new StatTemplateAutoControlResponse
            {
                Date = date,
                Activations = activations.TryGetValue(date, out var countAct) ? countAct : 0,
                Creations = creations.TryGetValue(date, out var countCrt) ? countCrt : 0,
                Deactivations = deactivations.TryGetValue(date, out var countDeact) ? countDeact : 0
            }).OrderBy(t => t.Date).ToList();

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


        class QueryResult
        {
            //public Guid TemplateId { get; set; }
            public DateTimeOffset? DateCreated { get; set; }
            public DateTimeOffset? DateModified { get; set; }
            public string? InitiatorComment { get; set; }
        }
    }
}
