using System.Collections.Generic;
using Verse;
namespace BlaxCastes
{
///
/// Where a join happens, as a stack of scopes. A hook pushes a scope in a prefix and pops it in a
/// Harmony finalizer, so an exception inside the scope never leaves the stack dirty. When a pawn's
/// status changes, the innermost scope that covers the pawn names the join reason; without one,
/// the reason is the status fallback, resolved from the final status when the join is applied.
/// Only touched from the main thread.
///
public static class JoinScopes
{
/// Pawn.PreTraded while the player buys. Resolves to bought as slave or bought as colonist.
public const string Bought = "bought";
///
/// Pawn.PreTraded while the player sells. Status changes inside it queue nothing (selling a slave
/// briefly frees it before the faction changes); the sale itself writes the former-caste record.
///
public const string Sold = "sold";
private struct Scope
{
public string reason;
public Pawn pawn;
}
private static readonly List stack = new List();
/// Open scopes. 0 outside every hooked call.
public static int Depth => stack.Count;
///
/// Opens a scope. With a pawn it covers only that pawn, without one it covers every pawn.
/// Returns the token Pop needs.
///
public static int Push(string reason, Pawn pawn = null)
{
stack.Add(new Scope { reason = reason, pawn = pawn });
return stack.Count;
}
///
/// Closes the scope the token came from and any scope opened inside it that was not closed.
/// Token 0 (nothing was pushed) does nothing.
///
public static void Pop(int token)
{
if (token <= 0 || token > stack.Count)
return;
stack.RemoveRange(token - 1, stack.Count - token + 1);
}
/// The reason of the innermost scope that covers the pawn, or null.
public static string ReasonFor(Pawn pawn)
{
for (int i = stack.Count - 1; i >= 0; i--)
{
if (stack[i].pawn == null || stack[i].pawn == pawn)
return stack[i].reason;
}
return null;
}
}
}