Decompiled source of WorkerPresets v0.1.3

plugins/WorkerPresets.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Clickable;
using SuperFantasyKingdom.Tavern;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("StaffingChecks")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WorkerPresets")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: AssemblyInformationalVersion("0.1.3+7c1f60f0c649eb99669ef18e09afe2a1bc187e02")]
[assembly: AssemblyProduct("WorkerPresets")]
[assembly: AssemblyTitle("WorkerPresets")]
[assembly: AssemblyVersion("0.1.3.0")]
namespace WorkerPresets;

internal sealed class AssignmentPanelFit : MonoBehaviour
{
	private RectTransform frame;

	private RectTransform panel;

	private RectTransform ribbon;

	private Transform owner;

	private Transform resourceBar;

	private readonly List<Graphic> counters = new List<Graphic>();

	private readonly Vector3[] corners = (Vector3[])(object)new Vector3[4];

	private float factor = 1f;

	private float shift;

	private float nextCheck;

	internal static void Bind(Transform selection, Transform launcher)
	{
		Transform parent = selection.parent;
		RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
		Transform obj = ((val != null) ? ((Transform)val).parent : null);
		RectTransform val2 = (RectTransform)(object)((obj is RectTransform) ? obj : null);
		Transform obj2 = ((val2 != null) ? ((Transform)val2).Find("HeaderContainer/Header") : null);
		RectTransform val3 = (RectTransform)(object)((obj2 is RectTransform) ? obj2 : null);
		if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val3))
		{
			AssignmentPanelFit obj3 = ((Component)val2).GetComponent<AssignmentPanelFit>() ?? ((Component)val2).gameObject.AddComponent<AssignmentPanelFit>();
			obj3.Restore();
			obj3.frame = val2;
			obj3.panel = val;
			obj3.ribbon = val3;
			obj3.owner = launcher;
			UIHeader obj4 = Object.FindObjectOfType<UIHeader>();
			obj3.resourceBar = ((obj4 != null) ? ((Component)obj4).transform.Find("PanelResources") : null);
			obj3.nextCheck = 0f;
			((Behaviour)obj3).enabled = true;
		}
	}

	private void OnDisable()
	{
		Restore();
	}

	private void Restore()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)frame) && (factor != 1f || shift != 0f))
		{
			RectTransform obj = frame;
			((Transform)obj).localScale = ((Transform)obj).localScale / factor;
			RectTransform obj2 = frame;
			obj2.anchoredPosition -= Vector2.up * shift;
		}
		factor = 1f;
		shift = 0f;
	}

	private Rect Bounds(RectTransform rect, Camera camera)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		rect.GetWorldCorners(corners);
		Vector2 val = RectTransformUtility.WorldToScreenPoint(camera, corners[0]);
		Vector2 val2 = RectTransformUtility.WorldToScreenPoint(camera, corners[2]);
		return Rect.MinMaxRect(val.x, val.y, val2.x, val2.y);
	}

	private void LateUpdate()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)owner) || !((Component)owner).gameObject.activeInHierarchy)
		{
			((Behaviour)this).enabled = false;
		}
		else
		{
			if (Time.unscaledTime < nextCheck)
			{
				return;
			}
			nextCheck = Time.unscaledTime + 0.12f;
			Canvas rootCanvas = ((Component)frame).GetComponentInParent<Canvas>().rootCanvas;
			Camera val = (((int)rootCanvas.renderMode == 0) ? null : rootCanvas.worldCamera);
			Rect val2 = Bounds(ribbon, val);
			Rect val3 = Bounds(panel, val);
			float num = (((Rect)(ref val2)).yMax - ((Rect)(ref val3)).yMin) / factor;
			if (num <= 0f)
			{
				return;
			}
			Rect safeArea = Screen.safeArea;
			float num2 = ((Rect)(ref safeArea)).yMax;
			float yMin = ((Rect)(ref safeArea)).yMin;
			if (Object.op_Implicit((Object)(object)resourceBar))
			{
				((Component)resourceBar).GetComponentsInChildren<Graphic>(false, counters);
				foreach (Graphic counter in counters)
				{
					if (((Behaviour)counter).isActiveAndEnabled && !(counter.color.a <= 0f))
					{
						Rect val4 = Bounds(counter.rectTransform, val);
						if (((Rect)(ref val4)).yMin > ((Rect)(ref safeArea)).center.y && ((Rect)(ref val4)).xMax > ((Rect)(ref val2)).xMin && ((Rect)(ref val4)).xMin < ((Rect)(ref val2)).xMax)
						{
							num2 = Mathf.Min(num2, ((Rect)(ref val4)).yMin);
						}
					}
				}
			}
			float num3 = 8f * rootCanvas.scaleFactor;
			num2 -= num3;
			yMin += num3;
			if (num2 <= yMin)
			{
				return;
			}
			float num4 = Mathf.Min(1f, (num2 - yMin) / num);
			Transform parent = ((Transform)frame).parent;
			float num5 = RectTransformUtility.WorldToScreenPoint(val, parent.TransformPoint(Vector3.up)).y - RectTransformUtility.WorldToScreenPoint(val, parent.position).y;
			if (!(num5 <= 0f))
			{
				float y = RectTransformUtility.WorldToScreenPoint(val, ((Transform)frame).position).y;
				float num6 = y - shift * num5;
				float num7 = num6 + (((Rect)(ref val2)).yMax - y) * num4 / factor;
				float num8 = num6 + (((Rect)(ref val3)).yMin - y) * num4 / factor;
				float num9 = Mathf.Clamp(0f, yMin - num8, num2 - num7) / num5;
				if (!(Mathf.Abs(num4 - factor) < 0.001f) || !(Mathf.Abs(num9 - shift) < 0.25f))
				{
					RectTransform obj = frame;
					((Transform)obj).localScale = ((Transform)obj).localScale * (num4 / factor);
					RectTransform obj2 = frame;
					obj2.anchoredPosition += Vector2.up * (num9 - shift);
					factor = num4;
					shift = num9;
				}
			}
		}
	}
}
internal sealed class CityStaffing
{
	private readonly Dictionary<string, BuildingCity> sources = new Dictionary<string, BuildingCity>();

	internal readonly Dictionary<string, Workplace> Sites = new Dictionary<string, Workplace>();

	private int otherWorkers;

	private int otherCarriers;

	private static readonly FieldRef<UIBuildingOverlayElementWorker, BuildingCity> RowBuilding = AccessTools.FieldRefAccess<UIBuildingOverlayElementWorker, BuildingCity>("m_Building");

	private static readonly FieldRef<UIBuildingOverlayElementWorker, Transform> RowView = AccessTools.FieldRefAccess<UIBuildingOverlayElementWorker, Transform>("m_OverlayElement");

	internal static string Key(BuildingCity building)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = ((Component)building).transform.position;
		return Workplace.Plot(((Object)building).name.Replace("(Clone)", "").Trim(), position.x, position.y);
	}

	private static bool HasWorkerControl(BuildingCity building)
	{
		List<UIBuildingOverlayElement> list = ((Component)building).GetComponent<UIBuildingOverlay>()?.buttons;
		if (list == null)
		{
			return false;
		}
		foreach (UIBuildingOverlayElement item in list)
		{
			if (item is UIBuildingOverlayElementWorker)
			{
				return true;
			}
			if (item is UIBuildingOverlayElementVein || item is UIBuildingOverlayElementWaterExpedition)
			{
				return false;
			}
		}
		return false;
	}

	private static bool Specialist(BuildingCity b)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		if ((int)b.GetBuildingSize() == 0)
		{
			return ((Building)b).CanUpgradeBeActivated();
		}
		return false;
	}

	private static int Current(BuildingCity b)
	{
		if (!Specialist(b))
		{
			return b.GetPossibleWorkers();
		}
		return ((Building)b).IsUpgradeActive() ? 1 : 0;
	}

	internal CityStaffing()
	{
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		CityManager instance = CityManager.Instance;
		foreach (IGrouping<string, BuildingCity> item in (from b in instance.GetBuildings().Concat(instance.GetOutposts())
			where (Object)(object)b != (Object)null && ((Behaviour)b).isActiveAndEnabled && !b.ShouldRemove()
			select b).Distinct().GroupBy(Key))
		{
			foreach (BuildingCity item2 in item)
			{
				bool flag = Specialist(item2);
				if (item.Count() != 1 || !HasWorkerControl(item2) || (!flag && ((Building)item2).GetMaxWorkers() < 1))
				{
					if (item2.CanCarrierWork())
					{
						otherCarriers += item2.GetPossibleJobs();
					}
					else
					{
						otherWorkers += item2.GetPossibleJobs();
					}
					continue;
				}
				int num = (flag ? 1 : (item2.AssignJobsIndividually() ? 9 : ((Building)item2).GetMaxWorkers()));
				sources.Add(item.Key, item2);
				Vector3 position = ((Component)item2).transform.position;
				Sites.Add(item.Key, new Workplace
				{
					Key = item.Key,
					BuildingName = ((Building)item2).GetTitle(),
					Title = $"{((Building)item2).GetTitle()} ({position.x:0.##}, {position.y:0.##})",
					Current = Current(item2),
					Max = num,
					Min = ((!flag && item2.AssignJobsIndividually()) ? Math.Min(num, item2.GetCurrentlyWorking()) : 0),
					Carrier = item2.CanCarrierWork(),
					Individual = (!flag && item2.AssignJobsIndividually()),
					Specialist = flag,
					CrewSize = (flag ? 1 : item2.GetWorkerIncrementAmount()),
					JobCapacity = ((!(item2 is BuildingGeneratingElves)) ? (flag ? 1 : ((Building)item2).GetMaxWorkers()) : 0)
				});
			}
		}
	}

	internal List<Entry> Capture()
	{
		return (from b in Sites.Values.OrderBy<Workplace, string>((Workplace b) => b.Key, StringComparer.Ordinal)
			select b.Capture()).ToList();
	}

	internal Preview Plan(Layout layout)
	{
		return new Preview(layout, Sites, JobManager.Instance.GetWorkerAmount(), JobManager.Instance.GetCarrierAmount(), otherWorkers, otherCarriers);
	}

	internal void Apply(Preview plan)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Expected O, but got Unknown
		GameObject val = Object.Instantiate<GameObject>(Resources.Load<GameObject>("UI/OverlayElementWorker"));
		try
		{
			val.SetActive(false);
			UIBuildingOverlayElementWorker val2 = new UIBuildingOverlayElementWorker();
			RowView.Invoke(val2) = val.transform;
			foreach (Change item in plan.InApplyOrder())
			{
				BuildingCity val3 = sources[item.Saved.Key];
				if (!item.Saved.Removed && !((Object)(object)val3 == (Object)null) && !val3.ShouldRemove())
				{
					ApplyRow(val2, val3, item.Target);
				}
			}
		}
		finally
		{
			Object.Destroy((Object)(object)val);
		}
	}

	internal static void ApplyRow(UIBuildingOverlayElementWorker row, BuildingCity building, int target)
	{
		RowBuilding.Invoke(row) = building;
		int num = Current(building);
		int num2 = Math.Sign(target - num);
		int num3 = Math.Abs(target - num);
		for (int i = 0; i < num3; i++)
		{
			row.ChangeAmount(num2);
			int num4 = Current(building);
			if (num2 * (target - num4) > 0 && num2 * (num4 - num) > 0)
			{
				num = num4;
				continue;
			}
			break;
		}
	}
}
internal sealed class Entry
{
	public string Key;

	public string Title;

	public int Amount;

	public bool Removed;

	public bool Specialist;
}
internal sealed class Layout
{
	public string Name;

	public List<Entry> Entries;
}
internal sealed class LayoutBook
{
	public Layout[] Slots = new Layout[2]
	{
		new Layout
		{
			Name = "Day Shift"
		},
		new Layout
		{
			Name = "Night Shift"
		}
	};

	internal void Remove(string key)
	{
		Layout[] slots = Slots;
		foreach (Layout layout in slots)
		{
			if (layout.Entries == null)
			{
				continue;
			}
			foreach (Entry item in layout.Entries.Where((Entry e) => e.Key == key))
			{
				item.Removed = true;
			}
		}
	}

	internal bool Valid()
	{
		Layout[] slots = Slots;
		if (slots != null && slots.Length == 2)
		{
			return Slots.All((Layout slot) => slot != null && !string.IsNullOrWhiteSpace(slot.Name) && slot.Name.Length <= 20 && (slot.Entries == null || (slot.Entries.All((Entry e) => e != null && !string.IsNullOrEmpty(e.Key) && !string.IsNullOrEmpty(e.Title) && e.Amount >= 0) && slot.Entries.Select((Entry e) => e.Key).Distinct().Count() == slot.Entries.Count)));
		}
		return false;
	}
}
internal sealed class Workplace
{
	public string Key;

	public string Title;

	public string BuildingName;

	public int Current;

	public int Min;

	public int Max;

	public int JobCapacity;

	public int CrewSize = 1;

	public bool Carrier;

	public bool Specialist;

	public bool Individual;

	internal static string Plot(string prefab, float x, float y)
	{
		return string.Format(CultureInfo.InvariantCulture, "{0}@{1:R},{2:R}", prefab, x, y);
	}

	internal Entry Capture()
	{
		return new Entry
		{
			Key = Key,
			Title = Title,
			Amount = Current,
			Specialist = Specialist
		};
	}

	internal string AmountText(int amount)
	{
		if (!Individual || amount != 9)
		{
			return amount.ToString();
		}
		return "∞";
	}
}
internal sealed class Change
{
	internal Entry Saved;

	internal Workplace Building;

	internal int Target;

	internal string Plot
	{
		get
		{
			int num = Saved.Key.LastIndexOf('@');
			if (num >= 0)
			{
				return Saved.Key.Substring(num + 1).Replace(",", ", ");
			}
			return "";
		}
	}

	internal string BuildingName
	{
		get
		{
			if (!string.IsNullOrEmpty(Building?.BuildingName))
			{
				return Building.BuildingName;
			}
			string title = Saved.Title;
			int num = title.LastIndexOf(" (", StringComparison.Ordinal);
			if (num <= 0 || !title.EndsWith(")"))
			{
				return title;
			}
			return title.Substring(0, num);
		}
	}

	internal bool Changes
	{
		get
		{
			if (Building != null)
			{
				return Building.Current != Target;
			}
			return false;
		}
	}
}
internal sealed class Preview
{
	internal readonly List<Change> Rows = new List<Change>();

	internal readonly int WorkersShort;

	internal readonly int CarriersShort;

	internal Preview(Layout layout, IReadOnlyDictionary<string, Workplace> buildings, int workers, int carriers, int otherWorkerJobs = 0, int otherCarrierJobs = 0)
	{
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		foreach (Entry entry in layout.Entries)
		{
			Change change = new Change
			{
				Saved = entry
			};
			if (!entry.Removed && buildings.TryGetValue(entry.Key, out var value) && value.Specialist == entry.Specialist)
			{
				change.Building = value;
				change.Target = Math.Max(value.Min, Math.Min(value.Max, entry.Amount));
				dictionary.Add(value.Key, change.Target);
			}
			Rows.Add(change);
		}
		foreach (Workplace value3 in buildings.Values)
		{
			int value2;
			int val = (dictionary.TryGetValue(value3.Key, out value2) ? value2 : value3.Current);
			int num = Math.Min(value3.JobCapacity, val);
			if (num > 0)
			{
				num = Math.Max(value3.CrewSize, num);
			}
			if (value3.Carrier)
			{
				otherCarrierJobs += num;
			}
			else
			{
				otherWorkerJobs += num;
			}
		}
		WorkersShort = Math.Max(0, otherWorkerJobs - workers);
		CarriersShort = Math.Max(0, otherCarrierJobs - carriers);
	}

	internal bool Matches(Preview other)
	{
		if (WorkersShort == other.WorkersShort && CarriersShort == other.CarriersShort && Rows.Count == other.Rows.Count)
		{
			return Rows.Zip(other.Rows, (Change a, Change b) => a.Saved.Key == b.Saved.Key && a.Target == b.Target && a.Building?.Current == b.Building?.Current).All((bool equal) => equal);
		}
		return false;
	}

	internal IEnumerable<Change> InApplyOrder()
	{
		return from row in Rows
			where row.Changes
			orderby row.Target > row.Building.Current
			select row;
	}
}
[BepInPlugin("gkj.sfk.workerpresets", "Worker Presets", "0.1.3")]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(GameInputManager), "CloseOverlay")]
	private static class BackInput
	{
		private static bool Prefix(CallbackContext context)
		{
			if (!((CallbackContext)(ref context)).performed || PauseMenuManger.Instance.InMenu())
			{
				return true;
			}
			OverlayManager instance = OverlayManager.Instance;
			if (!instance.IsOpen() || !instance.CanCloseOverlay())
			{
				return true;
			}
			PresetPanel componentInChildren = ((Component)instance.GetOverlaySelection()).GetComponentInChildren<PresetPanel>();
			if (!((Object)(object)componentInChildren == (Object)null))
			{
				return !componentInChildren.Back();
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UIBuildingOverlayElementWorker), "Draw", new Type[] { typeof(Building) })]
	private static class AssignmentPanel
	{
		private static void Postfix(Building building, Transform ___m_OverlayElement, bool __runOriginal)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (__runOriginal && Book != null)
			{
				BuildingCity val = (BuildingCity)(object)((building is BuildingCity) ? building : null);
				if (val != null)
				{
					Transform overlaySelection = OverlayManager.Instance.GetOverlaySelection();
					Button val2 = PresetPanel.AddLauncher(overlaySelection, (RectTransform)___m_OverlayElement, val);
					AssignmentPanelFit.Bind(overlaySelection, ((Component)val2).transform);
					GamepadManager.Instance.SetGameObjectToSelect(((Component)val2).gameObject, false);
				}
			}
		}
	}

	private Harmony patches;

	internal static LayoutBook Book { get; private set; }

	internal static void Reset(LayoutBook saved)
	{
		Book = saved ?? new LayoutBook();
	}

	internal static bool HasSavedLayouts(LayoutBook book)
	{
		if (!book.Slots.Any((Layout slot) => slot.Entries != null) && !(book.Slots[0].Name != "Day Shift"))
		{
			return book.Slots[1].Name != "Night Shift";
		}
		return true;
	}

	private void Awake()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		patches = new Harmony("gkj.sfk.workerpresets");
		patches.PatchAll(typeof(Plugin).Assembly);
		CityManager.OnBuildingRemoved += Removed;
	}

	private void OnDestroy()
	{
		CityManager.OnBuildingRemoved -= Removed;
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		Book = null;
	}

	private static void Removed(BuildingCity building, bool cancelJobs)
	{
		Book?.Remove(CityStaffing.Key(building));
	}
}
internal sealed class PresetPanel : MonoBehaviour
{
	private const int MaxPreviewRows = 3;

	private BuildingCity source;

	private LayoutBook book;

	private int index;

	private TextMeshProUGUI hints;

	private Action backAction;

	private static readonly string[] Names = new string[6] { "Day Shift", "Night Shift", "Harvest", "Construction", "Supplies", "Recovery" };

	private Layout Slot => book.Slots[index];

	private float Scale => ((Component)this).GetComponentInParent<Canvas>().rootCanvas.scaleFactor;

	internal static int PreviewRows(float logicalHeight)
	{
		if (!(logicalHeight < 420f))
		{
			if (!(logicalHeight < 580f))
			{
				return 3;
			}
			return 2;
		}
		return 1;
	}

	internal static float PanelWidth(float logicalWidth)
	{
		float val = Math.Max(448f, Math.Min(520f, logicalWidth * 0.35f));
		return Math.Max(1f, Math.Min(val, logicalWidth - 48f));
	}

	internal static Button Button(Transform parent, string title, Action action)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Expected O, but got Unknown
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Expected O, but got Unknown
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		Button obj = Object.Instantiate<Button>(((Component)Resources.Load<GameObject>("UI/OverlayElementButton").transform.Find("Button")).GetComponent<Button>(), parent, false);
		((Object)obj).name = title;
		TextMeshProUGUI componentInChildren = ((Component)obj).GetComponentInChildren<TextMeshProUGUI>(true);
		((TMP_Text)componentInChildren).text = title;
		((TMP_Text)componentInChildren).rectTransform.anchorMin = Vector2.zero;
		((TMP_Text)componentInChildren).rectTransform.anchorMax = Vector2.one;
		((TMP_Text)componentInChildren).rectTransform.offsetMin = new Vector2(8f, 1f);
		((TMP_Text)componentInChildren).rectTransform.offsetMax = new Vector2(-8f, -1f);
		((TMP_Text)componentInChildren).enableAutoSizing = true;
		((TMP_Text)componentInChildren).fontSizeMin = 15f;
		((TMP_Text)componentInChildren).fontSizeMax = 28f;
		LayoutElement obj2 = ((Component)obj).gameObject.AddComponent<LayoutElement>();
		float minHeight = (obj2.preferredHeight = 42f);
		obj2.minHeight = minHeight;
		obj2.flexibleWidth = 1f;
		obj.onClick = new ButtonClickedEvent();
		((UnityEvent)obj.onClick).AddListener((UnityAction)delegate
		{
			action();
		});
		Navigation navigation = ((Selectable)obj).navigation;
		((Navigation)(ref navigation)).mode = (Mode)3;
		((Selectable)obj).navigation = navigation;
		((Component)obj).gameObject.SetActive(true);
		return obj;
	}

	internal static Button AddLauncher(Transform panel, RectTransform workerRow, BuildingCity source)
	{
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		Button val = Button(panel, "Worker Presets", delegate
		{
			Open(source);
		});
		Transform obj = ((Transform)workerRow).Find("Jobs");
		TextMeshProUGUI val2 = ((obj != null) ? ((Component)obj).GetComponent<TextMeshProUGUI>() : null);
		if ((Object)(object)val2 != (Object)null)
		{
			float num = ((TMP_Text)val2).preferredWidth + 32f;
			Rect rect = workerRow.rect;
			if (num <= ((Rect)(ref rect)).width - 106f - 100f)
			{
				RectTransform val3 = (RectTransform)((Component)val).transform;
				((Transform)val3).SetParent((Transform)(object)workerRow, false);
				Vector2 val4 = default(Vector2);
				((Vector2)(ref val4))..ctor(1f, 0.5f);
				val3.pivot = val4;
				Vector2 anchorMin = (val3.anchorMax = val4);
				val3.anchorMin = anchorMin;
				val3.anchoredPosition = new Vector2(-106f, 0f);
				val3.sizeDelta = new Vector2(100f, 38f);
				((Component)val).GetComponent<LayoutElement>().ignoreLayout = true;
				((TMP_Text)((Component)val).GetComponentInChildren<TextMeshProUGUI>()).text = "Presets";
			}
		}
		return val;
	}

	internal static void Open(BuildingCity source)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		OverlayManager instance = OverlayManager.Instance;
		if (!((Object)(object)source == (Object)null) && Plugin.Book != null && instance.IsOpen())
		{
			instance.CloseOverlay(false);
			instance.OverlayVariable((BuildingWorld)null, new List<UIBuildingOverlayElement>(), "Worker Presets");
			GameObject val = new GameObject("Worker Presets", new Type[2]
			{
				typeof(RectTransform),
				typeof(VerticalLayoutGroup)
			});
			val.transform.SetParent(instance.GetOverlaySelection(), false);
			VerticalLayoutGroup component = val.GetComponent<VerticalLayoutGroup>();
			bool flag = (((HorizontalOrVerticalLayoutGroup)component).childControlHeight = true);
			bool childControlWidth = (((HorizontalOrVerticalLayoutGroup)component).childForceExpandWidth = flag);
			((HorizontalOrVerticalLayoutGroup)component).childControlWidth = childControlWidth;
			((HorizontalOrVerticalLayoutGroup)component).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)component).spacing = 4f;
			PresetPanel presetPanel = val.AddComponent<PresetPanel>();
			presetPanel.source = source;
			presetPanel.book = Plugin.Book;
		}
	}

	private void Start()
	{
		Slots();
	}

	private void Clear(string header, Action back)
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		((UIOverlayBase)((Component)this).GetComponentInParent<UIOverlayVariable>()).SetHeaderText(header);
		LayoutElement obj = ((Component)this).GetComponent<LayoutElement>() ?? ((Component)this).gameObject.AddComponent<LayoutElement>();
		float minWidth = (obj.preferredWidth = PanelWidth((float)Screen.width / Scale));
		obj.minWidth = minWidth;
		backAction = back;
		hints = null;
		foreach (Transform item in ((Component)this).transform)
		{
			((Component)item).gameObject.SetActive(false);
			Object.Destroy((Object)(object)((Component)item).gameObject);
		}
	}

	private TextMeshProUGUI Text(string value)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		TextMeshProUGUI obj = Object.Instantiate<TextMeshProUGUI>(Resources.Load<GameObject>("UI/OverlayElementText").GetComponentInChildren<TextMeshProUGUI>(true), ((Component)this).transform, false);
		((TMP_Text)obj).transform.localScale = Vector3.one;
		((TMP_Text)obj).margin = new Vector4(4f, 0f, 4f, 0f);
		((TMP_Text)obj).text = value;
		((TMP_Text)obj).alignment = (TextAlignmentOptions)514;
		((TMP_Text)obj).fontSize = 28f;
		((TMP_Text)obj).enableAutoSizing = false;
		((TMP_Text)obj).enableWordWrapping = true;
		((Graphic)obj).raycastTarget = false;
		return obj;
	}

	private Button ActionButton(string title, Action action)
	{
		return Button(((Component)this).transform, title, delegate
		{
			if (book == Plugin.Book && ((Behaviour)this).isActiveAndEnabled)
			{
				action();
			}
		});
	}

	private void Focus(Button first)
	{
		hints = Text("");
		Prompts();
		Canvas.ForceUpdateCanvases();
		GamepadManager.Instance.SetGameObjectToSelect(((Component)first).gameObject, true);
		EventSystem current = EventSystem.current;
		if (current != null)
		{
			current.SetSelectedGameObject(((Component)first).gameObject);
		}
	}

	private void OnEnable()
	{
		GamepadManager.OnControlSchemeChanged += SchemeChanged;
	}

	private void OnDisable()
	{
		GamepadManager.OnControlSchemeChanged -= SchemeChanged;
	}

	private void SchemeChanged(string current, string previous)
	{
		Prompts();
	}

	private void Prompts()
	{
		if (!((Object)(object)hints == (Object)null))
		{
			((TMP_Text)hints).text = Icon("UI/Submit", "Select") + "     " + Icon("UI/Cancel", "Back");
		}
		static string Icon(string action, string caption)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			string text = "$" + action + "$";
			string text2 = Helper.Instance.ReplaceStringWithInputIcon(text);
			if (text2 != text)
			{
				return text2 + " " + caption;
			}
			GamepadManager instance = GamepadManager.Instance;
			PlayerInput playerInput = instance.GetPlayerInput();
			InputAction val = ((playerInput != null) ? playerInput.actions.FindAction(action, false) : null);
			if (val != null)
			{
				Enumerator<InputControl> enumerator = val.controls.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						InputControl current = enumerator.Current;
						string text3 = ((current.device is Gamepad) ? "Gamepad" : ((current.device is Keyboard) ? "Keyboard" : null));
						if (text3 != null && text3 == "Gamepad" == instance.IsGamepadInUse())
						{
							Sprite buttonPrompt = instance.GetButtonPrompt("<" + text3 + ">/" + current.name, false);
							if ((Object)(object)buttonPrompt != (Object)null)
							{
								return "<sprite name=" + ((Object)buttonPrompt).name + "> " + caption;
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
			}
			return caption;
		}
	}

	private void Slots(string message = null)
	{
		Clear("Worker Presets", Jobs);
		if (message != null)
		{
			Text(message);
		}
		Button first = null;
		for (int i = 0; i < 2; i++)
		{
			int slot = i;
			Layout layout = book.Slots[slot];
			Button val = ActionButton(layout.Name + ((layout.Entries == null) ? "  (Empty)" : ("  |  " + Count(layout.Entries.Count, "building"))), delegate
			{
				index = slot;
				Manage();
			});
			if (slot == index)
			{
				first = val;
			}
		}
		ActionButton("Back to jobs", Jobs);
		Focus(first);
	}

	internal bool Back()
	{
		if (backAction == null || book != Plugin.Book || !((Behaviour)this).isActiveAndEnabled)
		{
			return false;
		}
		backAction();
		return true;
	}

	private void Jobs()
	{
		UIBuildingOverlay val = (((Object)(object)source != (Object)null) ? ((Component)source).GetComponent<UIBuildingOverlay>() : null);
		if ((Object)(object)val == (Object)null)
		{
			OverlayManager.Instance.Cancel(true);
			return;
		}
		val.Open(true, "");
		Button val2 = ((IEnumerable<Button>)((Component)OverlayManager.Instance.GetOverlaySelection()).GetComponentsInChildren<Button>()).FirstOrDefault((Func<Button, bool>)((Button b) => ((Object)b).name == "Worker Presets"));
		if ((Object)(object)val2 != (Object)null)
		{
			GamepadManager.Instance.SetGameObjectToSelect(((Component)val2).gameObject, true);
		}
	}

	private void Manage(string message = null)
	{
		Clear(Slot.Name, delegate
		{
			Slots();
		});
		if (message != null)
		{
			Text(message);
		}
		Button val = null;
		if (Slot.Entries != null)
		{
			val = ActionButton("Preview layout", delegate
			{
				ShowPreview(new CityStaffing().Plan(Slot), 0);
			});
		}
		Button val2 = ActionButton("Save current staffing", delegate
		{
			if (Slot.Entries == null)
			{
				Save();
			}
			else
			{
				Clear(Slot.Name, delegate
				{
					Manage();
				});
				Text("Replace this layout with the current staffing?");
				Button first = ActionButton("Keep saved layout", delegate
				{
					Manage();
				});
				ActionButton("Replace layout", Save);
				Focus(first);
			}
		});
		ActionButton("Rename", Rename);
		ActionButton("Back", delegate
		{
			Slots();
		});
		Focus(val ?? val2);
	}

	private void Save()
	{
		List<Entry> list = new CityStaffing().Capture();
		if (list.Count == 0)
		{
			Manage("No staffing controls are available.");
			return;
		}
		Slot.Entries = list;
		Slots(Slot.Name + " saved, " + list.Count + " buildings");
	}

	private void Rename()
	{
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Expected O, but got Unknown
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Expected O, but got Unknown
		Clear("Rename layout", delegate
		{
			Manage();
		});
		UIRename componentInChildren = ((Component)OverlayManager.Instance).GetComponentInChildren<UIRename>(true);
		TMP_InputField val = ((componentInChildren != null) ? ((Component)componentInChildren).GetComponentInChildren<TMP_InputField>(true) : null);
		TMP_InputField field = null;
		if ((Object)(object)val != (Object)null)
		{
			field = Object.Instantiate<TMP_InputField>(val, ((Component)this).transform);
			field.onValueChanged = new OnChangeEvent();
			field.onEndEdit = new SubmitEvent();
			field.onSubmit = new SubmitEvent();
			field.characterLimit = 20;
			field.lineType = (LineType)0;
			field.SetTextWithoutNotify(Slot.Name);
			LayoutElement obj = ((Component)field).GetComponent<LayoutElement>() ?? ((Component)field).gameObject.AddComponent<LayoutElement>();
			float minHeight = (obj.preferredHeight = 46f);
			obj.minHeight = minHeight;
			((Component)field).gameObject.SetActive(true);
		}
		string draft = Slot.Name;
		Button cycle = ActionButton("Choose name", delegate
		{
		});
		((UnityEventBase)cycle.onClick).RemoveAllListeners();
		((UnityEvent)cycle.onClick).AddListener((UnityAction)delegate
		{
			draft = Names[(Array.IndexOf(Names, draft) + 1) % Names.Length];
			if ((Object)(object)field != (Object)null)
			{
				field.SetTextWithoutNotify(draft);
			}
			else
			{
				((TMP_Text)((Component)cycle).GetComponentInChildren<TextMeshProUGUI>()).text = draft;
			}
		});
		ActionButton("Save name", delegate
		{
			string text = (((Object)(object)field != (Object)null) ? field.text : draft);
			text = new string(text.Where((char c) => !char.IsControl(c) && c != '<' && c != '>').Take(20).ToArray()).Trim();
			if (text.Length == 0 || string.Equals(text, book.Slots[1 - index].Name, StringComparison.OrdinalIgnoreCase))
			{
				Manage("Choose a distinct, non-empty name.");
			}
			else
			{
				Slot.Name = text;
				Manage();
			}
		});
		ActionButton("Back", delegate
		{
			Manage();
		});
		Focus(cycle);
	}

	private void ShowPreview(Preview plan, int page, string message = null, int pageDirection = 0)
	{
		//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
		Clear(Slot.Name + " - Preview", delegate
		{
			Manage();
		});
		int num = plan.Rows.Count((Change row) => row.Changes);
		int num2 = plan.Rows.Count((Change row) => row.Building == null);
		if (message != null)
		{
			Text(message);
		}
		string text = ((num == 0) ? "No assignments to change" : (Count(num, "building") + " will change"));
		if (num2 > 0)
		{
			text = text + "  |  " + num2 + " skipped";
		}
		Text(text);
		List<string> list = new List<string>();
		if (plan.WorkersShort > 0)
		{
			list.Add(Count(plan.WorkersShort, "worker"));
		}
		if (plan.CarriersShort > 0)
		{
			list.Add(Count(plan.CarriersShort, "carrier"));
		}
		if (list.Count > 0)
		{
			Text("<color=#FFE295><sprite name=IconWorking> Short " + string.Join(" and ", list) + "</color>");
		}
		Change[] array = plan.Rows.OrderByDescending((Change row) => row.Changes || row.Building == null).ToArray();
		HashSet<string> hashSet = (from r in array
			group r by r.BuildingName into @group
			where @group.Count() > 1
			select @group.Key).ToHashSet();
		int num3 = PreviewRows((float)Screen.height / Scale);
		int num4 = Math.Max(1, (array.Length + num3 - 1) / num3);
		page = Math.Max(0, Math.Min(page, num4 - 1));
		TableRow("Building", "Now", "After", null, header: true);
		foreach (Change item in array.Skip(page * num3).Take(num3))
		{
			string text2 = (hashSet.Contains(item.BuildingName) ? ("Plot " + item.Plot) : "");
			if (item.Building == null)
			{
				text2 = JoinDetail(text2, "Skipped");
			}
			else if (item.Target != item.Saved.Amount)
			{
				text2 = JoinDetail(text2, "Limited");
			}
			TableRow(item.BuildingName, item.Building?.AmountText(item.Building.Current) ?? "-", item.Building?.AmountText(item.Target) ?? "-", text2, header: false, item.Changes);
		}
		Button val = null;
		if (num4 > 1)
		{
			GameObject val2 = new GameObject("Pages", new Type[2]
			{
				typeof(RectTransform),
				typeof(HorizontalLayoutGroup)
			});
			val2.transform.SetParent(((Component)this).transform, false);
			((HorizontalOrVerticalLayoutGroup)val2.GetComponent<HorizontalLayoutGroup>()).spacing = 6f;
			Button val3 = Button(val2.transform, "Previous", delegate
			{
				ShowPreview(plan, page - 1, null, -1);
			});
			Button val4 = Button(val2.transform, $"{page + 1}/{num4}  Next", delegate
			{
				ShowPreview(plan, page + 1, null, 1);
			});
			((Selectable)val3).interactable = page > 0;
			((Selectable)val4).interactable = page + 1 < num4;
			if (pageDirection != 0)
			{
				val = ((((Selectable)val4).interactable && (pageDirection > 0 || !((Selectable)val3).interactable)) ? val4 : val3);
			}
		}
		Button val5 = ActionButton("Back", delegate
		{
			Manage();
		});
		if (num > 0)
		{
			ActionButton("Apply " + Count(num, "change"), delegate
			{
				Confirm(plan);
			});
		}
		Focus(val ?? val5);
	}

	private static string Count(int n, string noun)
	{
		return n + " " + noun + ((n == 1) ? "" : "s");
	}

	private static string JoinDetail(string a, string b)
	{
		if (a.Length != 0)
		{
			return a + "  |  " + b;
		}
		return b;
	}

	private void TableRow(string title, string current, string target, string detail, bool header, bool changes = false)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		GameObject row = new GameObject("Staffing row", new Type[3]
		{
			typeof(RectTransform),
			typeof(LayoutElement),
			typeof(Image)
		});
		row.transform.SetParent(((Component)this).transform, false);
		LayoutElement component = row.GetComponent<LayoutElement>();
		float preferredHeight = (component.minHeight = (header ? 30 : (string.IsNullOrEmpty(detail) ? 34 : 54)));
		component.preferredHeight = preferredHeight;
		Image component2 = row.GetComponent<Image>();
		((Graphic)component2).raycastTarget = false;
		((Graphic)component2).color = Color32.op_Implicit(header ? new Color32((byte)62, (byte)35, (byte)68, byte.MaxValue) : new Color32((byte)91, (byte)54, (byte)99, byte.MaxValue));
		TextMeshProUGUI template = Resources.Load<GameObject>("UI/OverlayElementText").GetComponentInChildren<TextMeshProUGUI>(true);
		if (!string.IsNullOrEmpty(detail))
		{
			title = title + "\n<size=84%><color=#E7D4E9>" + detail + "</color></size>";
		}
		Cell(title, 0f, 0.62f, (TextAlignmentOptions)4097);
		Cell(current, 0.62f, 0.81f, (TextAlignmentOptions)514);
		Cell(target, 0.81f, 1f, (TextAlignmentOptions)514, changes);
		void Cell(string value, float left, float right, TextAlignmentOptions alignment, bool accent = false)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI obj = Object.Instantiate<TextMeshProUGUI>(template, row.transform, false);
			((TMP_Text)obj).transform.localScale = Vector3.one;
			RectTransform rectTransform = ((TMP_Text)obj).rectTransform;
			rectTransform.anchorMin = new Vector2(left, 0f);
			rectTransform.anchorMax = new Vector2(right, 1f);
			rectTransform.offsetMin = new Vector2(8f, 0f);
			rectTransform.offsetMax = new Vector2(-8f, 0f);
			((TMP_Text)obj).margin = Vector4.zero;
			((TMP_Text)obj).text = value;
			((TMP_Text)obj).alignment = alignment;
			((TMP_Text)obj).enableAutoSizing = true;
			((TMP_Text)obj).fontSizeMax = (header ? 26 : 30);
			((TMP_Text)obj).fontSizeMin = 15f;
			((TMP_Text)obj).enableWordWrapping = true;
			((Graphic)obj).color = Color32.op_Implicit((header || accent) ? new Color32(byte.MaxValue, (byte)226, (byte)149, byte.MaxValue) : new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue));
			((Graphic)obj).raycastTarget = false;
		}
	}

	private void Confirm(Preview seen)
	{
		CityStaffing cityStaffing = new CityStaffing();
		Preview preview = cityStaffing.Plan(Slot);
		if (!seen.Matches(preview))
		{
			ShowPreview(preview, 0, "Staffing changed. Review again.");
			return;
		}
		try
		{
			cityStaffing.Apply(preview);
		}
		catch (Exception ex)
		{
			Debug.LogWarning((object)("Worker Presets stopped applying: " + ex));
			ShowPreview(new CityStaffing().Plan(Slot), 0, "Apply stopped. Review remaining changes.");
			return;
		}
		Preview preview2 = new CityStaffing().Plan(Slot);
		if (preview2.Rows.Any((Change r) => r.Changes))
		{
			ShowPreview(preview2, 0, "Some assignments are still limited.");
			return;
		}
		Manage("Layout applied, " + preview.Rows.Count((Change r) => r.Changes) + " changed");
	}
}
internal static class SaveHooks
{
	[Serializable]
	private sealed class Envelope
	{
		public string runID;

		public string hash;

		public LayoutBook workerPresetsV1;
	}

	private sealed class ReadContext
	{
		internal string Path;

		internal Envelope Selected;
	}

	[HarmonyPatch]
	private static class ReadScope
	{
		private static MethodBase[] TargetMethods()
		{
			return new MethodInfo[2]
			{
				AccessTools.Method(typeof(GameDataManager), "PositionWorldBuildings", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(TavernSaveManager), "Load", (Type[])null, (Type[])null)
			};
		}

		private static void Prefix(object __instance, out ReadContext __state)
		{
			__state = reading;
			reading = new ReadContext
			{
				Path = (string)AccessTools.Method(__instance.GetType(), "GetPath", (Type[])null, (Type[])null).Invoke(__instance, null)
			};
		}

		private static void Postfix(GameData ___m_GameData)
		{
			Attach(___m_GameData);
		}

		private static void Finalizer(ReadContext __state)
		{
			reading = __state;
		}
	}

	[HarmonyPatch(typeof(SaveManager), "LoadGameData")]
	private static class TavernCheckpoint
	{
		private static void Postfix(GameData __result)
		{
			Attach(__result);
		}
	}

	[HarmonyPatch]
	private static class ReadJson
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.FirstMethod(typeof(SaveManager), (Func<MethodInfo, bool>)((MethodInfo m) => m.Name == "Load" && !m.IsGenericMethod && m.ReturnType == typeof(string)));
		}

		private static void Postfix(string __0, string __result)
		{
			if (reading == null || __0 != reading.Path)
			{
				return;
			}
			reading.Selected = null;
			if (string.IsNullOrEmpty(__result) || !__result.Contains("\"workerPresetsV1\""))
			{
				return;
			}
			try
			{
				reading.Selected = JsonConvert.DeserializeObject<Envelope>(__result);
			}
			catch (JsonException)
			{
			}
		}
	}

	[HarmonyPatch(typeof(GameDataManager), "Load")]
	private static class Restore
	{
		private static void Prefix(GameData ___m_GameData)
		{
			Plugin.Reset((___m_GameData != null && Checkpoints.TryGetValue(___m_GameData, out var value)) ? value : null);
		}
	}

	[HarmonyPatch]
	private static class WriteScope
	{
		private static MethodBase[] TargetMethods()
		{
			return new MethodInfo[2]
			{
				AccessTools.Method(typeof(GameDataManager), "Save", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(TavernSaveManager), "Save", (Type[])null, (Type[])null)
			};
		}

		private static void Prefix(object __instance, out (LayoutBook, string) __state)
		{
			__state = (writing, writePath);
			writePath = (string)AccessTools.Method(__instance.GetType(), "GetPath", (Type[])null, (Type[])null).Invoke(__instance, null);
			TavernSaveManager val = (TavernSaveManager)((__instance is TavernSaveManager) ? __instance : null);
			if (val != null)
			{
				GameData gameData = val.GetGameData();
				writing = ((gameData != null && Checkpoints.TryGetValue(gameData, out var value)) ? value : null);
			}
			else
			{
				writing = Plugin.Book;
			}
		}

		private static void Finalizer((LayoutBook, string) __state)
		{
			(writing, writePath) = __state;
		}
	}

	[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	private static class WriteJson
	{
		private static void Prefix(string __0, ref string __1)
		{
			if (writing != null && !(__0 != writePath) && Plugin.HasSavedLayouts(writing))
			{
				int num = __1.LastIndexOf('}');
				if (num >= 0)
				{
					__1 = __1.Insert(num, ",\"workerPresetsV1\":" + JsonConvert.SerializeObject((object)writing));
				}
			}
		}
	}

	private const string Key = "workerPresetsV1";

	private static readonly ConditionalWeakTable<GameData, LayoutBook> Checkpoints = new ConditionalWeakTable<GameData, LayoutBook>();

	private static ReadContext reading;

	private static LayoutBook writing;

	private static string writePath;

	private static void Attach(GameData data)
	{
		Envelope envelope = reading?.Selected;
		if (envelope != null && envelope.workerPresetsV1?.Valid() == true && data != null && !(data.runID != envelope.runID) && !(data.hash != envelope.hash))
		{
			Checkpoints.Remove(data);
			Checkpoints.Add(data, envelope.workerPresetsV1);
		}
	}
}