using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegrator.Handlers.Components;
using Telegrator.MadiatorCore;
using Telegrator.MadiatorCore.Descriptors;
namespace Telegrator.Handlers.Building
{
///
/// Internal handler used for awaiting specific update types.
/// Provides synchronization mechanism for waiting for updates of a particular type.
///
/// The type of update this awaiter handler waits for.
internal class AwaiterHandler(UpdateType handlingUpdateType) : UpdateHandlerBase(handlingUpdateType), IHandlerContainerFactory, IDisposable
{
///
/// Manual reset event used for synchronization.
///
private ManualResetEventSlim ResetEvent = new ManualResetEventSlim(false);
///
/// Gets the update that triggered this awaiter handler.
///
public Update HandlingUpdate { get; private set; } = null!;
///
/// Waits for the specified update type to be received.
///
/// The cancellation token to cancel the wait operation.
public void Wait(CancellationToken cancellationToken)
{
ResetEvent.Reset();
ResetEvent.Wait(cancellationToken);
}
///
/// Creates a handler container for this awaiter handler.
///
/// The awaiting provider (unused).
/// The handler information containing the update.
/// An empty handler container.
public IHandlerContainer CreateContainer(IAwaitingProvider _, DescribedHandlerInfo describedHandler)
{
HandlingUpdate = describedHandler.HandlingUpdate;
return new EmptyHandlerContainer();
}
///
/// Executes the awaiter handler by setting the reset event.
///
/// The handler container (unused).
/// The cancellation token (unused).
/// A completed task.
protected override Task ExecuteInternal(IHandlerContainer container, CancellationToken cancellation)
{
ResetEvent.Set();
return Task.FromResult(Result.Ok());
}
///
/// Disposes of the reset event.
///
public void Dispose()
{
ResetEvent.Dispose();
ResetEvent = null!;
}
}
}