using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using AsbCloudApp.Repositories;
using System.ComponentModel.DataAnnotations;

namespace AsbCloudWebApi.Controllers.SAUB;


/// <summary>
/// Наработка талевого каната
/// </summary>
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class TelemetryWirelineRunOutController : ControllerBase
{
    private readonly ITelemetryService telemetryService;
    private readonly IWellService wellService;
    private readonly IHubContext<TelemetryHub> telemetryHubContext;
    private readonly ITelemetryWirelineRunOutRepository repository;
    private static string SirnalRMethodGetDataName => "ReceiveWirelineRunOut";

    public TelemetryWirelineRunOutController(
        ITelemetryService telemetryService,
        IWellService wellService,
        IHubContext<TelemetryHub> telemetryHubContext,
        ITelemetryWirelineRunOutRepository repository)
    {
        this.telemetryService = telemetryService;
        this.wellService = wellService;
        this.telemetryHubContext = telemetryHubContext;
        this.repository = repository;
    }

    /// <summary>
    /// Принимает данные от панели
    /// </summary>
    /// <param name="uid"></param>
    /// <param name="dto"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpPost("{uid}")]
    [AllowAnonymous]
    public async Task<IActionResult> PostDataAsync(string uid, [FromBody, Required] TelemetryWirelineRunOutBaseDto dto, CancellationToken token)
    {
        var data = await repository.AddOrUpdateAsync(uid, dto, token);

        var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
        if (idWell is not null)
            _ = Task.Run(async () =>
            {
                var clients = telemetryHubContext.Clients.Group($"well_{idWell}");
                await clients.SendAsync(SirnalRMethodGetDataName, dto);
            }, CancellationToken.None);

        return Ok();
    }

    /// <summary>
    /// Выдает данные по скважине
    /// </summary>
    /// <param name="idWell"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpGet("{idWell}")]
    [Permission]
    public async Task<ActionResult<TelemetryWirelineRunOutDto>> GetDataAsync(int idWell, CancellationToken token)
    {
        int? idCompany = User.GetCompanyId();

        if (idCompany is null)
            return Forbid();

        bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
            idWell, token).ConfigureAwait(false);

        if (!isCompanyOwnsWell)
            return Forbid();

        var dto = await repository.GetOrDefaultAsync(idWell, token);

        if (dto is null)
            return NoContent();
        return Ok(dto);
    }

    /// <summary>
    /// Выдает данные по всем доступным скважинам
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    [HttpGet]
    [Permission]
    public async Task<ActionResult<IEnumerable<TelemetryWirelineRunOutDto>>> GetAllAsync(CancellationToken token)
    {
        int? idCompany = User.GetCompanyId();
        if (idCompany is null)
            return Forbid();

        var dtos = await repository.GetAllAsync((int)idCompany, token);
        return Ok(dtos);
    }
}