using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Cors;
using TypedSignalR.Client;
using Tapper;
using server.Services;

namespace server.Hubs;

[Hub]
public interface IProgressHub
{
    Task<bool> Join(string taskId);
}

[Receiver]
public interface IProgressReceiver
{
    Task OnReceiveProgress(ProgressInfo message);
}

[TranspilationSource]
public enum ProgressStatus
{
    Pending,
    InProgress,
    Completed,
    Canceled,
    Failed
}

[TranspilationSource]
public class ProgressInfo
{
    public string TaskId { get; }
    public ProgressStatus Status { get; }
    public int ProgressPercent { get; }
    public string ErrorMessage { get; }
};

[Authorize]
[EnableCors("SignalR")]
public class ProgressHub : Hub<IProgressReceiver>, IProgressHub
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    private readonly IHubContext<ProgressHub, IProgressReceiver> _hubContext;
    private readonly ProgressTrackerService _tracker;

    public ProgressHub(IHubContext<ProgressHub, IProgressReceiver> hubContext, ProgressTrackerService tracker)
    {
        _hubContext = hubContext;
        _tracker = tracker;
    }

    public async Task<bool> Join(string taskId)
    {
        return _tracker.BindTask(taskId, Context.ConnectionId);
    }
}
