
using Microsoft.Extensions.Options;

using Serilog;

namespace Forwarder.Modules.Ademco;

/// <summary>
/// Менеджер слушателей.
/// </summary>
/// <param name="serviceProvider">Сервис-провайдер.</param>
internal sealed class AdemcoHost(
	IServiceProvider serviceProvider)
	: BackgroundService
{
	/// <inheritdoc />
	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		while (!stoppingToken.IsCancellationRequested)
		{
			using var scope = serviceProvider.CreateScope();

			var options = scope.ServiceProvider.GetRequiredService<IOptions<AdemcoOptions>>().Value;

			var taskList = new List<Task>();

			var posts = options.Ports.Split(',')
				.Select(x => ushort.Parse(x.Trim()));

			foreach (var port in posts)
			{
				taskList.Add(this.RunListener(port, stoppingToken));
			}

			await Task.WhenAll(taskList);
		}
	}

	private async Task RunListener(ushort port, CancellationToken stoppingToken)
	{
		try
		{
			using var scope = serviceProvider.CreateScope();

			Log.Information("Create listener for port {Port}", port);

			var listener = scope.ServiceProvider.GetRequiredService<UdpPortListener>();
			await listener.Start(port, stoppingToken);
		}
		catch (Exception ex)
		{
			Log.Error(ex, "Manager execution error when listener running");
		}
	}
}
