using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.IntegrationEvents; using AsbCloudApp.IntegrationEvents.Interfaces; using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb.Model; using Microsoft.AspNetCore.SignalR; namespace AsbCloudWebApi.SignalR; public class WellHub : Hub, IIntegrationEventHandler { private const string groupTemplate = "update_id_well_{0}"; private readonly IHubContext hubContext; private readonly IWellService wellService; private readonly IWellOperationRepository wellOperationRepository; public WellHub(IHubContext hubContext, IWellService wellService, IWellOperationRepository wellOperationRepository) { this.hubContext = hubContext; this.wellService = wellService; this.wellOperationRepository = wellOperationRepository; } public async Task OnConnectedAsync(int idWell) { await base.OnConnectedAsync(); await Groups.AddToGroupAsync(Context.ConnectionId, string.Format(groupTemplate, idWell)); await HandleAsync(new UpdateWellEvent(idWell), CancellationToken.None); } public async Task HandleAsync(UpdateWellEvent integrationEvent, CancellationToken cancellationToken) { const string method = "update_well"; var well = await wellService.GetOrDefaultAsync(integrationEvent.IdWell, cancellationToken); if(well is null) return; well.Section = (await wellOperationRepository.GetAsync(new WellOperationRequest { IdWell = integrationEvent.IdWell, OperationType = WellOperation.IdOperationTypeFact }, cancellationToken)).MaxBy(o => o.DateStart)?.WellSectionTypeName; await hubContext.Clients.Group(string.Format(groupTemplate, integrationEvent.IdWell)) .SendAsync(method, new object[] { well }, cancellationToken); } }