using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using RudderSdk.Core.Models.Leaderboards; namespace RudderSdk.Core; /// /// Leaderboards. Resolve a board with and work through /// the returned . /// public sealed class LeaderboardsService { private readonly RudderClient _client; private readonly Dictionary _cache = new(); internal LeaderboardsService(RudderClient client) => _client = client; /// Returns the (cached) handle for the leaderboard with the given slug. public LeaderboardHandle FindBySlug(string slug) { if (!_cache.TryGetValue(slug, out var leaderboard)) { leaderboard = new LeaderboardHandle(slug, this); _cache[slug] = leaderboard; } return leaderboard; } internal Task GetRankingAsync(string slug, int limit, CancellationToken cancellationToken) => _client.SendAsync( "GET", "/sdk/v1/leaderboards/" + Url.Encode(slug) + "/ranking" + Url.Query(("limit", limit > 0 ? limit.ToString() : null)), cancellationToken); internal Task SubmitScoreAsync(string slug, double score, CancellationToken cancellationToken) => _client.SendAsync( "POST", "/sdk/v1/leaderboards/" + Url.Encode(slug) + "/submit-score", new SubmitScoreRequest { Slug = slug, Score = score }, cancellationToken); } /// Operations on one leaderboard. public sealed class LeaderboardHandle { private readonly LeaderboardsService _service; internal LeaderboardHandle(string slug, LeaderboardsService service) { Slug = slug; _service = service; } /// Leaderboard slug. public string Slug { get; } /// Entries fetched by the last call. public IReadOnlyList Entries { get; private set; } = new List(); /// Submits a score for the current player. public Task SubmitAsync(double score, CancellationToken cancellationToken = default) => _service.SubmitScoreAsync(Slug, score, cancellationToken); /// Fetches the top entries and caches them in . public async Task> ListAsync(int limit = 100, CancellationToken cancellationToken = default) { var response = await _service.GetRankingAsync(Slug, limit, cancellationToken).ConfigureAwait(false); Entries = response?.Entries ?? new List(); return Entries; } }