using Microsoft.AspNetCore.Http.Features;

namespace EEMSServerCore.Hubs;

internal partial class ClientsMainHub(DeviceManager deviceManager, IEEMSBaseServerProvider provider) : Hub, IClientCaller
{
    public override Task OnConnectedAsync()
    {
        if (Context.Features.Get<IHttpConnectionFeature>() is IHttpConnectionFeature feature)
            provider?.OnConnected(feature.RemoteIpAddress!.ToString(), (ushort)feature.RemotePort, ServiceHub.ClinetHub);

        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        deviceManager.RemoveDevice(Context.ConnectionId, out DeviceInfo? device);

        if (device is not null && device.Guid.HasValue)
            ClientManager.DeviceClients.TryRemove(device.Guid.Value, out _);

        if (Context.Features.Get<IHttpConnectionFeature>() is IHttpConnectionFeature feature)
            provider?.OnDisConnected(feature.RemoteIpAddress!.ToString(), (ushort)feature.RemotePort, ServiceHub.ClinetHub);

        return base.OnDisconnectedAsync(exception);
    }

    public Task<Guid> RegisterDevice(DeviceInfo deviceInfo)
    {
        deviceInfo.Guid ??= Guid.NewGuid();
        deviceManager.LoginDevice(Context.ConnectionId, deviceInfo);
        ClientManager.DeviceClients[deviceInfo.Guid.Value] = Clients.Caller;
        return Task.FromResult(deviceInfo.Guid.Value);
    }
}
