using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
///
/// The enforcement queue (design: "Enforcement runs a tick later"). CaseFiler queues (case, stage)
/// entries from inside hooks; GameComponent_BlaxLaws.GameComponentTick drains them on a later tick, so
/// nothing acts inside a status change, an ingestion or an interaction. Every 250 ticks a sweep walks
/// the open cases only; every 2500 ticks the jailed ones. Nothing scans all pawns.
///
/// Not saved: entries refer to cases by id, and Refill rebuilds the queue from the cases after a load
/// (a stage with a row whose punishment never ran, a "Maintain only" write still owed).
///
public static class Enforcement
{
public const int SweepInterval = 250;
public const int SentenceInterval = 2500;
/// Ticks after the capture the "Maintain only" write lands (design: "Jail for N days").
public const int MaintainOnlyDelay = 2;
private struct Entry
{
public int caseId;
public CaseTask task;
public LawStage stage;
public int dueTick;
}
private static readonly List queue = new List();
private static readonly List due = new List();
/// Entries waiting. The component's tick returns at once while this is 0 and no case exists.
public static int Pending => queue.Count;
/// Queues the stage's punishment for the next tick.
public static void Enqueue(LawCase c, LawStage stage) => Schedule(c, CaseTask.Punish, stage, 1);
/// Queues a task for the case, delayTicks from now (at least 1).
public static void Schedule(LawCase c, CaseTask task, LawStage stage, int delayTicks)
{
if (c == null)
return;
int now = Find.TickManager?.TicksGame ?? 0;
queue.Add(new Entry { caseId = c.id, task = task, stage = stage, dueTick = now + Math.Max(1, delayTicks) });
}
/// Whether a task for the case is waiting.
public static bool IsQueued(LawCase c, CaseTask task)
{
if (c == null)
return false;
foreach (Entry e in queue)
{
if (e.caseId == c.id && e.task == task)
return true;
}
return false;
}
/// Drops every entry: a new game or a load. Then Refill.
public static void Reset() => queue.Clear();
///
/// After a load: queues each stage that has a row and never ran, and each "Maintain only" still owed
/// after a capture. Cases in Enforcing need nothing here; the 250-tick sweep re-issues their jobs.
///
public static void Refill(GameComponent_BlaxLaws comp)
{
if (comp == null)
return;
foreach (LawCase c in comp.Cases)
{
if (c.IsClosed)
continue;
foreach (LawStage s in new[] { LawStage.Planning, LawStage.DidIt })
{
if (c.LawIdFor(s) > 0 && !c.HasPunished(s))
Enqueue(c, s);
}
if (c.status == CaseStatus.Jailed && c.captureTick >= 0 && !c.maintainOnlyDone)
Schedule(c, CaseTask.MaintainOnly, c.activeStage, 1);
}
}
/// One game tick: due entries, then the sweeps.
internal static void Tick(GameComponent_BlaxLaws comp)
{
int now = Find.TickManager.TicksGame;
if (queue.Count > 0)
Drain(comp, now);
if (now % SweepInterval == 0)
Sweep(comp);
if (now % SentenceInterval == 0)
SentenceSweep(comp);
}
private static void Drain(GameComponent_BlaxLaws comp, int now)
{
due.Clear();
for (int i = 0; i < queue.Count; i++)
{
if (queue[i].dueTick <= now)
due.Add(queue[i]);
}
if (due.Count == 0)
return;
queue.RemoveAll(e => e.dueTick <= now);
foreach (Entry e in due)
{
LawCase c = comp.CaseById(e.caseId);
if (c == null)
continue;
try
{
switch (e.task)
{
case CaseTask.Punish:
Dispatch(comp, c, e.stage);
break;
case CaseTask.MaintainOnly:
Sentences.WriteMaintainOnly(c);
break;
}
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement " + e.task, ex);
}
}
}
///
/// Dispatches the case's queued punish entries whose punishment passes the filter now instead of next
/// tick, so a case about to close still carries out a stage filed in the same tick (a did-it Guilty,
/// Warn or Subdue filed during the subdue). Returns whether one ran.
///
internal static bool DispatchNow(LawCase c, Func filter)
{
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
if (c == null || comp == null || queue.Count == 0)
return false;
List now = null;
for (int i = 0; i < queue.Count; i++)
{
Entry e = queue[i];
if (e.caseId != c.id || e.task != CaseTask.Punish || c.HasPunished(e.stage))
continue;
PunishmentDef p = c.LawFor(e.stage)?.PunishmentDef;
if (p != null && filter(p))
(now ?? (now = new List())).Add(e);
}
if (now == null)
return false;
queue.RemoveAll(e => now.Contains(e));
foreach (Entry e in now)
{
try
{
Dispatch(comp, c, e.stage);
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement " + e.task, ex);
}
}
return true;
}
/// Starts the stage's punishment: once per stage, with a message, handing over from an unfinished earlier one.
private static void Dispatch(GameComponent_BlaxLaws comp, LawCase c, LawStage stage)
{
if (c.IsClosed || c.HasPunished(stage))
return;
Law law = c.LawFor(stage);
if (law == null)
return;
c.MarkPunished(stage);
PunishmentDef p = law.PunishmentDef;
CaseMessages.Filed(c, law, stage, p);
if (!BlaxLawsMod.S.enforceLaws)
{
// "Enforce laws" off: the case log runs, nothing is carried out.
if (c.activePunishment == null)
comp.CloseCase(c, CaseOutcomes.NotEnforced);
return;
}
if (p == null)
{
LawsLog.WarningOnce("punishment:" + law.punishment, "Law " + law.id + " names the punishment " + law.punishment + ", which isn't loaded; its cases are only listed.");
return;
}
if (!p.runsAlongside)
{
PunishmentDef active = ActiveOf(c);
if (active != null && active != p && !c.IsClosed)
active.Worker.Stop(c);
c.activePunishment = p.defName;
c.activeStage = stage;
}
p.Worker.Start(c, law, stage);
}
/// The case's running punishment, or null.
public static PunishmentDef ActiveOf(LawCase c) =>
c == null || c.activePunishment.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(c.activePunishment);
///
/// Every 250 ticks: closes planning cases whose break ended with nothing done, closes cases whose
/// offender is gone, and lets each active punishment retry and re-issue.
///
private static void Sweep(GameComponent_BlaxLaws comp)
{
if (!comp.AnyOpenCase)
return;
foreach (LawCase c in comp.OpenCases())
{
try
{
if (c.offender == null || LawCase.IsGone(c.offender))
{
if (c.status != CaseStatus.Jailed)
comp.CloseCase(c, CaseOutcomes.OffenderGone);
continue;
}
PunishmentDef active = ActiveOf(c);
if (active == null && c.status == CaseStatus.Open && c.IsBreakCase && c.stage == LawStage.Planning &&
!IsQueued(c, CaseTask.Punish) && !CaseFiler.StillInBreak(c))
{
comp.CloseCase(c, CaseOutcomes.BreakEnded);
continue;
}
if (active != null && c.status != CaseStatus.Jailed)
active.Worker.Sweep(c);
}
catch (Exception ex)
{
HookGuard.Fail("Enforcement sweep", ex);
}
}
}
/// Every 2500 ticks: the sentence check of each jailed case.
private static void SentenceSweep(GameComponent_BlaxLaws comp)
{
if (!comp.AnyOpenCase)
return;
foreach (LawCase c in comp.OpenCases())
{
if (c.status != CaseStatus.Jailed)
continue;
try
{
PunishmentDef active = ActiveOf(c);
if (active != null)
active.Worker.SentenceSweep(c);
else
Sentences.Check(c);
}
catch (Exception ex)
{
HookGuard.Fail("Sentence sweep", ex);
}
}
}
}
}