using AsbCloudApp.Data.ProcessMap;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers
{
#nullable enable
    /// <summary>
    /// РТК
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class ProcessMapController : CrudWellRelatedController<ProcessMapPlanDto, IProcessMapPlanRepository>
    {
        private readonly ITelemetryService telemetryService;
        private readonly IProcessMapReportMakerService processMapReportService;
        private readonly IProcessMapReportService processMapService;

        public ProcessMapController(
            IWellService wellService,
            IProcessMapPlanRepository repository,
            IProcessMapReportMakerService processMapReportService,
            IProcessMapReportService processMapService,
            ITelemetryService telemetryService)
            : base(wellService, repository)
        {
            this.telemetryService = telemetryService;
            this.processMapReportService = processMapReportService;
            this.processMapService = processMapService;

        }

        /// <summary>
        /// Возвращает все значения для коридоров бурения по uid панели
        /// </summary>
        /// <param name="uid"> uid панели </param>
        /// <param name="updateFrom"> Дата, с которой следует искать новые параметры </param>
        /// <param name="token"> Токен отмены задачи </param>
        /// <returns> Список параметров для коридоров бурения </returns>
        [HttpGet]
        [Obsolete("use GetByUidAsync(..) instead")]
        [Route("/api/telemetry/{uid}/drillFlowChart")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(IEnumerable<ProcessMapPlanDto>), (int)System.Net.HttpStatusCode.OK)]
        public IActionResult GetByTelemetry(string uid, DateTime updateFrom, CancellationToken token)
        {
            var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
            if (idWell is null)
                return BadRequest($"Wrong uid {uid}");

            var dto = Enumerable.Empty<ProcessMapPlanDto>();
            return Ok(dto);
        }

        /// <summary>
        /// Возвращает РТК по uid телеметрии
        /// </summary>
        /// <param name="uid"> uid телеметрии </param>
        /// <param name="updateFrom"> Дата, с которой следует искать новые параметры </param>
        /// <param name="token"> Токен отмены задачи </param>
        /// <returns> Список параметров для коридоров бурения </returns>
        [HttpGet]
        [Route("/api/telemetry/{uid}/processMap")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(IEnumerable<ProcessMapPlanDto>), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetByUidAsync(string uid, DateTime updateFrom, CancellationToken token)
        {
            var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
            if (idWell is null)
                return BadRequest($"Wrong uid {uid}");

            var dto = await service.GetAllAsync((int)idWell,
                updateFrom, token);

            return Ok(dto);
        }

        /// <summary>
        /// Выгрузка расширенной РТК
        /// </summary>
        /// <param name="wellId"></param>
        /// /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        [Route("getReportFile/{wellId}")]
        [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetReportFileAsync(int wellId, CancellationToken token)
        {
            var stream = await processMapReportService.MakeReportAsync(wellId, token);
            if (stream != null)
            {
                var well = await wellService.GetOrDefaultAsync(wellId, token);
                if (well is null)
                    return NoContent();
                else
                {
                    var fileName = $"РТК по скважине {well.Caption} куст {well.Cluster}.xlsx";
                    return File(stream, "application/octet-stream", fileName);
                }
            }
            else
                return NoContent();
        }

        /// <summary>
        /// Выгрузка режимной карты по бурению скважины
        /// </summary>
        /// <param name="wellId"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("getDrillProcessMap/{wellId}")]
        [ProducesResponseType(typeof(IEnumerable<ProcessMapReportDto>), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetDrillProcessMap(int wellId, CancellationToken token)
        {
            var data = await processMapService.GetProcessMapReportAsync(wellId, token);
            return Ok(data);
        }

        /// <summary>
        /// Добавить запись
        /// </summary>
        /// <param name="value"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult<int>> InsertAsync([FromBody] ProcessMapPlanDto value, CancellationToken token)
        {
            value.IdUser = User.GetUserId() ?? -1;
            return await base.InsertAsync(value, token);
        }

        /// <summary>
        /// Редактировать запись по id
        /// </summary>
        /// <param name="value">запись</param>
        /// <param name="token"></param>
        /// <returns>1 - успешно отредактировано, 0 - нет</returns>
        [HttpPut]
        public override async Task<ActionResult<int>> UpdateAsync([FromBody] ProcessMapPlanDto value, CancellationToken token)
        {
            value.IdUser = User.GetUserId() ?? -1;
            return await base.UpdateAsync(value, token);
        }
    }
#nullable disable
}