using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.SignalR;

namespace AsbCloudWebApi.SignalR;

public class WellInfoHub : BaseHub<IWellInfoHubClient>, IIntegrationEventHandler<UpdateWellInfoEvent>
{
   private readonly IHubContext<WellInfoHub, IWellInfoHubClient> hubContext;
   private readonly IWellService wellService;
   private readonly WellInfoService wellInfoService;

   public WellInfoHub(IHubContext<WellInfoHub, IWellInfoHubClient> hubContext,
      IWellService wellService,
      WellInfoService wellInfoService)
   {
      this.hubContext = hubContext;
      this.wellService = wellService;
      this.wellInfoService = wellInfoService;
   }

   public override async Task AddToGroup(string groupName)
   {
      var idWell = int.Parse(groupName.Split('_')[2]);
      
      await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

      await HandleAsync(new UpdateWellInfoEvent(idWell), CancellationToken.None);
   }

   public async Task HandleAsync(UpdateWellInfoEvent integrationEvent, CancellationToken cancellationToken)
   {
      var well = await wellService.GetOrDefaultAsync(integrationEvent.IdWell, cancellationToken);

      if(well is null)
         return;
      
      var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == well.Id);

      await hubContext.Clients.Group($"well_info_{integrationEvent.IdWell}")
         .UpdateWellInfo(new
         {
            Well = well,
            WellInfo = wellInfo 
         }, cancellationToken);
   }
}