using Microsoft.AspNetCore.SignalR;

namespace Diligent.WebAPI.Host.Hubs
{
    public class ConnectionHub : Hub
    {
        private static Dictionary<string, string> IDs { get; set; } = new();
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var msg = new StatusMessage { Id = IDs[Context.ConnectionId], M = "unsubscription" };
            IDs.Remove(Context.ConnectionId);
            await Clients.All.SendAsync("Notify", msg);
        }
        [HubMethodName("Subscribe")]
        public async Task Subscribe(string id)
        {
            if (!IDs.Any(n => n.Value == id))
                IDs[Context.ConnectionId] = id;

            string[] ids = new string[IDs.Count];
            IDs.Values.CopyTo(ids, 0);

            await Clients.Caller.SendAsync("ReceiveList", ids);
            var msg = new StatusMessage { Id = id, M = "subscription" };
            await Clients.Others.SendAsync("Notify", msg);
        }

        [HubMethodName("Unsubscribe")]
        public async Task Unsubscribe(SenderObj s)
        {
            IDs.Remove(s.ConnId);
            var msg = new StatusMessage { Id = s.Id, M = "unsubscription" };
            await Clients.Others.SendAsync("Notify", msg);
        }
    }
}
