namespace EEMSServerCore.HubSender;

public class ClientCaller : IClientProvider
{
    private Task<bool> SendAsync(Guid guid, string name)
    {
        if (string.IsNullOrEmpty(name))
            return Task.FromResult(false);
        if (ClientManager.DeviceClients.TryGetValue(guid, out ISingleClientProxy? client) || client is null)
            return Task.FromResult(false);

        try
        {
            client.SendAsync(name);
        }
        catch
        {
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }

    private Task<bool> SendAsync<T>(Guid guid, string name, T para)
    {
        if (string.IsNullOrEmpty(name))
            return Task.FromResult(false);

        if (ClientManager.DeviceClients.TryGetValue(guid, out ISingleClientProxy? client) || client is null)
            return Task.FromResult(false);

        try
        {
            client.SendAsync(name, para);
        }
        catch
        {
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }

    private Task<bool> SendAsync<T1, T2>(Guid guid, string name, T1 para1, T2 para2)
    {
        if (string.IsNullOrEmpty(name))
            return Task.FromResult(false);

        if (!ClientManager.DeviceClients.TryGetValue(guid, out ISingleClientProxy? client) || client is null)
            return Task.FromResult(false);

        try
        {
            client.SendAsync(name, para1, para2);
        }
        catch
        {
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }

    private Task<bool> SendAsync<T1, T2, T3>(Guid guid, string name, T1 para1, T2 para2, T3 para3)
    {
        if (string.IsNullOrEmpty(name))
            return Task.FromResult(false);

        if (ClientManager.DeviceClients.TryGetValue(guid, out ISingleClientProxy? client) || client is null)
            return Task.FromResult(false);

        try
        {
            client.SendAsync(name, para1, para2, para3);
        }
        catch
        {
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }

    private Task<bool> SendAsync<T1, T2, T3, T4>(Guid guid, string name, T1 para1, T2 para2, T3 para3, T4 para4)
    {
        if (string.IsNullOrEmpty(name))
            return Task.FromResult(false);

        if (ClientManager.DeviceClients.TryGetValue(guid, out ISingleClientProxy? client) || client is null)
            return Task.FromResult(false);

        try
        {
            client.SendAsync(name, para1, para2, para3, para4);
        }
        catch
        {
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }

    Task<bool> IClientProvider.RequestFile(Guid guid, FileType fileType)
    {
        return this.SendAsync(guid, "RequestFile", guid, fileType);
    }
}
