using Microsoft.AspNetCore.Http.Features;
using SqlSugarORM;

namespace EEMSServerCore.Hubs;

internal partial class ClientsMainHub(DeviceManager deviceManager, IEEMSBaseServerProvider provider, SqlSugarCustom orm) : 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();
        deviceInfo.IP ??= string.Empty;

        if (!orm.AddOrUpdate("Devices", deviceInfo, t => t.Guid == deviceInfo.Guid))
            return Task.FromResult(Guid.Empty);

        deviceManager.LoginDevice(Context.ConnectionId, deviceInfo);
        ClientManager.DeviceClients[deviceInfo.Guid.Value] = Clients.Caller;
        return Task.FromResult(deviceInfo.Guid.Value);
    }

    public Task<bool> UpdateRealTimeData(Dictionary<string, object> realtimeData)
    {
        throw new NotImplementedException();
    }
}
