using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
///
/// The work priorities slot: work type defName to priority 0 (off) to 4; a type that is not listed is
/// left alone. Names resolve with GetNamedSilentFail. Work types the pawn cannot do
/// (Pawn.WorkTypeIsDisabled) are skipped, which avoids the SetPriority error. The caste's own number is
/// stored even while manual priorities are off: the game then reads any nonzero value as on, and the
/// number takes effect once manual priorities are turned on, so members still match the caste after the
/// switch. The Follow rule works per type. The slot is off while the manageWorkPriorities setting is
/// off or an automatic work manager is active. A listed type of an official DLC that is off (Childcare
/// without Biotech) stays listed and is skipped, so it works again once the DLC is back.
///
public static class WorkSlot
{
public const int Off = 0;
public const int Highest = 1;
public const int Lowest = Pawn_WorkSettings.LowestPriority;
/// The automatic work managers, by package id, with the names the player sees.
public static readonly KeyValuePair[] Managers =
{
new KeyValuePair(Compat.WorkTab, "Work Tab"),
new KeyValuePair(Compat.FreeWill, "Free Will"),
new KeyValuePair(Compat.FreeWillUnstable, "Free Will"),
new KeyValuePair(Compat.WorkManager, "Work Manager"),
new KeyValuePair(Compat.AutoPriorities, "AutoPriorities"),
new KeyValuePair(Compat.WorkRoles, "WorkRoles"),
};
/// Package ids treated as active on top of the real mod list. For tests only.
public static readonly HashSet SimulatedActive = new HashSet(StringComparer.OrdinalIgnoreCase);
// The mod list can't change without a restart, so the real detection runs once.
private static string detectedManager;
private static bool detectionDone;
/// The name of the first active automatic work manager, or null.
public static string ActiveManager()
{
if (!detectionDone)
{
detectionDone = true;
detectedManager = Managers.Where(m => Compat.IsActive(m.Key)).Select(m => m.Value).FirstOrDefault();
}
if (detectedManager != null || SimulatedActive.Count == 0)
return detectedManager;
return Managers.Where(m => SimulatedActive.Contains(m.Key)).Select(m => m.Value).FirstOrDefault();
}
public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWorkPriorities;
/// The slot is written: the setting is on and no automatic work manager is active.
public static bool Active => SettingOn && ActiveManager() == null;
/// The game's "manual priorities" switch. Off: a work type is only on or off.
public static bool ManualPriorities => Current.Game?.playSettings == null || Current.Game.playSettings.useWorkPriorities;
/// A priority as the game treats it right now: with manual priorities off, any nonzero value is 3.
public static int Effective(int priority)
{
if (priority <= Off)
return Off;
return ManualPriorities ? priority : Pawn_WorkSettings.DefaultPriority;
}
/// The work types the manager lists: the visible ones, in the Work tab's order.
public static List Types() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(d => d.visible).ToList();
public static WorkTypeDef Resolve(string defName) => defName.NullOrEmpty() ? null : DefDatabase.GetNamedSilentFail(defName);
///
/// A listed work type of an official DLC that is off (Childcare without Biotech, Dark study without
/// Anomaly, Fishing without Odyssey): the caste keeps it and skips it until the DLC is on again.
///
public static bool IsDlcOff(string defName) =>
!defName.NullOrEmpty() && Resolve(defName) == null && DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName) != null;
/// Every listed type is of a DLC that is off, so writing the slot changes nothing. False for no entries.
public static bool AllDlcOff(IReadOnlyDictionary values) =>
values != null && values.Count > 0 && values.Keys.All(IsDlcOff);
///
/// "Start from nothing" turns the other work off only while at least one listed type is in the game,
/// so a caste that lists only work of a DLC that is off never leaves its members without work.
///
public static bool StripsOthers(IReadOnlyDictionary values, bool startFromNothing) =>
startFromNothing && values != null && values.Keys.Any(k => Resolve(k) != null);
///
/// Work type defName to priority from a value: a dictionary or any list of name and priority pairs.
/// Entries without a name or outside 0 to 4 are dropped. Null for null, anything else, or no entries.
///
public static Dictionary Normalize(object value)
{
if (!(value is IEnumerable> pairs))
return null;
var result = new Dictionary();
foreach (KeyValuePair kv in pairs)
{
if (!kv.Key.NullOrEmpty() && kv.Value >= Off && kv.Value <= Lowest)
result[kv.Key] = kv.Value;
}
return result.Count == 0 ? null : result;
}
public static bool Fits(object value) => value == null || value is IEnumerable>;
/// The pawn has initialized work settings.
public static bool HasWorkSettings(Pawn pawn) => pawn?.workSettings != null && pawn.workSettings.EverWork;
/// The pawn can take this work type: it exists and is not disabled for the pawn.
public static bool CanDo(Pawn pawn, WorkTypeDef def) => def != null && HasWorkSettings(pawn) && !pawn.WorkTypeIsDisabled(def);
///
/// The pawn already has the caste's value for this type, as the game treats both right now. A type
/// the pawn cannot do, or that no longer exists, never counts as different.
///
public static bool Matches(Pawn pawn, string defName, int casteValue)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def))
return true;
return Effective(pawn.workSettings.GetPriority(def)) == Effective(casteValue);
}
public static bool MatchesAll(Pawn pawn, IReadOnlyDictionary values)
{
if (values == null || !HasWorkSettings(pawn))
return false;
foreach (KeyValuePair kv in values)
{
if (!Matches(pawn, kv.Key, kv.Value))
return false;
}
return true;
}
/// The listed types where the pawn's priority differs from the caste's, in the Work tab's order.
public static List Differences(Pawn pawn, IReadOnlyDictionary values)
{
var result = new List();
if (values == null || !HasWorkSettings(pawn))
return result;
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (values.TryGetValue(def.defName, out int v) && !Matches(pawn, def.defName, v))
result.Add(def);
}
return result;
}
///
/// Writes one type. Skipped (false) when the type is gone or disabled for the pawn. The value is
/// stored as it is, also while manual priorities are off (the game then reads any nonzero value as
/// on, and GetPriority hides the stored number, so it is always written).
///
public static bool WriteType(Pawn pawn, string defName, int value)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def) || value < Off || value > Lowest)
return false;
if (!ManualPriorities || pawn.workSettings.GetPriority(def) != value)
pawn.workSettings.SetPriority(def, value);
return true;
}
///
/// Patient and Bed rest: the work types that send a hurt or sick pawn to bed. Every pawn starts with
/// them on and no backstory can turn them off (alwaysStartActive and no work tags), and a colonist or
/// slave has no other way to go to bed for treatment or rest. "Start from nothing" keeps them.
///
public static bool IsSelfCare(WorkTypeDef def) => def != null && def.alwaysStartActive && def.workTags == WorkTags.None;
/// The self-care work types (IsSelfCare), in the Work tab's order.
public static List SelfCareTypes() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(IsSelfCare).ToList();
///
/// Writes the listed types. startFromNothing first turns off every other work type except the
/// self-care ones (IsSelfCare), which stay as they are, for castes that should do only their listed
/// work; not while no listed type is in the game (StripsOthers). True when anything was written.
///
public static bool Write(Pawn pawn, IReadOnlyDictionary values, bool startFromNothing)
{
if (!HasWorkSettings(pawn) || values == null || values.Count == 0)
return false;
bool any = false;
if (StripsOthers(values, startFromNothing))
{
foreach (WorkTypeDef def in DefDatabase.AllDefsListForReading)
{
if (values.ContainsKey(def.defName) || IsSelfCare(def) || pawn.workSettings.GetPriority(def) == Off)
continue;
pawn.workSettings.SetPriority(def, Off);
}
any = true;
}
foreach (KeyValuePair kv in values)
{
if (WriteType(pawn, kv.Key, kv.Value))
any = true;
}
return any;
}
///
/// Every work type the caste decides, with its value: the listed ones, and with "Start from nothing"
/// (while it applies, StripsOthers) every other one except the self-care types, at off. Null while the
/// caste leaves work alone.
///
public static Dictionary Decided(Caste caste)
{
if (caste == null || !caste.IsManaged(CasteSlot.Work))
return null;
var result = new Dictionary(caste.WorkPriorities);
if (StripsOthers(caste.WorkPriorities, caste.WorkStartFromNothing))
{
foreach (WorkTypeDef def in DefDatabase.AllDefsListForReading)
{
if (!result.ContainsKey(def.defName) && !IsSelfCare(def))
result[def.defName] = Off;
}
}
return result;
}
/// The pawn's priority for every work type (activeOnly: only the types that are on), or null without work settings.
public static Dictionary Of(Pawn pawn, bool activeOnly = false)
{
if (!HasWorkSettings(pawn))
return null;
var result = new Dictionary();
foreach (WorkTypeDef def in DefDatabase.AllDefsListForReading)
{
int priority = pawn.workSettings.GetPriority(def);
if (!activeOnly || priority > Off)
result[def.defName] = priority;
}
return result;
}
/// The cycle of the manager's button: leave alone, 1, 2, 3, 4, off, leave alone.
public static int? Next(int? priority)
{
if (priority == null)
return Highest;
if (priority.Value == Off)
return null;
return priority.Value >= Lowest ? Off : priority.Value + 1;
}
/// The cycle backwards: leave alone, off, 4, 3, 2, 1, leave alone.
public static int? Previous(int? priority)
{
if (priority == null)
return Off;
if (priority.Value == Off)
return Lowest;
return priority.Value <= Highest ? (int?)null : priority.Value - 1;
}
/// A priority as the manager shows it: "-" for leave alone, "off", or the number.
public static string PriorityLabel(int? priority)
{
if (priority == null)
return "BlaxCastes_WorkLeaveAloneShort".Translate();
return priority.Value == Off ? (string)"BlaxCastes_WorkOff".Translate() : priority.Value.ToString();
}
public static string TypeLabel(WorkTypeDef def) => def == null ? "" : (def.labelShort.NullOrEmpty() ? def.label : def.labelShort).CapitalizeFirst();
public static string TypeLabel(string defName) => Resolve(defName) is WorkTypeDef def ? TypeLabel(def) : defName;
///
/// The listed types with their priority, in the Work tab's order: "Firefight 1, Grow 1". Off types say
/// "off". A type of a DLC that is off comes last with its DLC: "Childcare 1 (needs Biotech)".
///
public static string Summary(IReadOnlyDictionary values)
{
if (values == null || values.Count == 0)
return "BlaxCastes_Unmanaged".Translate();
var parts = new List();
var listed = new HashSet();
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (!values.TryGetValue(def.defName, out int v))
continue;
listed.Add(def.defName);
parts.Add(TypeLabel(def) + " " + PriorityLabel(v));
}
foreach (KeyValuePair kv in values)
{
if (listed.Contains(kv.Key))
continue;
parts.Add(IsDlcOff(kv.Key) ? DlcOffLabel(kv.Key, kv.Value) : kv.Key + " " + PriorityLabel(kv.Value));
}
return string.Join(", ", parts);
}
/// The listed types of a DLC that is off, as Summary words them; empty when there are none.
public static List DlcOffLabels(IReadOnlyDictionary values)
{
var result = new List();
if (values == null)
return result;
foreach (KeyValuePair kv in values.OrderBy(kv => kv.Key))
{
if (IsDlcOff(kv.Key))
result.Add(DlcOffLabel(kv.Key, kv.Value));
}
return result;
}
/// "Dark study 1 (needs Anomaly)": the def is not loaded, so its name comes from the defName.
private static string DlcOffLabel(string defName, int priority)
{
string name = GenText.SplitCamelCase(defName).ToLowerInvariant().CapitalizeFirst();
return "BlaxCastes_NeedsDlc".Translate((name + " " + PriorityLabel(priority)).Named("WHAT"),
DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName).Named("DLC"));
}
}
}