using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Performance.Services
{
    public class AllotLogHub : Hub
    {
        private readonly ILogger<AllotLogHub> logger;
        private static ConcurrentDictionary<int, List<ConnectionUser>> _pairs
            = new ConcurrentDictionary<int, List<ConnectionUser>>();

        public AllotLogHub(ILogger<AllotLogHub> logger)
        {
            this.logger = logger;
        }

        public override Task OnConnectedAsync()
        {
            logger.LogDebug($"日志推送 连接{Context.ConnectionId}");

            return base.OnConnectedAsync();
        }
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var connectionId = Context.ConnectionId;
            var userId = Context.User?.Claims.FirstOrDefault(w => w.Type == "id").Value ?? "";

            if (!string.IsNullOrEmpty(userId))
            {
                foreach (var item in _pairs)
                {
                    var conn = item.Value.FirstOrDefault(w => w.ConnectionId == connectionId);
                    if (conn != null)
                    {
                        Groups.RemoveFromGroupAsync(connectionId, item.Key.ToString()).Wait();
                        logger.LogDebug($"日志推送 断开连接{connectionId}-{item.Key}-{userId}");
                    }
                }
            }

            return base.OnDisconnectedAsync(exception);
        }

        public async Task AddGroup(string token, int groupName)
        {
            var connectionId = Context.ConnectionId;

            var userId = Context.User?.Claims.FirstOrDefault(w => w.Type == "id").Value ?? "";

            if (!string.IsNullOrEmpty(userId))
            {
                if (_pairs.ContainsKey(groupName))
                    _pairs[groupName].Add(new ConnectionUser { ConnectionId = connectionId, UserId = userId });
                else
                    _pairs[groupName] = new List<ConnectionUser> { new ConnectionUser { ConnectionId = connectionId, UserId = userId } };
                await Groups.AddToGroupAsync(connectionId, groupName.ToString());
            }

            logger.LogDebug($"日志推送 添加用户组{connectionId}-{groupName}-{userId}");

        }

        class ConnectionUser
        {
            public string ConnectionId { get; set; }
            public string UserId { get; set; }
        }
    }
}
