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

namespace Performance.Services
{
    public class AllotLogHub : Hub
    {
        private readonly ILogger<AllotLogHub> logger;

        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;
            logger.LogDebug($"日志推送 断开连接{connectionId}");
            //1 查询用户分组信息
            var groupName = "";

            //2 删除数据库中用户分组数据
            if (RedisHelper.HExists("AllotLogGroup", connectionId))
            {
                groupName = RedisHelper.HGet("AllotLogGroup", connectionId);
                RedisHelper.HDel("AllotLogGroup", connectionId);
            }

            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;
            if (!RedisHelper.HExists("AllotLogGroup", connectionId))
            {
                //1 向数据库中插入用户及分组信息
                RedisHelper.HSet("AllotLogGroup", connectionId, groupName);

                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);
        }
    }
}
