using AyCode.Core.Extensions;
using AyCode.Core.Helpers;
using AyCode.Core.Loggers;
using AyCode.Services.SignalRs;
using Microsoft.AspNetCore.SignalR;

namespace AyCode.Services.Server.SignalRs;

public abstract class AcSignalRSendToClientService<TSignalRHub, TSignalRTags, TLogger>(IHubContext<TSignalRHub, IAcSignalRHubItemServer> signalRHub, IAcLoggerBase logger)
    where TSignalRHub: Hub<IAcSignalRHubItemServer>, IAcSignalRHubServer where TSignalRTags : AcSignalRTags where TLogger : IAcLoggerBase
{
    protected IAcLoggerBase Logger => logger;

    protected virtual async Task SendMessageToClient(IAcSignalRHubItemServer sendTo, int messageTag, object? content)
    {
        var signalParams = new SignalParams
        {
            Status = SignalResponseStatus.Success,
            DataSerializerType = AyCode.Core.Serializers.AcSerializerType.Binary
        };

        Logger.Info($"Server sending to client; {ConstHelper.NameByValue<TSignalRTags>(messageTag)}");
        await sendTo.OnReceiveMessage(messageTag, null, signalParams, content!);
    }

    public virtual Task SendMessageToAllClients(int messageTag, object? content)
        => SendMessageToClient(signalRHub.Clients.All, messageTag, content);

    public virtual Task SendMessageToConnection(string connectionId, int messageTag, object? content)
        => SendMessageToClient(signalRHub.Clients.Client(connectionId), messageTag, content);

    public virtual Task SendMessageToConnections(IEnumerable<string> connectionIds, int messageTag, object? content)
        => SendMessageToClient(signalRHub.Clients.Clients(connectionIds), messageTag, content);

    public virtual Task SendMessageToUser(string user, int messageTag, object? content)
        => SendMessageToClient(signalRHub.Clients.User(user), messageTag, content);

    public virtual Task SendMessageToUsers(IEnumerable<string> users, int messageTag, object? content)
        => SendMessageToClient(signalRHub.Clients.Users(users), messageTag, content);
}