using AutoMapper;
using FluentValidation;
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.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Управление автоматическим созданием/деактивацией/активацией РР
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class JobAutoControlController : BaseApiController
    {
        //private readonly IJobAutoControlService jobAutoControlService;
        //private readonly IApplicationsInWorkService applicationsInWorkService;
        //private readonly IMapper mapper;
        //private readonly IValidator<JobAutoControlRequest> validator;
        //private readonly IUriService uriService;

        //public JobAutoControlController(
        //    IJobAutoControlService jobAutoControlService,
        //    IApplicationsInWorkService applicationsInWorkService,
        //    IMapper mapper,
        //    IValidator<JobAutoControlRequest> validator,
        //    IUriService uriService
        //    )
        //{
        //    this.jobAutoControlService = jobAutoControlService;
        //    this.applicationsInWorkService = applicationsInWorkService;
        //    this.mapper = mapper;
        //    this.validator = validator;
        //    this.uriService = uriService;
        //}


        ///// <summary>
        ///// Получить настройки автоматического управления РР
        ///// </summary>
        ///// <param name="applicationInWorkId"></param>
        ///// <returns></returns>
        //[HttpGet(ApiRoutes.JobAutoControl.Get)]
        //public async Task<IActionResult> Get([FromRoute] Guid applicationInWorkId)
        //{
        //    var obj = await jobAutoControlService.Get()
        //        .Include(t => t.ApplicationsInWork).ThenInclude(t => t.WorkGroups).ThenInclude(t => t.WorkGroup)
        //        .Include(t => t.JobEkMasks)
        //        .Include(t => t.JobAutoControlInEkStatuses).ThenInclude(t => t.EkStatus)
        //        .FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);

        //    if (obj == null)
        //    {
        //        // проверим, есть ли вообще такой AppInWork
        //        var appInWork = await applicationsInWorkService.GetAsync(applicationInWorkId);
        //        if (appInWork == null)
        //            return NotFound();

        //        return NoContent();
        //    }

        //    var response = mapper.Map<JobAutoControlResponse>(obj);

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


        ///// <summary>
        ///// Создать настройки автоматического управления РР
        ///// </summary>
        ///// <param name="applicationInWorkId"></param>
        ///// <param name="request"></param>
        ///// <returns></returns>
        //[HttpPost(ApiRoutes.JobAutoControl.Create)]
        //public async Task<IActionResult> Create([FromRoute] Guid applicationInWorkId, [FromBody] JobAutoControlRequest request)
        //{
        //    var exist = await jobAutoControlService.Get().FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);
        //    if (exist != null)
        //        return BadRequest(new Response(false, new List<ErrorModel> {
        //            new ErrorModel { FieldName = nameof(applicationInWorkId), Message = $"Запись с {nameof(applicationInWorkId)}: {applicationInWorkId} уже существует." }
        //        }));

        //    var resultValidate = await validator.ValidateAsync(request);
        //    if (!resultValidate.IsValid)
        //        return BadRequest(new Response(resultValidate.Errors));

        //    var newObj = new DAL.Models.JobAutoControl
        //    {
        //        Id = Guid.NewGuid(),
        //        ApplicationInWorkId = applicationInWorkId,
        //        CreateNew = request.CreateNew,
        //        Deactivate = request.Deactivate,
        //        Activate = request.Activate,
        //        OnTemplateIsActive = request.OnTemplateIsActive,
        //        OnScheduleIsActive = request.OnScheduleIsActive,
        //        OffTemplateIsActive = request.OffTemplateIsActive,
        //        OffScheduleIsActive = request.OffScheduleIsActive
        //    };

        //    // убираем пробелы и дубли
        //    request.EkMasks.Where(t => t.Trim() != string.Empty).Distinct().ToList().ForEach(mask => newObj.JobEkMasks.Add(new JobEkMask
        //    {
        //        Id = Guid.NewGuid(),
        //        DateCreated = DateTimeOffset.UtcNow,
        //        Name = mask.Trim(),
        //        JobAutoControlId = newObj.Id
        //    }));

        //    request.EnabledEkStatuses.ForEach(status => newObj.JobAutoControlInEkStatuses.Add(new JobAutoControlInEkStatus
        //    {
        //        EkStatusCode = (int)status,
        //        JobAutoControlId = newObj.Id
        //    }));

        //    if (!await jobAutoControlService.CreateAsync(newObj) || !await jobAutoControlService.CommitAsync())
        //        return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создани записи." } }));

        //    var locationUri = uriService.GetUri(ApiRoutes.JobAutoControl.Get, ApiRoutes.JobAutoControl.appInWorkId, applicationInWorkId);

        //    var createdObj = await jobAutoControlService.Get()
        //        .Include(t => t.ApplicationsInWork).ThenInclude(t => t.WorkGroups).ThenInclude(t => t.WorkGroup)
        //        .Include(t => t.JobEkMasks)
        //        .Include(t => t.JobAutoControlInEkStatuses).ThenInclude(t => t.EkStatus)
        //        .FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);

        //    return Created(locationUri, new Response<JobAutoControlResponse>(mapper.Map<JobAutoControlResponse>(createdObj), true));
        //}


        ///// <summary>
        ///// Обновить настройки автоматического управления РР
        ///// </summary>
        ///// <param name="applicationInWorkId"></param>
        ///// <param name="request"></param>
        ///// <returns></returns>
        //[HttpPut(ApiRoutes.JobAutoControl.Update)]
        //public async Task<IActionResult> Update([FromRoute] Guid applicationInWorkId, [FromBody] JobAutoControlRequest request)
        //{
        //    var resultValidate = await validator.ValidateAsync(request);
        //    if (!resultValidate.IsValid)
        //        return BadRequest(new Response(resultValidate.Errors));

        //    var orig = await jobAutoControlService.Get()
        //        .Include(t => t.JobEkMasks)
        //        .Include(t => t.JobAutoControlInEkStatuses)
        //        .FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);

        //    if (orig == null)
        //        return BadRequest(new Response(false, new List<ErrorModel> {
        //            new ErrorModel { FieldName = nameof(applicationInWorkId), Message = $"Запись с {nameof(applicationInWorkId)}: {applicationInWorkId} не существует." }
        //        }));


        //    orig.DateModified = DateTimeOffset.UtcNow;
        //    orig.CreateNew = request.CreateNew;
        //    orig.Deactivate = request.Deactivate;
        //    orig.Activate = request.Activate;
        //    orig.OnTemplateIsActive = request.OnTemplateIsActive;
        //    orig.OnScheduleIsActive = request.OnScheduleIsActive;
        //    orig.OffTemplateIsActive = request.OffTemplateIsActive;
        //    orig.OffScheduleIsActive = request.OffScheduleIsActive;

        //    orig.JobEkMasks.Clear();
        //    // убираем пробелы и дубли
        //    request.EkMasks.Where(t => t.Trim() != string.Empty).Distinct().ToList().ForEach(mask => orig.JobEkMasks.Add(new JobEkMask
        //    {
        //        //Id = Guid.NewGuid(), // не пойму почему не нужно это поле. с ним ошибка. 
        //        DateCreated = DateTimeOffset.UtcNow,
        //        Name = mask.Trim(),
        //        JobAutoControlId = orig.Id
        //    }));

        //    orig.JobAutoControlInEkStatuses.Clear();
        //    request.EnabledEkStatuses.ForEach(status => orig.JobAutoControlInEkStatuses.Add(new JobAutoControlInEkStatus
        //    {
        //        EkStatusCode = (int)status,
        //        JobAutoControlId = orig.Id
        //    }));

        //    if (!await jobAutoControlService.CommitAsync())
        //        return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении записи." } }));


        //    var updatedObj = await jobAutoControlService.Get()
        //       .Include(t => t.ApplicationsInWork).ThenInclude(t => t.WorkGroups).ThenInclude(t => t.WorkGroup)
        //       .Include(t => t.JobEkMasks)
        //       .Include(t => t.JobAutoControlInEkStatuses).ThenInclude(t => t.EkStatus)
        //       .FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);

        //    return Ok(new Response<JobAutoControlResponse>(mapper.Map<JobAutoControlResponse>(updatedObj), true));
        //}


        ///// <summary>
        ///// Удалить настройки автоматического управления РР
        ///// </summary>
        ///// <param name="applicationInWorkId"></param>
        ///// <returns></returns>
        //[HttpDelete(ApiRoutes.JobAutoControl.Delete)]
        //public async Task<IActionResult> Delete([FromRoute] Guid applicationInWorkId)
        //{
        //    var obj = await jobAutoControlService.Get().FirstOrDefaultAsync(t => t.ApplicationInWorkId == applicationInWorkId);

        //    if (obj == null)
        //        return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении настроект. Не найден настройки с {nameof(applicationInWorkId)}: {applicationInWorkId}" } }));

        //    if (!jobAutoControlService.Delete(obj) || !await jobAutoControlService.CommitAsync())
        //        return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении настроек." } }));

        //    return NoContent();
        //}


    }
}
