using System; using System.Collections.Generic; namespace Fateforge { public sealed class RewardedSlotCoordinator : IDisposable { readonly IRewardedAdService ads; readonly Func current; readonly Action save; readonly HashSet closed = new HashSet(); string opportunityRun; AdPurpose opportunityPurpose; bool receivedReward; public AdRequest Pending { get; private set; } public event Action Finished; public RewardedSlotCoordinator(IRewardedAdService ads, Func current, Action save) { this.ads = ads; this.current = current; this.save = save; ads.Result += Receive; } internal static bool CanRequest(Game game, AdPurpose purpose) { if (game == null) return false; return purpose == AdPurpose.ShopSlot ? game.State.stage == Stage.Shop && !game.State.adSlot : purpose == AdPurpose.ExtraCollect && game.State.stage == Stage.ReviveChoice && !game.State.reviveUsed; } public bool Request(AdPurpose purpose = AdPurpose.ShopSlot) { var game = current(); if (Pending != null || !CanRequest(game, purpose) || !ads.Available) return false; if (opportunityRun != game.State.id || opportunityPurpose != purpose) closed.Clear(); opportunityRun = game.State.id; opportunityPurpose = purpose; receivedReward = false; Pending = new AdRequest{runId=opportunityRun, requestId=Guid.NewGuid().ToString("N"), purpose=purpose}; if (ads.Show(Pending)) return true; Pending = null; return false; } void Receive(AdRequest request, AdResult result) { if (request == null || request.runId != opportunityRun || request.purpose != opportunityPurpose) return; bool active = request.requestId == Pending?.requestId; if (!active && (result != AdResult.Rewarded || !closed.Remove(request.requestId))) return; var game = current(); if (game == null || game.State.id != request.runId) { if (active) Pending = null; return; } if (result == AdResult.Rewarded) { bool granted = request.purpose == AdPurpose.ExtraCollect ? game.GrantExtraCollect(request.runId, request.requestId) : game.State.stage == Stage.Shop && game.GrantAdSlot(request.runId, request.requestId); if (!granted) return; // Commit immediately, then release the UI when the covering video closes. closed.Clear(); receivedReward = true; save(); if (Pending == null) Finished?.Invoke(AdResult.Rewarded); return; } if (result == AdResult.AwaitingLateReward && !receivedReward) closed.Add(request.requestId); Pending = null; Finished?.Invoke(receivedReward ? AdResult.Rewarded : result); } public void Dispose() { ads.Result -= Receive; Pending = null; } } }