using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Services.Notifications;
using Microsoft.AspNetCore.SignalR;

namespace AsbCloudWebApi.SignalR.Services;

public class SignalRNotificationTransportService : INotificationTransportService
{
	private readonly ConnectionManagerService connectionManagerService;
	private readonly IHubContext<NotificationHub> notificationHubContext;

	public SignalRNotificationTransportService(ConnectionManagerService connectionManagerService,
		IHubContext<NotificationHub> notificationHubContext)
	{
		this.connectionManagerService = connectionManagerService;
		this.notificationHubContext = notificationHubContext;
	}

	public int IdTransportType => 0;

	public async Task SendAsync(NotificationDto notification, 
		CancellationToken cancellationToken)
	{
		const string method = "receiveNotifications";
		
		var connectionId = connectionManagerService.GetConnectionIdByUserId(notification.IdUser);
					
		if (!string.IsNullOrWhiteSpace(connectionId))
		{
			notification.SentDate = DateTime.UtcNow;
			
			await notificationHubContext.Clients.Client(connectionId)
				.SendAsync(method,
					notification,
					cancellationToken);
		}
	}

	public Task SendRangeAsync(IEnumerable<NotificationDto> notifications, 
		CancellationToken cancellationToken)
	{
		var tasks = notifications
			.Select(notification => SendAsync(notification, cancellationToken));

		return Task.WhenAll(tasks);
	}
}