using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.SignalR.Client;
using RobotNet.RobotShares.Dtos;
using RobotNet.Shares;

namespace RobotNet.WebApp.Clients;

public class TrafficHubClient: WebAssemblyHubClient
{
    public event Action<IEnumerable<TrafficAgentDto>>? TrafficAgentUpdated;
    private IDisposable? disTrafficAgentUpdated;

    public event Action? MapDeactive;
    private IDisposable? disMapDeactive;

    public TrafficHubClient(IAccessTokenProvider tokenProvider, Uri uri) : base(tokenProvider, uri)
    {
        disTrafficAgentUpdated = Connection.On<IEnumerable<TrafficAgentDto>>("TrafficAgentUpdated", agents => TrafficAgentUpdated?.Invoke(agents));
        disMapDeactive = Connection.On("TrafficManagerDeactive", () => MapDeactive?.Invoke());

    }

    public override async Task StopAsync()
    {
        if (disTrafficAgentUpdated != null)
        {
            disTrafficAgentUpdated.Dispose();
            disTrafficAgentUpdated = null;
        }
        if (disMapDeactive != null)
        {
            disMapDeactive.Dispose();
            disMapDeactive = null;
        }
        await base.StopAsync();
    }

    public Task TrafficActive(Guid mapId) => IsConnected ? Connection.InvokeAsync("TrafficActive", mapId) : Task.CompletedTask;

    public async Task<MessageResult<IEnumerable<TrafficMapDto>>> LoadTrafficMaps()
        => IsConnected ? await Connection.InvokeAsync<MessageResult<IEnumerable<TrafficMapDto>>>(nameof(LoadTrafficMaps)) : new(false, "Kết nối thất bại");

    public async Task<MessageResult<TrafficMapDto>> LoadTrafficMap(Guid mapId)
        => IsConnected ? await Connection.InvokeAsync<MessageResult<TrafficMapDto>>(nameof(LoadTrafficMap), mapId) : new(false, "Kết nối thất bại");
}
