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

namespace Performance.Services
{
    public class HubGroupInfo
    {
        public DateTime AddTime { get; set; }
        public string ConnectionId { get; set; }
    }

    public class AllotLogHub : Hub
    {
        private readonly ILogger<AllotLogHub> logger;
        private readonly IMemoryCache cache;

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

        public override Task OnConnectedAsync()
        {
            logger.LogDebug($"日志推送 连接{Context.ConnectionId}");
            return base.OnConnectedAsync();
        }
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var connectionId = Context.ConnectionId;
            logger.LogDebug($"日志推送 断开连接{connectionId}");

            string key = $"AllotLogGroup_{connectionId}";
            //1 查询用户分组信息
            var groupName = "";
            //2 删除数据库中用户分组数据
            if (cache.TryGetValue(key, out string value))
            {
                cache.Remove(key);
            }

            logger.LogDebug($"日志推送 断开连接{connectionId}-{groupName}");
            //3 分组中删除用户
            Groups.RemoveFromGroupAsync(connectionId, groupName);
            return base.OnDisconnectedAsync(exception);
        }

        public async Task AddGroup(string token, string groupName)
        {
            var connectionId = Context.ConnectionId;
            string key = $"AllotLogGroup_{connectionId}";
            if (cache.TryGetValue(key, out string value))
            {
                cache.Remove(key);
            }
            cache.Set(key, groupName, new TimeSpan(1, 0, 0));

            logger.LogDebug($"日志推送 添加用户组{connectionId}-{groupName}");
            //2 将用户插入分组
            await Groups.AddToGroupAsync(connectionId, groupName);
        }

        public async Task SendMessage(string groupName, string message)
        {
            await Clients.Group(groupName).SendAsync("ReceiveMessage", "测试", message);
        }
    }
}
