using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers
{
    /// <summary>
    /// Отчет (временная диаграмма с сообщениями)
    /// </summary>
    [Route("api/well/{idWell}/report")]
    [ApiController]
    public class ReportController : ControllerBase
    {
        private readonly IReportService reportService;
        private readonly FileService fileService;
        private readonly IWellService wellService;
        private readonly IHubContext<ReportsHub> reportsHubContext;

        public ReportController(IReportService reportService, IWellService wellService,
            FileService fileService, IHubContext<ReportsHub> reportsHubContext)
        {
            this.reportService = reportService;
            this.fileService = fileService;
            this.wellService = wellService;
            this.reportsHubContext = reportsHubContext;
        }

        /// <summary>
        /// Создает отчет по скважине с указанными параметрами
        /// </summary>
        /// <param name="idWell">id скважины</param>
        /// <param name="stepSeconds">шаг интервала</param>
        /// <param name="format">формат отчета (0-PDF, 1-LAS)</param>
        /// <param name="begin">дата начала интервала</param>
        /// <param name="end">дата окончания интервала</param>
        /// <param name="token">Токен для отмены задачи</param>
        /// <returns>id фоновой задачи формирования отчета</returns>
        [HttpPost]
        [Permission]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> CreateReportAsync(int idWell, int stepSeconds, int format,
            DateTime begin = default, DateTime end = default,
            CancellationToken token = default)
        {
            var idCompany = User.GetCompanyId();
            var idUser = User.GetUserId();

            if ((idCompany is null) || (idUser is null))
                return Forbid();

            if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
                idWell, token).ConfigureAwait(false))
                return Forbid();

            void HandleReportProgressAsync(object progress, string id) =>
                Task.Run(() =>
                {
                    reportsHubContext.Clients.Group($"Report_{id}").SendAsync(
                        nameof(IReportHubClient.GetReportProgress),
                        progress,
                        token
                    ).ConfigureAwait(false);
                }, token);

            var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser,
                stepSeconds, format, begin, end, HandleReportProgressAsync);

            return Ok(id);
        }

        /// <summary>
        /// Возвращает имена всех отчетов по скважине
        /// </summary>
        /// <param name="idWell">id скважины</param>
        /// <param name="token">Токен для отмены задачи</param>
        /// <returns>Список имен существующих отчетов (отчетов)</returns>
        [HttpGet]
        [Permission]
        [ProducesResponseType(typeof(IEnumerable<string>), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetAllReportsNamesByWellAsync(int idWell, CancellationToken token = default)
        {
            int? idCompany = User.GetCompanyId();

            if (idCompany is null)
                return Forbid();

            if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
                idWell, token).ConfigureAwait(false))
                return Forbid();

            var reports = await reportService.GetAllReportsByWellAsync(idWell, token).ConfigureAwait(false);

            return Ok(reports);
        }

        /// <summary>
        /// Возвращает прогнозируемое количество страниц будущего отчета
        /// </summary>
        /// <param name="idWell">id скважины</param>
        /// <param name="begin">дата начала интервала</param>
        /// <param name="end">дата окончания интервала</param>
        /// <param name="stepSeconds">шаг интервала</param>
        /// <param name="format">формат отчета (0-PDF, 1-LAS)</param>
        /// <param name="token">Токен для отмены задачи</param>
        /// <returns>прогнозируемое кол-во страниц отчета</returns>
        [HttpGet]
        [Route("reportSize")]
        [Permission]
        [ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetReportSizeAsync(int idWell,
            int stepSeconds, int format, DateTime begin = default,
            DateTime end = default, CancellationToken token = default)
        {
            int? idCompany = User.GetCompanyId();

            if (idCompany is null)
                return Forbid();

            if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
                idWell, token).ConfigureAwait(false))
                return Forbid();

            int reportSize = reportService.GetReportPagesCount(idWell,
                begin, end, stepSeconds, format);

            return Ok(reportSize);
        }

        /// <summary>
        /// Возвращает даты самого старого и самого свежего отчетов в БД
        /// </summary>
        /// <param name="idWell">id скважины</param>
        /// <param name="token">Токен для отмены задачи</param>
        /// <returns>Даты самого старого и самого свежего отчетов в БД</returns>
        [HttpGet]
        [Route("datesRange")]
        [Permission]
        [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetReportsDateRangeAsync(int idWell, CancellationToken token = default)
        {
            int? idCompany = User.GetCompanyId();

            if (idCompany is null)
                return Forbid();

            if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
                idWell, token).ConfigureAwait(false))
                return Forbid();

            var wellReportsDatesRange = reportService.GetDatesRangeOrDefault(idWell);

            return Ok(wellReportsDatesRange);
        }
    }
}