Decompiled source of Daybook v0.4.1

plugins/Daybook.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.UI;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Daybook")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.1.0")]
[assembly: AssemblyInformationalVersion("0.4.1+4c78a29fc9cb673c89e9aebd3d643cf80ca459af")]
[assembly: AssemblyProduct("Daybook")]
[assembly: AssemblyTitle("Daybook")]
[assembly: AssemblyVersion("0.4.1.0")]
namespace Daybook;

internal static class ControllerLedger
{
	[HarmonyPatch(typeof(GameInputManager), "PauseToggle")]
	internal static class OlderAction
	{
		private static bool Prefix(CallbackContext __0)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (!Captures(__0))
			{
				return true;
			}
			Plugin.PageHistory(1);
			return false;
		}
	}

	[HarmonyPatch(typeof(GameInputManager), "TimeButton")]
	internal static class NewerAction
	{
		private static bool Prefix(CallbackContext __0)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (!Captures(__0))
			{
				return true;
			}
			Plugin.PageHistory(-1);
			return false;
		}
	}

	[HarmonyPatch(typeof(UIButtonPrompt), "OnActionPerformed")]
	internal static class HudAction
	{
		private static bool Prefix(CallbackContext __0)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			InputAction action = ((CallbackContext)(ref __0)).action;
			InputActionMap actionMap = action.actionMap;
			if (((actionMap != null) ? actionMap.name : null) == "Game" && (action.name == "PauseToggle" || action.name == "ChangeGameSpeed"))
			{
				return !Captures(__0);
			}
			return true;
		}
	}

	internal const string Details = "Game/WorkerMenu";

	internal const string Older = "Game/PauseToggle";

	internal const string Newer = "Game/ChangeGameSpeed";

	internal static DaybookPlugin Plugin;

	internal static PlayerInput ActivePlayer()
	{
		GamepadManager instance = GamepadManager.Instance;
		if ((Object)(object)instance == (Object)null || !instance.IsGamepadInUse())
		{
			return null;
		}
		return instance.GetPlayerInput();
	}

	internal static Sprite Glyph(PlayerInput player, string actionPath, out string bindingName)
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: 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_008c: 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_0096: Unknown result type (might be due to invalid IL or missing references)
		InputAction val = player.actions.FindAction(actionPath, false);
		bindingName = "";
		if (val == null || !val.enabled)
		{
			return null;
		}
		int num = -1;
		Enumerator<InputControl> enumerator = val.controls.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				InputControl current = enumerator.Current;
				if (current.device is Gamepad)
				{
					num = InputActionRebindingExtensions.GetBindingIndexForControl(val, current);
					if (num >= 0)
					{
						break;
					}
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		if (num < 0)
		{
			return null;
		}
		bindingName = InputActionRebindingExtensions.GetBindingDisplayString(val, num, (DisplayStringOptions)0);
		InputBinding val2 = val.bindings[num];
		string text = ((InputBinding)(ref val2)).effectivePath;
		if (!string.IsNullOrEmpty(((InputBinding)(ref val2)).effectiveProcessors))
		{
			text += "Processor";
		}
		return GamepadManager.Instance.GetButtonPrompt(text, false);
	}

	private static bool Captures(CallbackContext context)
	{
		if (((CallbackContext)(ref context)).performed)
		{
			InputControl control = ((CallbackContext)(ref context)).control;
			if (((control != null) ? control.device : null) is Gamepad && (Object)(object)Plugin != (Object)null)
			{
				return Plugin.CanPageWithController();
			}
		}
		return false;
	}
}
public sealed class DaybookPanel : MonoBehaviour
{
	private sealed class Row
	{
		internal LedgerEntry Entry;

		internal Text Title;

		internal Text Compact;

		internal Text Dawn;

		internal Text Earned;

		internal Text Spent;

		internal Text Now;

		internal Text Net;

		internal int? LastDawn;

		internal int? LastNow;

		internal long LastEarned;

		internal long LastSpent;

		internal bool Painted;

		internal bool ShowGross;

		internal bool Partial;
	}

	private sealed class ButtonHint
	{
		internal RectTransform Root;

		internal Image Icon;

		internal Text Label;

		internal string Action;

		internal string Verb;
	}

	private static readonly Color32 Ink = new Color32((byte)48, (byte)35, (byte)24, byte.MaxValue);

	private static readonly Color32 Gold = new Color32(byte.MaxValue, (byte)224, (byte)158, byte.MaxValue);

	private static readonly Color32 Gain = new Color32((byte)162, (byte)243, (byte)137, byte.MaxValue);

	private static readonly Color32 Loss = new Color32(byte.MaxValue, (byte)169, (byte)151, byte.MaxValue);

	private readonly List<Row> rows = new List<Row>();

	private RectTransform frame;

	private RectTransform strip;

	private RectTransform book;

	private RectTransform viewport;

	private Text fontSource;

	private Text historyCaption;

	private Text coverageNote;

	private float bookHeight;

	private int revision = -1;

	private DayRecord selected;

	private bool detailed;

	private bool historyHintsVisible;

	private bool noteVisible;

	private readonly LedgerTooltipLayout tooltipLayout = new LedgerTooltipLayout();

	private CanvasGroup visibility;

	private ButtonHint older;

	private ButtonHint newer;

	private void OnEnable()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		Canvas.willRenderCanvases += new WillRenderCanvases(PlaceTooltip);
	}

	private void OnDisable()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		Canvas.willRenderCanvases -= new WillRenderCanvases(PlaceTooltip);
		tooltipLayout.Restore();
	}

	private void PlaceTooltip()
	{
		if (!((Object)(object)frame == (Object)null) && !((Object)(object)viewport == (Object)null) && !((Object)(object)visibility == (Object)null))
		{
			OverlayManager instance = OverlayManager.Instance;
			bool flag = false;
			if ((Object)(object)instance != (Object)null && instance.IsOpen())
			{
				Transform overlaySelection = instance.GetOverlaySelection();
				Transform obj = ((overlaySelection != null) ? overlaySelection.parent : null);
				RectTransform obstacle = (RectTransform)(object)((obj is RectTransform) ? obj : null);
				Transform overlayTabsSelection = instance.GetOverlayTabsSelection();
				RectTransform obstacle2 = (RectTransform)(object)((overlayTabsSelection is RectTransform) ? overlayTabsSelection : null);
				flag = tooltipLayout.OverlapsVisible(frame, obstacle, viewport) || tooltipLayout.OverlapsVisible(frame, obstacle2, viewport);
			}
			float num = ((!flag) ? 1 : 0);
			if (visibility.alpha != num)
			{
				visibility.alpha = num;
			}
			tooltipLayout.Place((detailed && !flag) ? frame : null, viewport);
		}
	}

	internal static DaybookPanel Attach(UIHeader header, ResourceLedger ledger)
	{
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Expected O, but got Unknown
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Expected O, but got Unknown
		Transform val = ((Component)header).transform.Find("PanelResources");
		object obj;
		if (val == null)
		{
			obj = null;
		}
		else
		{
			Transform obj2 = val.Find("Wood/Amount");
			obj = ((obj2 != null) ? ((Component)obj2).GetComponent<Text>() : null);
		}
		Text val2 = (Text)obj;
		if ((Object)(object)val2 == (Object)null && (Object)(object)val != (Object)null)
		{
			val2 = ((Component)val).GetComponentInChildren<Text>(true);
		}
		Image val3 = ((val != null) ? ((Component)val).GetComponent<Image>() : null);
		if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
		{
			return null;
		}
		GameObject val4 = new GameObject("Daybook", new Type[2]
		{
			typeof(RectTransform),
			typeof(LayoutElement)
		});
		val4.GetComponent<LayoutElement>().ignoreLayout = true;
		DaybookPanel daybookPanel = val4.AddComponent<DaybookPanel>();
		daybookPanel.visibility = val4.AddComponent<CanvasGroup>();
		daybookPanel.visibility.blocksRaycasts = false;
		daybookPanel.visibility.interactable = false;
		daybookPanel.fontSource = val2;
		daybookPanel.frame = (RectTransform)val4.transform;
		((Transform)daybookPanel.frame).SetParent(val, false);
		daybookPanel.frame.anchorMin = Vector2.zero;
		daybookPanel.frame.anchorMax = Vector2.right;
		daybookPanel.frame.pivot = new Vector2(0.5f, 1f);
		daybookPanel.frame.anchoredPosition = new Vector2(0f, -4f);
		Canvas componentInParent = ((Component)header).GetComponentInParent<Canvas>();
		if ((Object)(object)componentInParent != (Object)null)
		{
			daybookPanel.viewport = (RectTransform)((Component)componentInParent.rootCanvas).transform;
		}
		Image obj3 = val4.AddComponent<Image>();
		((Graphic)obj3).raycastTarget = false;
		obj3.sprite = val3.sprite;
		obj3.type = val3.type;
		obj3.pixelsPerUnitMultiplier = val3.pixelsPerUnitMultiplier;
		((Graphic)obj3).color = ((Graphic)val3).color;
		daybookPanel.strip = daybookPanel.Inset("Daily changes");
		daybookPanel.book = daybookPanel.Inset("Daily ledger");
		daybookPanel.SelectRows(ledger, null);
		daybookPanel.SetView(expanded: false, showHistoryHints: false);
		return daybookPanel;
	}

	private RectTransform Inset(string name)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		Image obj = GraphicChild<Image>(frame, name);
		((Graphic)obj).color = Color32.op_Implicit(Ink);
		RectTransform rectTransform = ((Graphic)obj).rectTransform;
		rectTransform.anchorMin = Vector2.zero;
		rectTransform.anchorMax = Vector2.one;
		rectTransform.offsetMin = new Vector2(5f, 5f);
		rectTransform.offsetMax = new Vector2(-5f, -5f);
		return rectTransform;
	}

	internal bool SelectRows(ResourceLedger ledger, DayRecord history)
	{
		//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 (selected == history && revision == ledger.Revision)
		{
			return false;
		}
		selected = history;
		revision = ledger.Revision;
		RectTransform[] array = (RectTransform[])(object)new RectTransform[2] { strip, book };
		for (int i = 0; i < array.Length; i++)
		{
			foreach (Transform item in (Transform)array[i])
			{
				((Component)item).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
		}
		rows.Clear();
		BuildRows((history == null) ? ledger.Entries : ledger.HistoryRows(history), (history == null) ? ledger.HeaderCount : 0);
		SetView(detailed, historyHintsVisible);
		return true;
	}

	private void BuildRows(List<LedgerEntry> entries, int headerCount)
	{
		//IL_0352: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		ColumnTitle("Dawn", 0.33f, 0.46f);
		ColumnTitle("Earned", 0.46f, 0.62f);
		ColumnTitle("Spent", 0.62f, 0.76f);
		ColumnTitle("Now", 0.76f, 0.88f);
		ColumnTitle("Net", 0.88f, 1f);
		float num = 0f;
		string text = null;
		for (int i = 0; i < entries.Count; i++)
		{
			LedgerEntry ledgerEntry = entries[i];
			if (ledgerEntry.Group != text)
			{
				text = ledgerEntry.Group;
				Text obj = Label(book, text switch
				{
					"Food and supplies" => "Food and Supplies", 
					"Other stock" => "Other Stock", 
					"Archived stock" => "Archived Stock", 
					_ => text, 
				}, 24, (TextAnchor)3);
				Place(((Graphic)obj).rectTransform, 0f, 0.33f, num, 26f, 5f, 2f);
				((Graphic)obj).color = Color32.op_Implicit(Gold);
				num += 26f;
			}
			Row row = new Row
			{
				Entry = ledgerEntry
			};
			if (i < headerCount)
			{
				float left = (float)i / (float)headerCount;
				float right = (float)(i + 1) / (float)headerCount;
				row.Compact = Label(strip, "Net " + ((object)ledgerEntry.Type/*cast due to .constrained prefix*/).ToString(), 26, (TextAnchor)4);
				Place(((Graphic)row.Compact).rectTransform, left, right, 0f, 26f);
			}
			Image val = GraphicChild<Image>(book, ((object)ledgerEntry.Type/*cast due to .constrained prefix*/).ToString() + " icon");
			val.sprite = ledgerEntry.Icon;
			((Behaviour)val).enabled = (Object)(object)val.sprite != (Object)null;
			val.preserveAspect = true;
			Place(((Graphic)val).rectTransform, 0f, 0f, num, 24f, 3f, -27f);
			row.Title = Label(book, ledgerEntry.Label, 23, (TextAnchor)3);
			Place(((Graphic)row.Title).rectTransform, 0f, 0.33f, num, 24f, ((Behaviour)val).enabled ? 30 : 5, 2f);
			row.Dawn = Number("Dawn", 0.33f, 0.46f, num);
			row.Earned = Number("Earned", 0.46f, 0.62f, num);
			row.Spent = Number("Spent", 0.62f, 0.76f, num);
			row.Now = Number("Now", 0.76f, 0.88f, num);
			row.Net = Number("Net", 0.88f, 1f, num);
			rows.Add(row);
			num += 24f;
		}
		historyCaption = Label(book, "", 21, (TextAnchor)4);
		((Graphic)historyCaption).color = Color32.op_Implicit(Gold);
		Place(((Graphic)historyCaption).rectTransform, 0f, 1f, num, 26f);
		coverageNote = Label(book, "* Counts start at first observation and exclude gaps.", 20, (TextAnchor)4);
		((Graphic)coverageNote).color = Color32.op_Implicit(Gold);
		bookHeight = num + 36f;
		older = MakeHint(book, "Game/PauseToggle", "Older", 0.18f, 0.5f, num + 26f);
		newer = MakeHint(book, "Game/ChangeGameSpeed", "Newer", 0.55f, 0.9f, num + 26f);
	}

	private ButtonHint MakeHint(RectTransform parent, string action, string verb, float left, float right, float top)
	{
		//IL_0014: 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_0024: Expected O, but got Unknown
		RectTransform val = (RectTransform)new GameObject(verb, new Type[1] { typeof(RectTransform) }).transform;
		((Transform)val).SetParent((Transform)(object)parent, false);
		Place(val, left, right, top, 26f);
		Image val2 = GraphicChild<Image>(val, "Button");
		val2.preserveAspect = true;
		Place(((Graphic)val2).rectTransform, 0f, 0f, 0f, 24f, 0f, -26f);
		Text label = Label(val, verb, 20, (TextAnchor)3);
		return new ButtonHint
		{
			Root = val,
			Icon = val2,
			Label = label,
			Action = action,
			Verb = verb
		};
	}

	internal void UpdateControllerHints(PlayerInput player, bool canGoOlder, bool canGoNewer)
	{
		ShowHint(older, player, canGoOlder);
		ShowHint(newer, player, canGoNewer);
	}

	private static void ShowHint(ButtonHint hint, PlayerInput player, bool available)
	{
		string bindingName = "";
		Sprite val = (available ? ControllerLedger.Glyph(player, hint.Action, out bindingName) : null);
		bool flag = (Object)(object)val != (Object)null || !string.IsNullOrEmpty(bindingName);
		((Component)hint.Root).gameObject.SetActive(flag);
		if (flag)
		{
			hint.Icon.sprite = val;
			((Behaviour)hint.Icon).enabled = (Object)(object)val != (Object)null;
			hint.Label.text = (((Object)(object)val == (Object)null && !string.IsNullOrEmpty(bindingName)) ? (bindingName + "  " + hint.Verb) : hint.Verb);
			Place(((Graphic)hint.Label).rectTransform, 0f, 1f, 0f, 26f, ((Object)(object)val != (Object)null) ? 29 : 0, 2f);
		}
	}

	private void ColumnTitle(string title, float left, float right)
	{
		//IL_0031: 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)
		Text obj = Label(book, title, 23, (TextAnchor)5);
		Place(((Graphic)obj).rectTransform, left, right, 0f, 26f, 1f, 5f);
		((Graphic)obj).color = Color32.op_Implicit(Gold);
	}

	private Text Number(string name, float left, float right, float y)
	{
		Text obj = Label(book, name, 24, (TextAnchor)5);
		Place(((Graphic)obj).rectTransform, left, right, y, 24f, 1f, 5f);
		return obj;
	}

	internal bool SyncView(bool expanded, bool showHistoryHints, bool recording)
	{
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: 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_0117: Unknown result type (might be due to invalid IL or missing references)
		bool flag = expanded && recording && rows.Exists((Row row) => row.Entry.Balance.IsPartial);
		bool num = expanded != detailed || historyHintsVisible != showHistoryHints || flag != noteVisible;
		noteVisible = flag;
		if (num)
		{
			SetView(expanded, showHistoryHints);
		}
		if (expanded && (Object)(object)viewport != (Object)null)
		{
			float y = ((Transform)viewport).InverseTransformPoint(((Transform)frame).position).y;
			float num2 = Mathf.Abs(((Transform)viewport).InverseTransformVector(((Transform)frame).parent.TransformVector(Vector3.up)).y);
			Rect rect = viewport.rect;
			float num3 = y - ((Rect)(ref rect)).yMin - 8f;
			if (num3 > 0f && num2 > 0f)
			{
				((Transform)frame).localScale = Vector3.one * Mathf.Min(1f, num3 / (frame.sizeDelta.y * num2));
			}
		}
		return num;
	}

	private void SetView(bool expanded, bool showHistoryHints)
	{
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		detailed = expanded;
		historyHintsVisible = showHistoryHints;
		((Component)older.Root).gameObject.SetActive(showHistoryHints);
		((Component)newer.Root).gameObject.SetActive(showHistoryHints);
		((Component)strip).gameObject.SetActive(!expanded);
		((Component)book).gameObject.SetActive(expanded);
		((Component)coverageNote).gameObject.SetActive(noteVisible);
		float num = (showHistoryHints ? 26 : 0);
		Place(((Graphic)coverageNote).rectTransform, 0f, 1f, bookHeight - 10f + num, 24f, 5f, 5f);
		((Transform)frame).localScale = Vector3.one;
		frame.pivot = new Vector2(1f, 1f);
		frame.sizeDelta = new Vector2((float)(expanded ? 140 : 0), expanded ? (bookHeight + num + (float)(noteVisible ? 24 : 0)) : 36f);
		frame.anchoredPosition = new Vector2(0f, -4f);
	}

	internal void Refresh(string caption, bool recording)
	{
		//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0344: Unknown result type (might be due to invalid IL or missing references)
		//IL_0346: Unknown result type (might be due to invalid IL or missing references)
		//IL_0371: Unknown result type (might be due to invalid IL or missing references)
		//IL_0373: Unknown result type (might be due to invalid IL or missing references)
		historyCaption.text = caption;
		foreach (Row row in rows)
		{
			Balance balance = row.Entry.Balance;
			bool flag = recording && balance.HasSample;
			bool flag2 = flag && balance.IsPartial;
			if (!row.Painted || row.ShowGross != flag || row.Partial != flag2 || row.LastDawn != balance.Dawn || row.LastNow != balance.Now || row.LastEarned != balance.Earned || row.LastSpent != balance.Spent)
			{
				if (!row.Painted || row.Partial != flag2)
				{
					row.Title.text = (flag2 ? (row.Entry.Label + "*") : row.Entry.Label);
				}
				row.Painted = true;
				row.ShowGross = flag;
				row.Partial = flag2;
				row.LastDawn = balance.Dawn;
				row.LastNow = balance.Now;
				row.LastEarned = balance.Earned;
				row.LastSpent = balance.Spent;
				row.Earned.text = (flag ? balance.Earned.ToString() : "–");
				row.Spent.text = (flag ? balance.Spent.ToString() : "–");
				long? num = (long?)balance.Now - (long?)balance.Dawn;
				string text = num?.ToString("+0;-0;0") ?? "–";
				Color32 val = ((num > 0) ? Gain : ((num < 0) ? Loss : Color32.op_Implicit(Color.white)));
				row.Dawn.text = balance.Dawn?.ToString() ?? "–";
				row.Now.text = balance.Now?.ToString() ?? "–";
				row.Net.text = text;
				((Graphic)row.Net).color = Color32.op_Implicit(val);
				if ((Object)(object)row.Compact != (Object)null)
				{
					row.Compact.text = text;
					((Graphic)row.Compact).color = Color32.op_Implicit(val);
				}
			}
		}
	}

	private static T GraphicChild<T>(RectTransform parent, string name) where T : Graphic
	{
		//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)
		GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
		val.transform.SetParent((Transform)(object)parent, false);
		T val2 = val.AddComponent<T>();
		((Graphic)val2).raycastTarget = false;
		return val2;
	}

	private Text Label(RectTransform parent, string text, int size, TextAnchor alignment)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		Text obj = GraphicChild<Text>(parent, text);
		obj.font = fontSource.font;
		obj.fontStyle = fontSource.fontStyle;
		int fontSize = (obj.resizeTextMaxSize = size);
		obj.fontSize = fontSize;
		obj.resizeTextMinSize = 12;
		obj.resizeTextForBestFit = true;
		obj.alignment = alignment;
		obj.supportRichText = false;
		obj.text = text;
		return obj;
	}

	private static void Place(RectTransform rect, float left, float right, float top, float height, float insetLeft = 0f, float insetRight = 0f)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		rect.anchorMin = new Vector2(left, 1f);
		rect.anchorMax = new Vector2(right, 1f);
		rect.offsetMin = new Vector2(insetLeft, 0f - top - height);
		rect.offsetMax = new Vector2(0f - insetRight, 0f - top);
	}
}
[BepInPlugin("sfk.daybook", "Daybook", "0.4.1")]
public sealed class DaybookPlugin : BaseUnityPlugin
{
	private ConfigEntry<bool> showOverlay;

	private ResourceLedger ledger;

	private CityManager detailedCity;

	private float nextRefresh;

	private DaybookPanel panel;

	private float nextBind;

	private Journal journal;

	private DayRecord history;

	private string[] previous = Array.Empty<string>();

	private int historyIndex = -1;

	private int day;

	private Guid run;

	private bool tracking;

	private bool dirty;

	private float nextWrite;

	private float nextPoll;

	private float nextCatalog;

	private string lastError;

	private Harmony patches;

	internal string LoadedHash;

	private void Awake()
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		showOverlay = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOverlay", true, "Show resource balances and changes since dawn.");
		ControllerLedger.Plugin = this;
		GameCheckpoints.Plugin = this;
		patches = new Harmony("sfk.daybook.checkpoints");
		patches.PatchAll(typeof(GameCheckpoints.Load));
		patches.PatchAll(typeof(GameCheckpoints.Save));
		patches.PatchAll(typeof(ControllerLedger.OlderAction));
		patches.PatchAll(typeof(ControllerLedger.NewerAction));
		patches.PatchAll(typeof(ControllerLedger.HudAction));
		DirectStockChanges.Install(patches);
		DirectStockChanges.Changed += ResourceChanged;
		GameManager.OnGameInit += CloseDay;
		GameManager.BeforeSave += CaptureAndFlush;
		ResourceManager.OnResourceAmountChanged += ResourceChanged;
		DaytimeManager.OnMorningStart += RecordDawn;
		CityManager.WorkerToggle += SetDetailedView;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Daybook ready. Waiting for dawn.");
	}

	private void OnDestroy()
	{
		CloseDay();
		ControllerLedger.Plugin = null;
		GameCheckpoints.Plugin = null;
		DirectStockChanges.Changed -= ResourceChanged;
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		GameManager.OnGameInit -= CloseDay;
		GameManager.BeforeSave -= CaptureAndFlush;
		ResourceManager.OnResourceAmountChanged -= ResourceChanged;
		DaytimeManager.OnMorningStart -= RecordDawn;
		CityManager.WorkerToggle -= SetDetailedView;
		if ((Object)(object)panel != (Object)null)
		{
			Object.Destroy((Object)(object)((Component)panel).gameObject);
		}
	}

	private void SetDetailedView(bool enabled)
	{
		detailedCity = (enabled ? CityManager.Instance : null);
	}

	private void OnApplicationQuit()
	{
		CaptureAndFlush();
		tracking = false;
	}

	private void CaptureAndFlush()
	{
		if (tracking && (Object)(object)ledger.Kingdom != (Object)null && (Object)(object)ledger.Kingdom == (Object)(object)ResourceManager.Instance && (Object)(object)GameManager.Instance != (Object)null && !GameManager.Instance.IsUnloading())
		{
			dirty |= ledger.RefreshCatalog();
			dirty |= ledger.Read();
		}
		Flush();
	}

	private void CloseDay()
	{
		Flush();
		tracking = (dirty = false);
		journal = null;
		history = null;
		historyIndex = -1;
		previous = Array.Empty<string>();
		LoadedHash = null;
	}

	private void RecordDawn(int newDay)
	{
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected I4, but got Unknown
		string loadedHash = LoadedHash;
		CloseDay();
		if (!BindLedger())
		{
			return;
		}
		day = newDay;
		ledger.RefreshCatalog();
		ledger.Read();
		DayRecord saved = null;
		if (Guid.TryParse(GameDataManager.Instance.GetRunID(), out run))
		{
			journal = new Journal(Path.Combine(Application.persistentDataPath, "Daybook"), SettingsManager.Instance.GetProfile() + 1, (int)ledger.Race.GetRace(), run);
			try
			{
				previous = journal.Previous();
				if (!string.IsNullOrEmpty(loadedHash))
				{
					saved = journal.LoadCheckpoint(Journal.Fingerprint(loadedHash));
				}
			}
			catch (Exception error)
			{
				ReportJournalError(error);
			}
		}
		ledger.BeginDay(day, saved);
		tracking = (dirty = true);
		nextRefresh = (nextWrite = 0f);
		Flush();
	}

	internal void ReportJournalError(Exception error)
	{
		if (lastError != error.Message)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Daybook journal: " + error.Message));
		}
		lastError = error.Message;
	}

	private void Flush()
	{
		if (!dirty || journal == null || ledger == null)
		{
			return;
		}
		try
		{
			journal.Save(ledger.Snapshot(day));
			dirty = false;
			lastError = null;
		}
		catch (Exception error)
		{
			ReportJournalError(error);
		}
	}

	internal void Checkpoint(string savedRun, string hash)
	{
		if (tracking && journal != null && !((Object)(object)ledger.Kingdom != (Object)(object)ResourceManager.Instance) && Guid.TryParse(savedRun, out var result) && !(result != run) && !string.IsNullOrEmpty(hash))
		{
			dirty |= ledger.RefreshCatalog();
			dirty |= ledger.Read();
			journal.SaveCheckpoint(Journal.Fingerprint(hash), ledger.Snapshot(day));
			Flush();
		}
	}

	private void ResourceChanged(ResourceType type)
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		if (tracking && (Object)(object)ledger.Kingdom != (Object)null && (Object)(object)ledger.Kingdom == (Object)(object)ResourceManager.Instance && (Object)(object)GameManager.Instance != (Object)null && !GameManager.Instance.IsUnloading())
		{
			dirty |= ledger.Changed(type);
		}
	}

	private bool CanBrowseHistory()
	{
		if (previous.Length != 0 && (Object)(object)panel != (Object)null && ((Behaviour)panel).isActiveAndEnabled && (Object)(object)UIManager.Instance != (Object)null)
		{
			return UIManager.Instance.IsWorldInteractable();
		}
		return false;
	}

	internal bool CanPageWithController()
	{
		PlayerInput val = ControllerLedger.ActivePlayer();
		PauseMenuManger instance = PauseMenuManger.Instance;
		if ((Object)(object)val != (Object)null && showOverlay.Value && CanBrowseHistory() && (Object)(object)detailedCity != (Object)null && (Object)(object)detailedCity == (Object)(object)CityManager.Instance)
		{
			InputAction obj = val.actions.FindAction("Game/WorkerMenu", false);
			if (obj != null && obj.IsPressed())
			{
				if (!((Object)(object)instance == (Object)null))
				{
					if (!instance.InMenu())
					{
						return !instance.IsOpen();
					}
					return false;
				}
				return true;
			}
		}
		return false;
	}

	internal void PageHistory(int step)
	{
		int target = Math.Max(-1, Math.Min(previous.Length - 1, historyIndex + step));
		if (SelectHistory(target))
		{
			nextRefresh = 0f;
		}
	}

	private bool SelectHistory(int target)
	{
		if (target == historyIndex)
		{
			return false;
		}
		if (target >= 0)
		{
			return journal.Browse(ref previous, ref historyIndex, ref history, target, ReportJournalError);
		}
		history = null;
		historyIndex = -1;
		return true;
	}

	private bool BindLedger()
	{
		ResourceManager instance = ResourceManager.Instance;
		RaceManager instance2 = RaceManager.Instance;
		if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)CityManager.Instance == (Object)null)
		{
			return false;
		}
		if (ledger == null || (Object)(object)ledger.Kingdom != (Object)(object)instance || (Object)(object)ledger.Race != (Object)(object)instance2)
		{
			if ((Object)(object)panel != (Object)null)
			{
				((Component)panel).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)panel).gameObject);
				panel = null;
			}
			if (tracking)
			{
				CloseDay();
			}
			ledger = new ResourceLedger(instance, instance2);
			nextRefresh = (nextBind = 0f);
		}
		return true;
	}

	private void LateUpdate()
	{
		bool flag = (Object)(object)DaytimeManager.Instance != (Object)null && (Object)(object)GameManager.Instance != (Object)null && GameManager.Instance.IsGameLoaded() && !GameManager.Instance.IsUnloading() && BindLedger();
		if (flag && Time.unscaledTime >= nextPoll)
		{
			nextPoll = Time.unscaledTime + 0.5f;
			bool flag2 = false;
			if (Time.unscaledTime >= nextCatalog)
			{
				nextCatalog = Time.unscaledTime + 2f;
				flag2 = ledger.RefreshCatalog();
			}
			if ((ledger.Read() || flag2) && tracking)
			{
				dirty = true;
			}
		}
		if (dirty && Time.unscaledTime >= nextWrite)
		{
			nextWrite = Time.unscaledTime + 2f;
			Flush();
		}
		PauseMenuManger instance = PauseMenuManger.Instance;
		if (!showOverlay.Value || !flag || ((Object)(object)instance != (Object)null && (instance.InMenu() || instance.IsOpen())))
		{
			if ((Object)(object)panel != (Object)null && ((Component)panel).gameObject.activeSelf)
			{
				((Component)panel).gameObject.SetActive(false);
			}
			return;
		}
		if ((Object)(object)panel == (Object)null)
		{
			if (Time.unscaledTime < nextBind)
			{
				return;
			}
			nextBind = Time.unscaledTime + 1f;
			UIHeader val = Object.FindObjectOfType<UIHeader>();
			if ((Object)(object)val == (Object)null || (Object)(object)(panel = DaybookPanel.Attach(val, ledger)) == (Object)null)
			{
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Resource HUD attached: {ledger.HeaderCount} header counters, {ledger.Entries.Count} ledger rows.");
			nextRefresh = 0f;
		}
		bool num = !((Component)panel).gameObject.activeSelf;
		if (num)
		{
			((Component)panel).gameObject.SetActive(true);
		}
		bool flag3 = (Object)(object)detailedCity != (Object)null && (Object)(object)detailedCity == (Object)(object)CityManager.Instance;
		PlayerInput val2 = ControllerLedger.ActivePlayer();
		if ((Object)(object)val2 != (Object)null)
		{
			bool num2 = flag3;
			InputAction obj = val2.actions.FindAction("Game/WorkerMenu", false);
			flag3 = num2 & (obj != null && obj.IsPressed());
		}
		bool flag4 = flag3 && CanBrowseHistory();
		bool flag5 = flag4 && (Object)(object)val2 != (Object)null;
		bool flag6 = false;
		Keyboard current = Keyboard.current;
		if (!flag3)
		{
			flag6 |= SelectHistory(-1);
		}
		else if (flag4 && (Object)(object)val2 == (Object)null && current != null)
		{
			if (((ButtonControl)current.pageUpKey).wasPressedThisFrame)
			{
				PageHistory(1);
			}
			else if (((ButtonControl)current.pageDownKey).wasPressedThisFrame)
			{
				PageHistory(-1);
			}
		}
		flag6 |= panel.SelectRows(ledger, history);
		bool recording = tracking || history != null;
		flag6 |= panel.SyncView(flag3, flag5, recording);
		if (!num && !flag6 && Time.unscaledTime < nextRefresh)
		{
			return;
		}
		nextRefresh = Time.unscaledTime + 0.5f;
		string text = ((history != null) ? $"Saved Day {history.Day} ({historyIndex + 1}/{previous.Length})" : (tracking ? $"Day {day}" : "Waiting for dawn"));
		bool flag7 = historyIndex + 1 < previous.Length;
		bool flag8 = historyIndex >= 0;
		if (flag4 && (Object)(object)val2 == (Object)null && current != null)
		{
			if (flag7)
			{
				text += "   PgUp Older";
			}
			if (flag8)
			{
				text += (flag7 ? " / PgDn Newer" : "   PgDn Newer");
			}
		}
		panel.Refresh(text, recording);
		if (flag5)
		{
			panel.UpdateControllerHints(val2, flag7, flag8);
		}
	}
}
internal static class DirectStockChanges
{
	internal static event Action<ResourceType> Changed;

	internal static void Install(Harmony harmony)
	{
		Type? typeFromHandle = typeof(ResourceManager);
		Watch(typeFromHandle, "SetCoins", Coins);
		Watch(typeFromHandle, "AddToCoins", Coins);
		Watch(typeFromHandle, "SetShards", Shards);
		Watch(typeFromHandle, "AddToShards", Shards);
		Watch(typeFromHandle, "SetStars", Stars);
		Watch(typeFromHandle, "AddToStars", Stars);
		Watch(typeFromHandle, "SetSuperMetal", SuperMetal);
		Watch(typeFromHandle, "AddToSuperMetal", SuperMetal);
		Watch(typeof(FaithManager), "SetFaith", Faith);
		void Watch(Type manager, string method, Action observed)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(manager, method, new Type[1] { typeof(int) }, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(observed.Method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}

	private static void Coins()
	{
		DirectStockChanges.Changed?.Invoke((ResourceType)12);
	}

	private static void Shards()
	{
		DirectStockChanges.Changed?.Invoke((ResourceType)23);
	}

	private static void Stars()
	{
		DirectStockChanges.Changed?.Invoke((ResourceType)54);
	}

	private static void SuperMetal()
	{
		DirectStockChanges.Changed?.Invoke((ResourceType)44);
	}

	private static void Faith()
	{
		DirectStockChanges.Changed?.Invoke((ResourceType)13);
	}
}
internal static class GameCheckpoints
{
	[Serializable]
	private sealed class SaveIdentity
	{
		public string runID;

		public string hash;
	}

	[HarmonyPatch(typeof(GameDataManager), "Load")]
	internal static class Load
	{
		private static void Prefix(GameData ___m_GameData)
		{
			if ((Object)(object)Plugin != (Object)null)
			{
				Plugin.LoadedHash = ___m_GameData?.hash;
			}
		}
	}

	[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	internal static class Save
	{
		private static void Postfix(string __0, string __1)
		{
			if ((Object)(object)Plugin == (Object)null || __0 == null || !__0.EndsWith("_game", StringComparison.Ordinal))
			{
				return;
			}
			try
			{
				SaveIdentity saveIdentity = JsonUtility.FromJson<SaveIdentity>(__1);
				if (saveIdentity != null)
				{
					Plugin.Checkpoint(saveIdentity.runID, saveIdentity.hash);
				}
			}
			catch (Exception error)
			{
				Plugin.ReportJournalError(error);
			}
		}
	}

	internal static DaybookPlugin Plugin;
}
[DataContract]
internal sealed class Balance
{
	[DataMember]
	internal int? Dawn;

	[DataMember]
	internal int? Now;

	[DataMember]
	internal long Earned;

	[DataMember]
	internal long Spent;

	[DataMember(EmitDefaultValue = false)]
	internal string Asset;

	[DataMember(EmitDefaultValue = false)]
	internal string Label;

	[DataMember(EmitDefaultValue = false)]
	internal string Group;

	[DataMember(EmitDefaultValue = false)]
	internal bool ObservationGap;

	internal bool HasSample
	{
		get
		{
			if (!Dawn.HasValue && !Now.HasValue && Earned == 0L)
			{
				return Spent != 0;
			}
			return true;
		}
	}

	internal bool IsPartial
	{
		get
		{
			if (HasSample)
			{
				if (!ObservationGap && Dawn.HasValue && Now.HasValue)
				{
					return (long)Now.Value - (long)Dawn.Value != Earned - Spent;
				}
				return true;
			}
			return false;
		}
	}

	internal bool SameResource(string asset)
	{
		if (!string.IsNullOrEmpty(Asset))
		{
			return Asset == asset;
		}
		return true;
	}

	internal bool Observe(int? amount)
	{
		if (Now == amount)
		{
			return false;
		}
		if (Now.HasValue && !amount.HasValue)
		{
			ObservationGap = true;
		}
		if (Now.HasValue && amount.HasValue)
		{
			long num = (long)amount.Value - (long)Now.Value;
			if (num > 0)
			{
				Earned += num;
			}
			else
			{
				Spent -= num;
			}
		}
		Now = amount;
		return true;
	}

	internal Balance Copy()
	{
		return (Balance)MemberwiseClone();
	}
}
[DataContract]
internal sealed class DayRecord
{
	[DataMember]
	internal int Version = 1;

	[DataMember]
	internal int Day;

	[DataMember]
	internal Dictionary<int, Balance> Rows = new Dictionary<int, Balance>();

	[DataMember(EmitDefaultValue = false)]
	internal List<KeyValuePair<int, Balance>> Removed;

	internal IEnumerable<KeyValuePair<int, Balance>> AllRows()
	{
		foreach (KeyValuePair<int, Balance> row in Rows)
		{
			yield return row;
		}
		if (Removed == null)
		{
			yield break;
		}
		foreach (KeyValuePair<int, Balance> item in Removed)
		{
			yield return item;
		}
	}
}
internal sealed class Journal
{
	private readonly string directory;

	private readonly string current;

	private readonly DataContractJsonSerializer format = new DataContractJsonSerializer(typeof(DayRecord));

	internal Journal(string root, int profile, int race, Guid run)
	{
		directory = Path.Combine(root, profile.ToString(), race.ToString(), run.ToString("N"));
		current = Path.Combine(directory, $"day-{DateTime.UtcNow.Ticks:D19}-{Guid.NewGuid():N}.json");
	}

	internal void Save(DayRecord record)
	{
		Write(current, record);
	}

	internal string[] Previous()
	{
		if (!Directory.Exists(directory))
		{
			return Array.Empty<string>();
		}
		return (from path in Directory.GetFiles(directory, "day-*.json")
			where path != current
			select path).OrderByDescending<string, string>((string path) => path, StringComparer.Ordinal).ToArray();
	}

	internal bool Browse(ref string[] pages, ref int index, ref DayRecord selected, int target, Action<Exception> report)
	{
		string text = ((index >= 0) ? pages[index] : null);
		int num = ((target > index) ? 1 : (-1));
		HashSet<string> unreadable = null;
		bool flag = false;
		while (target >= 0 && target < pages.Length)
		{
			string text2 = pages[target];
			DayRecord dayRecord = null;
			try
			{
				dayRecord = Read(text2);
			}
			catch (Exception obj)
			{
				report(obj);
			}
			if (dayRecord != null)
			{
				selected = dayRecord;
				text = text2;
				flag = true;
				break;
			}
			(unreadable ?? (unreadable = new HashSet<string>())).Add(text2);
			target += num;
		}
		if (unreadable != null)
		{
			pages = Array.FindAll(pages, (string path) => !unreadable.Contains(path));
		}
		index = ((text == null) ? (-1) : Array.IndexOf(pages, text));
		if (!flag)
		{
			return unreadable != null;
		}
		return true;
	}

	internal static string Fingerprint(string json)
	{
		using SHA256 sHA = SHA256.Create();
		return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(json))).Replace("-", "");
	}

	private string Checkpoint(string fingerprint)
	{
		return Path.Combine(directory, "save-" + fingerprint + ".json");
	}

	internal void SaveCheckpoint(string fingerprint, DayRecord record)
	{
		Write(Checkpoint(fingerprint), record);
	}

	internal DayRecord LoadCheckpoint(string fingerprint)
	{
		return Read(Checkpoint(fingerprint));
	}

	internal DayRecord Read(string path)
	{
		if (!File.Exists(path))
		{
			return null;
		}
		using FileStream stream = File.OpenRead(path);
		if (!(format.ReadObject(stream) is DayRecord { Version: 1, Rows: not null } dayRecord) || dayRecord.Rows.Count == 0 || dayRecord.AllRows().Any((KeyValuePair<int, Balance> row) => row.Value == null || row.Value.Earned < 0 || row.Value.Spent < 0))
		{
			throw new InvalidDataException("Unrecognized Daybook record.");
		}
		return dayRecord;
	}

	private void Write(string path, DayRecord record)
	{
		Directory.CreateDirectory(directory);
		string text = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
		try
		{
			using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None))
			{
				format.WriteObject(fileStream, record);
				fileStream.Flush(flushToDisk: true);
			}
			if (File.Exists(path))
			{
				File.Replace(text, path, null);
			}
			else
			{
				File.Move(text, path);
			}
		}
		finally
		{
			if (File.Exists(text))
			{
				File.Delete(text);
			}
		}
	}
}
internal sealed class LedgerTooltipLayout
{
	private static readonly FieldInfo TipRect = AccessTools.Field(typeof(TooltipManager), "rectTransform");

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

	private TooltipManager owner;

	private RectTransform tip;

	private Vector3 original;

	private Vector3 shifted;

	private bool moved;

	internal void Restore()
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		if (moved && (Object)(object)tip != (Object)null && ((Transform)tip).localPosition == shifted)
		{
			((Transform)tip).localPosition = original;
		}
		moved = false;
	}

	internal void Place(RectTransform ledger, RectTransform viewport)
	{
		//IL_00ae: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		Restore();
		if ((Object)(object)ledger == (Object)null || (Object)(object)viewport == (Object)null)
		{
			return;
		}
		TooltipManager instance = TooltipManager.Instance;
		if ((Object)(object)instance == (Object)null || !instance.IsOpen())
		{
			return;
		}
		if ((Object)(object)owner != (Object)(object)instance || (Object)(object)tip == (Object)null)
		{
			owner = instance;
			ref RectTransform reference = ref tip;
			object? obj = TipRect?.GetValue(instance);
			reference = (RectTransform)((obj is RectTransform) ? obj : null);
		}
		if ((Object)(object)tip == (Object)null || !((Component)tip).gameObject.activeInHierarchy)
		{
			return;
		}
		Rect bounds = Bounds(tip, viewport);
		Rect val = Bounds(ledger, viewport);
		Vector2 best;
		float distance;
		if (((Rect)(ref bounds)).Overlaps(val))
		{
			float num = 4f * Mathf.Abs(((Transform)viewport).InverseTransformVector(((Transform)ledger).TransformVector(Vector3.up)).y);
			best = Vector2.zero;
			distance = float.PositiveInfinity;
			TryOffset(0f, ((Rect)(ref val)).yMin - ((Rect)(ref bounds)).yMax - num);
			TryOffset(((Rect)(ref val)).xMax - ((Rect)(ref bounds)).xMin + num, 0f);
			TryOffset(((Rect)(ref val)).xMin - ((Rect)(ref bounds)).xMax - num, 0f);
			if (!(best == Vector2.zero))
			{
				original = ((Transform)tip).localPosition;
				RectTransform obj2 = tip;
				((Transform)obj2).position = ((Transform)obj2).position + ((Transform)viewport).TransformVector(Vector2.op_Implicit(best));
				shifted = ((Transform)tip).localPosition;
				moved = true;
			}
		}
		void TryOffset(float x, float y)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0037: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(x, y);
			Rect val3 = default(Rect);
			((Rect)(ref val3))..ctor(((Rect)(ref bounds)).position + val2, ((Rect)(ref bounds)).size);
			Rect rect = viewport.rect;
			if (!(((Rect)(ref val3)).xMin < ((Rect)(ref rect)).xMin) && !(((Rect)(ref val3)).yMin < ((Rect)(ref rect)).yMin) && !(((Rect)(ref val3)).xMax > ((Rect)(ref rect)).xMax) && !(((Rect)(ref val3)).yMax > ((Rect)(ref rect)).yMax) && !(((Vector2)(ref val2)).sqrMagnitude >= distance))
			{
				best = val2;
				distance = ((Vector2)(ref val2)).sqrMagnitude;
			}
		}
	}

	internal bool OverlapsVisible(RectTransform frame, RectTransform obstacle, RectTransform viewport)
	{
		//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_0024: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)obstacle != (Object)null && ((Component)obstacle).gameObject.activeInHierarchy)
		{
			Rect val = Bounds(frame, viewport);
			return ((Rect)(ref val)).Overlaps(Bounds(obstacle, viewport));
		}
		return false;
	}

	private Rect Bounds(RectTransform target, RectTransform viewport)
	{
		//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)
		target.GetWorldCorners(corners);
		Vector3 val = ((Transform)viewport).InverseTransformPoint(corners[0]);
		Vector3 val2 = ((Transform)viewport).InverseTransformPoint(corners[2]);
		return Rect.MinMaxRect(val.x, val.y, val2.x, val2.y);
	}
}
internal sealed class LedgerEntry
{
	internal readonly ResourceType Type;

	internal readonly ResourceData Data;

	internal readonly string Group;

	internal Balance Balance = new Balance();

	internal string Label;

	internal readonly string Asset;

	internal readonly Sprite Icon;

	internal unsafe LedgerEntry(ResourceType type, ResourceData data, string group, string label = null)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Invalid comparison between Unknown and I4
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Expected I4, but got Unknown
		Type = type;
		Data = data;
		Group = group;
		Asset = (((Object)(object)data == (Object)null) ? null : ((Object)data).name);
		Icon = (((Object)(object)data == (Object)null) ? null : data.icon);
		Label = label ?? (((Object)(object)data != (Object)null && data.stringTitle != null) ? data.GetName() : null);
		if (string.IsNullOrEmpty(Label))
		{
			Label = (((int)type == 44) ? "Super Metal" : (Enum.IsDefined(typeof(ResourceType), type) ? ((object)(*(ResourceType*)(&type))/*cast due to .constrained prefix*/).ToString() : $"Resource {(int)type}"));
		}
	}
}
internal sealed class ResourceLedger
{
	internal readonly ResourceManager Kingdom;

	internal readonly RaceManager Race;

	private readonly HashSet<ResourceType> notified = new HashSet<ResourceType>();

	private readonly List<KeyValuePair<int, Balance>> removed = new List<KeyValuePair<int, Balance>>();

	internal List<LedgerEntry> Entries { get; private set; } = new List<LedgerEntry>();

	internal int HeaderCount { get; private set; }

	internal int Revision { get; private set; }

	internal ResourceLedger(ResourceManager kingdom, RaceManager race)
	{
		Kingdom = kingdom;
		Race = race;
		RefreshCatalog();
	}

	private static Balance CopyRow(LedgerEntry entry)
	{
		Balance balance = entry.Balance.Copy();
		balance.Asset = entry.Asset;
		balance.Label = entry.Label;
		balance.Group = entry.Group;
		return balance;
	}

	private void RememberRemoved(int key, Balance balance)
	{
		removed.RemoveAll((KeyValuePair<int, Balance> pair) => pair.Key == key && pair.Value.Asset == balance.Asset);
		removed.Add(new KeyValuePair<int, Balance>(key, balance));
	}

	internal bool RefreshCatalog()
	{
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: 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_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0262: Unknown result type (might be due to invalid IL or missing references)
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Unknown result type (might be due to invalid IL or missing references)
		//IL_0330: Unknown result type (might be due to invalid IL or missing references)
		//IL_0337: Unknown result type (might be due to invalid IL or missing references)
		//IL_042a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0440: Expected I4, but got Unknown
		//IL_050a: Unknown result type (might be due to invalid IL or missing references)
		List<LedgerEntry> next = new List<LedgerEntry>();
		HashSet<ResourceType> seen = new HashSet<ResourceType>();
		List<ResourceData> mainResources = Race.GetMainResources();
		if (mainResources != null)
		{
			foreach (ResourceData item2 in mainResources)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					Add(item2.type, item2, "Materials");
				}
			}
		}
		int count = next.Count;
		List<ResourceType> foods = Kingdom.GetFoods();
		if (foods != null)
		{
			foreach (ResourceType item3 in foods)
			{
				Add(item3, Race.GetResourceData(item3), "Food and supplies");
			}
		}
		ResourceType[] array = (ResourceType[])(object)new ResourceType[2]
		{
			(ResourceType)8,
			(ResourceType)1
		};
		foreach (ResourceType val in array)
		{
			Add(val, Race.GetResourceData(val), "Food and supplies");
		}
		array = (ResourceType[])(object)new ResourceType[2]
		{
			(ResourceType)12,
			(ResourceType)13
		};
		foreach (ResourceType val2 in array)
		{
			Add(val2, Race.GetResourceData(val2), "Currency", universal: true);
		}
		ResourceType[] array2 = new ResourceType[3];
		RuntimeHelpers.InitializeArray(array2, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		array = (ResourceType[])(object)array2;
		foreach (ResourceType val3 in array)
		{
			Add(val3, Race.GetResourceData(val3), "Progression", universal: true);
		}
		CityManager instance = CityManager.Instance;
		List<BuildingCity> list = ((instance != null) ? instance.GetBuildings() : null);
		if (list != null)
		{
			foreach (BuildingCity item4 in list)
			{
				object obj;
				if (item4 == null)
				{
					obj = null;
				}
				else
				{
					ResourceStorage storage = ((Building)item4).GetStorage();
					obj = ((storage != null) ? storage.GetStorageSpaces() : null);
				}
				int[] array3 = (int[])obj;
				if (array3 == null)
				{
					continue;
				}
				for (int j = 0; j < array3.Length; j++)
				{
					if (array3[j] > 0)
					{
						AddStock((ResourceType)j);
					}
				}
			}
		}
		Dictionary<ResourceType, int> startingResourcesDictionary = Kingdom.GetStartingResourcesDictionary();
		if (startingResourcesDictionary != null)
		{
			foreach (ResourceType key in startingResourcesDictionary.Keys)
			{
				if (!Enum.IsDefined(typeof(ResourceType), key))
				{
					AddStock(key);
				}
			}
		}
		foreach (ResourceType item5 in notified)
		{
			AddStock(item5);
		}
		bool flag = HeaderCount != count || Entries.Count != next.Count;
		int num = 0;
		while (!flag && num < next.Count)
		{
			LedgerEntry ledgerEntry = Entries[num];
			LedgerEntry ledgerEntry2 = next[num];
			flag = ledgerEntry.Type != ledgerEntry2.Type || (Object)(object)ledgerEntry.Data != (Object)(object)ledgerEntry2.Data || ledgerEntry.Asset != ledgerEntry2.Asset || ledgerEntry.Group != ledgerEntry2.Group || ledgerEntry.Label != ledgerEntry2.Label || (Object)(object)ledgerEntry.Icon != (Object)(object)ledgerEntry2.Icon;
			num++;
		}
		if (!flag)
		{
			return false;
		}
		foreach (LedgerEntry old in Entries)
		{
			if (old.Balance.Now.HasValue && !next.Exists((LedgerEntry e) => e.Type == old.Type && e.Asset == old.Asset))
			{
				RememberRemoved((int)old.Type, CopyRow(old));
			}
		}
		foreach (LedgerEntry item in next)
		{
			if (Entries.Exists((LedgerEntry e) => e.Type == item.Type && e.Asset == item.Asset))
			{
				continue;
			}
			Balance match = FindSaved(removed, item, next);
			if (match != null)
			{
				item.Balance = match.Copy();
				item.Balance.ObservationGap = true;
				item.Balance.Now = Amount(item.Type);
				removed.RemoveAll((KeyValuePair<int, Balance> pair) => pair.Value == match);
			}
		}
		HeaderCount = count;
		Entries = next;
		Revision++;
		return true;
		void Add(ResourceType type, ResourceData data, string group, bool universal = false)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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)
			if ((Object)(object)data != (Object)null && (int)data.type == 0)
			{
				data = null;
			}
			if (!((Object)(object)data == (Object)null) || universal)
			{
				if ((Object)(object)data != (Object)null)
				{
					type = data.type;
				}
				if ((int)type != 0 && seen.Add(type))
				{
					LedgerEntry entry = new LedgerEntry(type, data, group);
					LedgerEntry ledgerEntry3 = Entries.Find((LedgerEntry ledgerEntry4) => ledgerEntry4.Type == type && ledgerEntry4.Asset == entry.Asset);
					if (ledgerEntry3 != null)
					{
						entry.Balance = ledgerEntry3.Balance;
					}
					next.Add(entry);
				}
			}
		}
		void AddStock(ResourceType type)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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)
			if (!seen.Contains(type))
			{
				ResourceData resourceData = Race.GetResourceData(type);
				if ((Object)(object)resourceData != (Object)null)
				{
					Add(type, resourceData, resourceData.isFood ? "Food and supplies" : "Other stock");
				}
			}
		}
	}

	internal bool Changed(ResourceType type)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: 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_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		ResourceData resourceData = Race.GetResourceData(type);
		ResourceType stock = (((Object)(object)resourceData != (Object)null && (int)resourceData.type != 0) ? resourceData.type : type);
		LedgerEntry ledgerEntry = Entries.Find((LedgerEntry e) => e.Type == stock);
		bool flag = false;
		if ((Object)(object)resourceData != (Object)null && (int)resourceData.type != 0 && ((ledgerEntry != null) ? (ledgerEntry.Asset != ((Object)resourceData).name) : (!Enum.IsDefined(typeof(ResourceType), stock))))
		{
			notified.Add(type);
			flag = RefreshCatalog();
		}
		return Read(stock) || flag;
	}

	private static Balance FindSaved(List<KeyValuePair<int, Balance>> saved, LedgerEntry entry, List<LedgerEntry> catalog)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Invalid comparison between I4 and Unknown
		foreach (KeyValuePair<int, Balance> item in saved)
		{
			if (item.Key == (int)entry.Type && item.Value.SameResource(entry.Asset))
			{
				return item.Value;
			}
		}
		if (string.IsNullOrEmpty(entry.Asset) || catalog.Count((LedgerEntry e) => e.Asset == entry.Asset) != 1)
		{
			return null;
		}
		Balance balance = null;
		foreach (KeyValuePair<int, Balance> item2 in saved)
		{
			if (item2.Value.Asset == entry.Asset)
			{
				if (balance != null)
				{
					return null;
				}
				balance = item2.Value;
			}
		}
		return balance;
	}

	internal List<LedgerEntry> HistoryRows(DayRecord record)
	{
		//IL_0071: 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)
		List<LedgerEntry> list = new List<LedgerEntry>();
		List<KeyValuePair<int, Balance>> saved = record.AllRows().ToList();
		foreach (KeyValuePair<int, Balance> pair in saved)
		{
			ResourceType type = (ResourceType)pair.Key;
			LedgerEntry ledgerEntry = Entries.Find((LedgerEntry e) => e.Type == type && pair.Value.SameResource(e.Asset));
			if (ledgerEntry == null && !string.IsNullOrEmpty(pair.Value.Asset))
			{
				ledgerEntry = Entries.Find((LedgerEntry e) => e.Asset == pair.Value.Asset && FindSaved(saved, e, Entries) == pair.Value);
			}
			string text = pair.Value.Group ?? ledgerEntry?.Group ?? "Archived stock";
			LedgerEntry ledgerEntry2 = new LedgerEntry(type, ledgerEntry?.Data, text, pair.Value.Label ?? ledgerEntry?.Label);
			ledgerEntry2.Balance = pair.Value;
			list.Add(ledgerEntry2);
		}
		return list;
	}

	private int? Amount(ResourceType type)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Invalid comparison between Unknown and I4
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		if ((int)type != 13 || !((Object)(object)FaithManager.Instance == (Object)null))
		{
			return Kingdom.GetResourceAvailableAmount(type, true);
		}
		return null;
	}

	internal bool Read(ResourceType? changed = null)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		bool flag = false;
		foreach (LedgerEntry entry in Entries)
		{
			if (!changed.HasValue || entry.Type == changed.Value)
			{
				flag |= entry.Balance.Observe(Amount(entry.Type));
			}
		}
		return flag;
	}

	internal DayRecord Snapshot(int day)
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected I4, but got Unknown
		DayRecord dayRecord = new DayRecord
		{
			Day = day
		};
		foreach (LedgerEntry entry in Entries)
		{
			dayRecord.Rows.Add((int)entry.Type, CopyRow(entry));
		}
		if (removed.Count > 0)
		{
			dayRecord.Removed = new List<KeyValuePair<int, Balance>>(removed);
		}
		return dayRecord;
	}

	internal void BeginDay(int day, DayRecord saved)
	{
		removed.Clear();
		List<KeyValuePair<int, Balance>> list = ((saved != null && saved.Day == day) ? saved.AllRows().ToList() : null);
		HashSet<Balance> hashSet = new HashSet<Balance>();
		foreach (LedgerEntry entry in Entries)
		{
			int? now = entry.Balance.Now;
			Balance balance = ((list == null) ? null : FindSaved(list, entry, Entries));
			if (balance != null)
			{
				hashSet.Add(balance);
			}
			entry.Balance = ((balance != null && now.HasValue && balance.Now == now) ? balance.Copy() : new Balance
			{
				Dawn = now,
				Now = now
			});
		}
		if (list == null)
		{
			return;
		}
		foreach (KeyValuePair<int, Balance> item in list)
		{
			if (!hashSet.Contains(item.Value))
			{
				RememberRemoved(item.Key, item.Value.Copy());
			}
		}
	}
}