using System;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Services.Notifications;
using AsbCloudWebApi.SignalR.Clients;
using AsbCloudWebApi.SignalR.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AsbCloudWebApi.SignalR;

[Authorize]
public class NotificationHub : BaseHub<INotificationHubClient>
{
   private readonly ConnectionManagerService connectionManagerService;
   private readonly NotificationService notificationService;
   private readonly NotificationPublisher notificationPublisher;

   public NotificationHub(ConnectionManagerService connectionManagerService,
      NotificationService notificationService,
      NotificationPublisher notificationPublisher)
   {
      this.connectionManagerService = connectionManagerService;
      this.notificationService = notificationService;
      this.notificationPublisher = notificationPublisher;
   }

   public override async Task OnConnectedAsync()
   {
      var idUser = Context.User?.GetUserId();

      if (!idUser.HasValue)
         return;

      string connectionId = Context.ConnectionId;

      connectionManagerService.AddOrUpdateConnection(idUser.Value, connectionId);

      await base.OnConnectedAsync();

      await notificationPublisher.PublishCountUnreadAsync(idUser.Value, CancellationToken.None);

      await notificationService.RenotifyAsync(idUser.Value,
         CancellationToken.None);
   }

   public override async Task OnDisconnectedAsync(Exception? exception)
   {      
      var idUser = Context.User?.GetUserId();

      if (!idUser.HasValue)
         return;
      
      connectionManagerService.RemoveConnection(idUser.Value);
      await base.OnDisconnectedAsync(exception);
   }
}