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

namespace Performance.Services
{
    [Authorize]
    public class AllotLogHub : Hub
    {
        private readonly IMemoryCache cache;
        private readonly ILogger<AllotLogHub> logger;

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

        public override Task OnConnectedAsync()
        {
            string key = Context.User.Claims.FirstOrDefault(t => t.Type == "id")?.Value;
            if (!string.IsNullOrEmpty(key))
            {
                if (cache.TryGetValue(key, out _))
                {
                    cache.Remove(key);
                }
                cache.Set(key, Context.ConnectionId);
            }
            logger.LogInformation($"用户在{DateTime.Now.ToString("yyyy年MM月dd日 hh时mm分ss秒")}创建连接");
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            string key = Context.User.Claims.FirstOrDefault(t => t.Type == "id")?.Value;
            if (!string.IsNullOrEmpty(key))
            {
                if (cache.TryGetValue(key, out _))
                {
                    cache.Remove(key);
                }
            }
            logger.LogInformation($"用户在{DateTime.Now.ToString("yyyy年MM月dd日 hh时mm分ss秒")}断开连接");
            return base.OnDisconnectedAsync(exception);
        }
    }
}
