using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers.Trajectory
{

    /// <summary>
    /// Плановые и фактические траектории (загрузка и хранение)
    /// </summary>
    [ApiController]
    [Authorize]
    public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>
        where TDto : TrajectoryGeoDto
    {
        private readonly TrajectoryParserService<TDto> trajectoryImportService;
        private readonly TrajectoryExportService<TDto> trajectoryExportService;
        private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;

        public TrajectoryEditableController(IWellService wellService,
            TrajectoryParserService<TDto> trajectoryImportService,
            TrajectoryExportService<TDto> trajectoryExportService,
            ITrajectoryEditableRepository<TDto> trajectoryRepository)
            : base(
                  wellService,
                  trajectoryExportService,
                  trajectoryRepository)
        {
            this.trajectoryImportService = trajectoryImportService;
            this.trajectoryExportService = trajectoryExportService;
            this.trajectoryRepository = trajectoryRepository;

        }

        /// <summary>
        /// Возвращает excel шаблон для заполнения строк траектории
        /// </summary>
        /// <returns>Запрашиваемый файл</returns>
        [HttpGet("template")]
        [AllowAnonymous]
        [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK, "application/octet-stream")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public IActionResult GetTemplate()
        {
            var stream = trajectoryExportService.GetTemplateFile();
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// Импортирует координаты из excel (xlsx) файла
        /// </summary>
        /// <param name="idWell">id скважины</param>
        /// <param name="files">Коллекция из одного файла xlsx</param>
        /// <param name="deleteBeforeImport">Удалить операции перед импортом, если фал валидный</param>
        /// <param name="token"> Токен отмены задачи </param>
        /// <returns>количество успешно записанных строк в БД</returns>
        [HttpPost("import/{deleteBeforeImport}")]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        [ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
        public async Task<IActionResult> ImportAsync(int idWell,
            [FromForm] IFormFileCollection files,
            bool deleteBeforeImport,
            CancellationToken token)
        {
            int? idUser = User.GetUserId();
            if (!idUser.HasValue)
                return Forbid();
            if (!await CanUserAccessToWellAsync(idWell,
                token).ConfigureAwait(false))
                return Forbid();
            if (files.Count < 1)
                return this.ValidationBadRequest(nameof(files), "нет файла");
            var file = files[0];
            if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
                return this.ValidationBadRequest(nameof(files), "Требуется xlsx файл.");
            using Stream stream = file.OpenReadStream();

            try
            {
                var trajectoryRows = trajectoryImportService.Import(stream);
                foreach (var row in trajectoryRows)
                {
                    row.IdWell = idWell;
                    row.IdUser = idUser.Value;
                }

                if (deleteBeforeImport)
                    await trajectoryRepository.DeleteByIdWellAsync(idWell, token);

                var rowsCount = await trajectoryRepository.AddRangeAsync(trajectoryRows, token);

                return Ok(rowsCount);
            }
            catch (FileFormatException ex)
            {
                return this.ValidationBadRequest(nameof(files), ex.Message);
            }
        }


        /// <summary>
        /// Добавить одну новую строчку координат для плановой траектории
        /// </summary>
        /// <param name="idWell"></param>
        /// <param name="row"></param>
        /// <param name="token"></param>
        /// <returns>количество успешно записанных строк в БД</returns>
        [HttpPost]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> AddAsync(int idWell, [FromBody] TDto row,
            CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
                return Forbid();
            var idUser = User.GetUserId();
            if (!idUser.HasValue)
                return Forbid();
            row.IdUser = idUser.Value;
            row.IdWell = idWell;
            var result = await trajectoryRepository.AddAsync(row, token);
            return Ok(result);
        }

        /// <summary>
        /// Добавить массив строчек координат для плановой траектории
        /// </summary>
        /// <param name="idWell"></param>
        /// <param name="rows"></param>
        /// <param name="token"></param>
        /// <returns>количество успешно записанных строк в БД</returns>
        [HttpPost("range")]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> AddRangeAsync(int idWell, [FromBody] IEnumerable<TDto> rows,
            CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
                return Forbid();
            int? idUser = User.GetUserId();
            if (!idUser.HasValue)
                return Forbid();
            foreach (var item in rows)
            {
                item.IdUser = idUser.Value;
                item.IdWell = idWell;
            }
            var result = await trajectoryRepository.AddRangeAsync(rows, token);
            return Ok(result);
        }

        /// <summary>
        /// Изменить выбранную строку с координатами
        /// </summary>
        /// <param name="idWell"></param>
        /// <param name="idRow"></param>
        /// <param name="row"></param>
        /// <param name="token"></param>
        /// <returns>количество успешно обновленных строк в БД</returns>
        [HttpPut("{idRow}")]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> UpdateAsync(int idWell, int idRow,
            [FromBody] TDto row, CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
                return Forbid();
            int? idUser = User.GetUserId();
            if (!idUser.HasValue)
                return Forbid();
            row.Id = idRow;
            row.IdUser = idUser.Value;
            row.IdWell = idWell;
            var result = await trajectoryRepository.UpdateAsync(row, token);
            return Ok(result);
        }

        /// <summary>
        /// Удалить выбранную строку с координатами
        /// </summary>
        /// <param name="idWell"></param>
        /// <param name="idRow"></param>
        /// <param name="token"></param>
        /// <returns>количество успешно удаленных строк из БД</returns>
        [HttpDelete("{idRow}")]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> DeleteAsync(int idWell, int idRow, CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell,
                token).ConfigureAwait(false))
                return Forbid();

            var result = await trajectoryRepository.DeleteRangeAsync(new int[] { idRow }, token);

            return Ok(result);
        }
    }
}