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.BLL.Services.Interfaces;
using PARR.Constants;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Controllers.V1.Statistics
{
    public class StatTemplateAutoControlController : BaseApiController
    {
        private readonly ITemplateService templateService;
        private readonly ITemplateHistoryService templateHistoryService;
        private readonly ICalendarService calendarService;

        public StatTemplateAutoControlController(
            ITemplateService templateService,
            ITemplateHistoryService templateHistoryService,
            ICalendarService calendarService
            )
        {
            this.templateService = templateService;
            this.templateHistoryService = templateHistoryService;
            this.calendarService = calendarService;
        }


        /// <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 templates = await templateService.Get()
               .Where(t =>
                        t.InitiatorParrComponentId == Constants.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.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                            && t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                            && 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.TemplateHistories.Any(x => x.InitiatorParrComponentId == Constants.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 == Constants.ParrComponentsEnum.JobAutoControl
                        )).ToList();
            //TODO: createdTemplatesAndMoveToHistory - возможно тут ошибка. Не убираются дубли шаблонов из template
            #endregion

            var history = await templateHistoryService.Get()
                            .Where(t =>
                                    t.InitiatorParrComponentId == Constants.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
                                )
                            .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)
                                .Select(t => new { Date = t.Key, Created = t.Count() });

            // активаций (сколько раз, а не сколько объектов)
            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)
                                    .Select(t => new { Date = t.Key, Actiovations = t.Count() });

            // деактиваций (сколько раз, а не сколько объектов)
            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)
                                    .Select(t => new { Date = t.Key, Deactivations = t.Count() });

            var daysList = calendarService.GetDatesForPeriod(startPeriod, endPeriod);
            var response = new List<StatTemplateAutoControlResponse>();

            daysList.ForEach(date => response.Add(new StatTemplateAutoControlResponse
            {
                Date = date,
                Activations = activations.FirstOrDefault(t => DateOnly.FromDateTime(t.Date) == date)?.Actiovations ?? 0,
                Creations = creations.FirstOrDefault(t => DateOnly.FromDateTime(t.Date) == date)?.Created ?? 0,
                Deactivations = deactivations.FirstOrDefault(t => DateOnly.FromDateTime(t.Date) == date)?.Deactivations ?? 0,
            }));

            response = response.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; }
        }
    }
}
