using System.Collections.Generic;
using System.Linq;
using BlaxLaws;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxLawsTests
{
///
/// The release's headline, planning path, end to end: the "Starter lawbook" action, a colonist forced into a
/// wake-up binge through the vanilla mental state call (so hook A files the case), a warden beside it and
/// no drug within reach. Nothing here opens or queues a case by hand.
///
public static class EndToEndSubdueTests
{
private static string BingeKey => ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge);
///
/// Warden work off for every other free colonist on the map (the quick test's starting colonists), put
/// back after the test. The enforcer mode stays "Wardens first", the default, so the warden is the only
/// warden and the nearest pick.
///
private static void SoleWarden(Pawn warden, Pawn offender)
{
var old = new List<(Pawn pawn, int priority)>();
foreach (Pawn p in Fixtures.Map.mapPawns.FreeColonistsSpawned.ToList())
{
if (p == warden || p == offender || !Enforcers.IsWarden(p))
continue;
old.Add((p, p.workSettings.GetPriority(WorkTypeDefOf.Warden)));
p.workSettings.SetPriority(WorkTypeDefOf.Warden, 0);
}
Fixtures.OnCleanup(() =>
{
foreach (var (pawn, priority) in old)
{
if (!pawn.Destroyed && pawn.workSettings != null)
pawn.workSettings.SetPriority(WorkTypeDefOf.Warden, priority);
}
});
}
[BlaxTest("end to end: under the Starter lawbook a forced wake-up binge with a warden beside it and no drug in reach is filed by hook A, beaten down with bruises by that warden and closes as subdued, one case for the incident")]
public static void StarterBingeSubdued()
{
T.Check(ActCatalogue.Get(BingeKey) != null, "the catalogue has no 'any drug binge' entry: the starter row would not resolve");
// The defaults the headline is about, whatever the test profile holds.
BlaxLawsSettings s = Fixtures.Settings;
s.enforceLaws = true;
s.enforcers = EnforcerMode.WardensFirst;
s.caseMessages = true;
s.subdueRemovesCatharsis = true;
// Only the subdue hits the binger (no social fight, no predator), and the binge has no drug to reach.
DetectionKit.QuietSocialFights();
EnforceFixtures.NoPredatorsHuntColonists();
DetectionKit.ClearDrugsOnMap();
Pawn offender = EnforceFixtures.Offender();
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(offender.Position, 2f, 5f));
SoleWarden(warden, offender);
// The real "Starter lawbook" action, the one the Laws tab's button calls.
T.Check(Lawbook.Find(BingeKey, DrugOptions.Any, LawStage.Planning) == null && Lawbook.Find(BingeKey, DrugOptions.Any, LawStage.DidIt) == null,
"setup: a starter binge row is already in the book");
int added = LawbookUi.PressStarter();
Law plan = Lawbook.Find(BingeKey, DrugOptions.Any, LawStage.Planning);
T.Check(added > 0 && plan != null, "the Starter lawbook action added no 'any drug binge, planning' row (added " + added + ")");
T.Equal("Subdue", plan.punishment, "punishment of the starter's 'any drug binge, planning'");
T.Check(plan.enabled && plan.Resolves, "the starter's planning row is off or doesn't resolve: " + plan.MissingText);
// One wake-up within reach makes it the only drug the binge can choose (MentalState_BingingDrug.cs:67,
// AddictionUtility.cs:120-139); it is gone before the first tick, so the binger never reaches a drug.
Thing wake = DetectionKit.ItemNear(offender, ThingDefOf.WakeUp, 1);
HashSet before = EnforceFixtures.Injuries(offender);
string subduedText = "BlaxLaws_MsgSubdued".Translate(offender.LabelShort, warden.LabelShort);
int subduedBefore = EnforceFixtures.MessagesWith(subduedText);
EnforceFixtures.ForceBreak(offender, DefDatabase.GetNamed("Binging_DrugExtreme"));
T.Equal("WakeUp", (offender.MentalState as MentalState_BingingDrug)?.chemical?.defName, "fixture: the binge's chemical");
wake.Destroy(DestroyMode.Vanish);
T.Equal(0, Fixtures.Map.listerThings.ThingsInGroup(ThingRequestGroup.Drug).Count, "fixture: drugs left on the map");
// Hook A filed it inside the vanilla call: no tick has passed.
List filed = Fixtures.Comp.CasesOf(offender).ToList();
T.Equal(1, filed.Count, "cases of the binger right after the break started (hook A)");
LawCase c = filed[0];
T.Equal(BingeKey, c.actKey, "the case's act");
T.Equal(plan.id, c.planningLawId, "the case's planning row: the starter's");
T.Equal(LawStage.Planning, c.stage, "the case's stage at the start");
T.Equal("Binging_DrugExtreme", c.breakState, "the case's break");
T.Check(Enforcement.IsQueued(c, CaseTask.Punish), "the planning case isn't queued for its punishment");
var enforcers = new HashSet();
bool ran = false;
bool done = EnforceFixtures.RunUntil(() =>
{
if (SubdueFlow.Runs(c))
ran = true;
foreach (Pawn p in EnforceFixtures.EnforcersOn(offender))
enforcers.Add(p);
return offender.Downed && c.IsClosed;
}, EnforceFixtures.SubdueTicks);
string story = EnforceFixtures.SubdueStory(c, offender, before) + "; " + EnforceFixtures.EnforcerStory(warden, c);
T.Check(ran, "no subdue ever ran; " + story);
T.Check(done, "the binger isn't downed with its case closed within " + EnforceFixtures.SubdueTicks + " ticks; " + story);
T.Equal(CaseOutcomes.Subdued, c.outcome, "the case's outcome");
T.Check(c.enforcer == warden, "the case's enforcer is " + (c.enforcer?.LabelShort ?? "nobody") + ", not the warden beside the binger");
T.Check(enforcers.Count == 1 && enforcers.Contains(warden), "pawns that enforced: " + string.Join(", ", enforcers.Select(p => p.LabelShort)));
// The subdue ran (ran above); closing the case clears the punishment in progress (CloseCase).
T.Equal(null, c.activePunishment, "the punishment in progress on the closed case");
T.Check(c.HasPunished(LawStage.Planning), "the planning stage isn't marked punished");
T.Equal(LawStage.Planning, c.stage, "the case's stage at the end: no dose was taken");
T.Equal(0, c.count, "doses counted");
T.Equal(subduedBefore + 1, EnforceFixtures.MessagesWith(subduedText), "messages that the warden subdued the binger (the driver's downing hit)");
// Downed by the subdue's hits, not by anything else.
List fresh = EnforceFixtures.NewInjuries(offender, before);
T.Check(fresh.Count > 0, "downed without a hit");
List notBruises = fresh.Where(h => h.def != EnforceFixtures.Bruise).Select(EnforceFixtures.Describe).ToList();
T.Check(notBruises.Count == 0, "injuries that aren't bruises: " + string.Join("; ", notBruises));
List onHead = fresh.Where(h => h.Part == null || SubdueHits.InHeadOrNeck(offender, h.Part)).Select(EnforceFixtures.Describe).ToList();
T.Check(onHead.Count == 0, "hits on the head or neck: " + string.Join("; ", onHead));
T.Check(!offender.Dead, "the binger died");
T.Check(!warden.guilt.IsGuilty, "the warden is guilty");
T.Check(offender.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis) == null, "the subdued binger has Catharsis");
// One case for the incident, also a sweep later, and nobody is sent again.
Fixtures.Tick(Enforcement.SweepInterval + 1);
List after = Fixtures.Comp.CasesOf(offender).Where(x => x.actKey == BingeKey || x.IsBreakCase).ToList();
T.Equal(1, after.Count, "binge cases of the binger a sweep after the subdue: " + string.Join("; ", after.Select(x => x.ToString())));
T.Check(after[0] == c && c.IsClosed && c.outcome == CaseOutcomes.Subdued, "the case a sweep later: " + c);
T.Check(!EnforceFixtures.AnyEnforcementJobOn(offender), "an enforcement job on the binger a sweep after the subdue");
}
}
}