using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Background;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.SignalR
{
    // SignalR manual:
    // https://docs.microsoft.com/ru-ru/aspnet/core/signalr/introduction?view=aspnetcore-5.0
    //[SignalRHub]
    /// <summary>
    /// ReportsHub
    /// </summary>
    [Authorize]
    public class ReportsHub : BaseHub<IReportHubClient>
    {
        private readonly IWellService wellService;
        private readonly IReportService reportService;

        public ReportsHub(IWellService wellService, IReportService reportService)
        {
            this.wellService = wellService;
            this.reportService = reportService;
        }

        /// <summary>
        /// Добавление в группу, отправка данных о формировании отчета
        /// </summary>
        /// <param name="groupName">группа</param>
        /// <param name="idWell">ключ скважины</param>
        /// <param name="request">параметры запроса</param>
        /// <returns></returns>
        public async Task CreateReport(string groupName, int idWell, ReportParametersRequest request)
        {
            var idUser = Context.User?.GetUserId();
            var idCompany = Context.User?.GetCompanyId();

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

            if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, CancellationToken.None))
                return;

            await base.AddToGroup(groupName);

            void HandleReportProgressAsync(object progress, string id) =>
                Task.Run(async () =>
                {
                    await Clients.Group(groupName)
                    .GetReportProgress(progress, CancellationToken.None);
                }, CancellationToken.None);

            var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser, request, HandleReportProgressAsync);
        }
    }
}