using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Performance.Services
{
    public class NotificationsService : IAutoInjection
    {
        private readonly ILogger logger;
        private readonly IMemoryCache cache;
        private readonly IHubContext<AllotLogHub> hubContext;
        private readonly PerforLogdsignalrRepository repository;

        public NotificationsService(
            ILogger<NotificationsService> logger,
            IMemoryCache cache,
            IHubContext<AllotLogHub> hubContext,
            PerforLogdsignalrRepository repository
            )
        {
            this.logger = logger;
            this.cache = cache;
            this.hubContext = hubContext;
            this.repository = repository;
        }

        public void SendGenerateMessage(int userId, int allotId, string message, ComponentType type = ComponentType.info)
        {
            var info = new MessageInfo("", allotId, "生成绩效", message, Component.Notification, type);
            SendMessage(userId, info);
        }


        public void SendMessage(int userId, MessageInfo data)
        {
            string key = userId.ToString();
            if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId))
            {
                SendMessageToClient(connectionId, data);
            }
        }

        private void SaveLogToDataBase()
        {

        }

        private void SendMessageToClient(string connectionId, MessageInfo data, string method = "ReceiveMessage")
        {
            hubContext.Clients.Client(connectionId).SendAsync(method, data.Title, data);
        }
    }
}
