using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace RudderSdk.Core;
/// A scenario leaderboard node. End it with or claim with .
public sealed class LeaderboardEffect
{
private readonly EffectHandle _handle;
internal LeaderboardEffect(EffectHandle handle) => _handle = handle;
/// Run id.
public string RunId => _handle.RunId;
/// Scenario id.
public string ScenarioId => _handle.ScenarioId;
/// Node id.
public string NodeId => _handle.NodeId;
/// Node data payload.
public JObject Data => _handle.Data;
/// True after the effect was resolved once.
public bool IsResolved { get; private set; }
/// Reads a typed value from the node data.
public T Get(string key, T defaultValue = default!) => _handle.Get(key, defaultValue);
/// Posts the onEnd callback.
public Task EndAsync(CancellationToken cancellationToken = default) => ResolveAsync("onEnd", cancellationToken);
/// Posts the onEnd callback (fire-and-forget).
public void End() => Resolve("onEnd");
/// Posts the onClaim callback. The server matches live rank to a place.
public Task ClaimAsync(CancellationToken cancellationToken = default) => ResolveAsync("onClaim", cancellationToken);
/// Posts the onClaim callback (fire-and-forget).
public void Claim() => Resolve("onClaim");
private async Task ResolveAsync(string handle, CancellationToken cancellationToken)
{
if (IsResolved)
return;
IsResolved = true;
await _handle.CompleteAsync(handle, cancellationToken).ConfigureAwait(false);
}
private void Resolve(string handle)
{
if (IsResolved)
return;
IsResolved = true;
_handle.Complete(handle);
}
}