Decompiled source of KingdomCharters v0.1.0

plugins/KingdomCharters.dll

Decompiled 36 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Tavern;
using SuperFantasyKingdom.TitleScreen;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.UI;
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("KingdomCharters")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+47680d1b74cf96f5bb5778a6e78b59161a9c4fa8")]
[assembly: AssemblyProduct("KingdomCharters")]
[assembly: AssemblyTitle("KingdomCharters")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace KingdomCharters;

internal enum Charter
{
	Standard,
	Merchant,
	Forester,
	Mason
}
[Serializable]
internal sealed class CharterState
{
	public Charter choice;

	public int debt;

	public bool openingComplete;

	public int firstVisit;

	internal static readonly string[] Names = new string[4] { "Standard Run", "Merchant Charter", "Forester’s Charter", "Mason’s Charter" };

	internal static readonly string[] Terms = new string[4] { "Play with the usual starting resources and caravan schedule.", "First caravan one day early if the gate and guest slot are open. Pay 1 extra coin per immediate pick. Prepaid deliveries are free.", "Gain 3 of the kingdom’s wood equivalent. Repay 2 of its stone equivalent. Review materials at run start.", "Gain 2 of the kingdom’s stone equivalent. Repay 3 of its wood equivalent. Review materials at run start." };

	internal bool Valid
	{
		get
		{
			if (choice >= Charter.Merchant && choice <= Charter.Mason && debt >= 0 && debt <= Start(choice).debt)
			{
				return firstVisit >= 0;
			}
			return false;
		}
	}

	internal static CharterState Start(Charter choice)
	{
		return new CharterState
		{
			choice = choice,
			debt = choice switch
			{
				Charter.Mason => 3, 
				Charter.Forester => 2, 
				_ => 0, 
			}
		};
	}

	internal bool VisitToday(int day, bool vanilla, bool scheduledTomorrow)
	{
		if (firstVisit == 0)
		{
			return vanilla || scheduledTomorrow;
		}
		if (vanilla)
		{
			return day != firstVisit;
		}
		return false;
	}
}
internal sealed class CharterPicker : MonoBehaviour
{
	private readonly List<Button> buttons = new List<Button>();

	private TitleScreenHeroSelectionManager screen;

	private CanvasGroup underlying;

	private GameObject play;

	private GameObject root;

	private RectTransform panel;

	private RectTransform page;

	private TMP_FontAsset font;

	private Sprite buttonSkin;

	private CanvasScaler scaler;

	private Image backIcon;

	private RectTransform focusMarker;

	private TMP_Text backHint;

	private string scheme;

	private bool review;

	private bool interactable;

	private bool raycasts;

	private bool waitForRelease;

	private int selected;

	private int changedFrame = -1;

	private int backFrame = -1;

	private static readonly Color Ink = Color32.op_Implicit(new Color32((byte)26, (byte)32, (byte)36, byte.MaxValue));

	private static readonly Color Paper = Color32.op_Implicit(new Color32((byte)245, (byte)234, (byte)204, byte.MaxValue));

	internal bool IsOpen => (Object)(object)root != (Object)null;

	internal bool HandledBackThisFrame => backFrame == Time.frameCount;

	private static InputSystemUIInputModule Module
	{
		get
		{
			EventSystem current = EventSystem.current;
			BaseInputModule obj = ((current != null) ? current.currentInputModule : null);
			return (InputSystemUIInputModule)(object)((obj is InputSystemUIInputModule) ? obj : null);
		}
	}

	internal void Open(TitleScreenHeroSelectionManager owner, CanvasGroup group, GameObject opener)
	{
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Expected O, but got Unknown
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		screen = owner;
		underlying = group;
		play = opener;
		interactable = group.interactable;
		raycasts = group.blocksRaycasts;
		selected = 0;
		review = false;
		TMP_Text val = play.GetComponentInChildren<TMP_Text>(true) ?? ((Component)screen).GetComponentInChildren<TMP_Text>(true);
		font = (((Object)(object)val != (Object)null) ? val.font : TMP_Settings.defaultFontAsset);
		Button component = play.GetComponent<Button>();
		Graphic obj = ((component != null) ? ((Selectable)component).targetGraphic : null);
		Graphic obj2 = ((obj is Image) ? obj : null);
		buttonSkin = ((obj2 != null) ? ((Image)obj2).sprite : null);
		root = new GameObject("Kingdom Charters", new Type[4]
		{
			typeof(RectTransform),
			typeof(Canvas),
			typeof(CanvasScaler),
			typeof(GraphicRaycaster)
		});
		Canvas component2 = root.GetComponent<Canvas>();
		component2.renderMode = (RenderMode)0;
		component2.sortingOrder = 32000;
		scaler = root.GetComponent<CanvasScaler>();
		scaler.uiScaleMode = (ScaleMode)0;
		ScaleToScreen();
		RectTransform val2 = Box(root.transform, "Backdrop", new Color(0.03f, 0.04f, 0.05f, 0.69f));
		Stretch(val2);
		panel = Box((Transform)(object)val2, "Charter menu", Ink);
		panel.sizeDelta = new Vector2(852f, 644f);
		group.interactable = false;
		group.blocksRaycasts = false;
		Draw();
	}

	private void ScaleToScreen()
	{
		float num = (((Object)(object)SettingsManager.Instance != (Object)null) ? SettingsManager.Instance.GetUIScaling() : 1f);
		scaler.scaleFactor = Mathf.Min(new float[3]
		{
			Mathf.Max(num, 1f),
			(float)Screen.width / 876f,
			(float)Screen.height / 668f
		});
	}

	private void Draw()
	{
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		changedFrame = Time.frameCount;
		if ((Object)(object)page != (Object)null)
		{
			((Component)page).gameObject.SetActive(false);
			Object.Destroy((Object)(object)((Component)page).gameObject);
		}
		buttons.Clear();
		page = Child((Transform)(object)panel, "Choices");
		Stretch(page);
		Label((Transform)(object)page, review ? "Review Your Charter" : "Kingdom Charters", 30, 16, 780, 52, 36);
		if (review)
		{
			Label((Transform)(object)page, CharterState.Names[selected], 30, 111, 790, 64, 34);
			Label((Transform)(object)page, Terms(selected), 30, 185, 780, 132, 25);
			AddButton("Start Run", 365, 70, Commit);
			AddButton("Back to Charters", 450, 65, Back);
		}
		else
		{
			for (int i = 0; i < CharterState.Names.Length; i++)
			{
				int index = i;
				AddButton(CharterState.Names[i] + "\n" + Terms(i), 78 + i * 101, 92, delegate
				{
					Inspect(index);
				});
			}
			AddButton("Back to Hero Selection", 491, 55, Back);
		}
		WireNavigation();
		backIcon = Icon(34);
		backHint = Label((Transform)(object)page, "", 79, 570, 720, 47, 19);
		scheme = null;
		RefreshPrompts();
		focusMarker = Box((Transform)(object)page, "Focused choice", Color32.op_Implicit(new Color32(byte.MaxValue, (byte)208, (byte)83, byte.MaxValue)));
		((Graphic)((Component)focusMarker).GetComponent<Image>()).raycastTarget = false;
		Focus((!review) ? selected : 0);
	}

	private string Terms(int index)
	{
		if (index != 1)
		{
			return CharterState.Terms[index];
		}
		if (Plugin.DailyCaravan)
		{
			return "Unavailable while Daily Caravan sets the schedule.";
		}
		if (!Merchant.OtherSchedule)
		{
			return CharterState.Terms[index];
		}
		return "Another mod controls arrivals. Pay 1 extra coin per immediate pick. Prepaid deliveries are free.";
	}

	private void Inspect(int index)
	{
		if (Time.frameCount == changedFrame)
		{
			return;
		}
		selected = index;
		if (index == 1 && Plugin.DailyCaravan)
		{
			Focus(index);
			return;
		}
		review = true;
		InputSystemUIInputModule module = Module;
		int num;
		if (module == null)
		{
			num = 0;
		}
		else
		{
			InputActionReference submit = module.submit;
			bool? obj;
			if (submit == null)
			{
				obj = null;
			}
			else
			{
				InputAction action = submit.action;
				obj = ((action != null) ? new bool?(action.IsPressed()) : ((bool?)null));
			}
			bool? flag = obj;
			num = ((flag == true) ? 1 : 0);
		}
		waitForRelease = (byte)num != 0;
		Draw();
	}

	private void Commit()
	{
		if (review && !waitForRelease && changedFrame != Time.frameCount)
		{
			if (selected == 1 && Plugin.DailyCaravan)
			{
				Back();
				return;
			}
			TitleScreenHeroSelectionManager val = screen;
			Charter choice = (Charter)selected;
			Close();
			Plugin.Instance.StartRun(val, choice);
		}
	}

	internal void Back()
	{
		if (IsOpen && changedFrame != Time.frameCount && !HandledBackThisFrame)
		{
			backFrame = Time.frameCount;
			if (review)
			{
				review = false;
				Draw();
			}
			else
			{
				Close();
			}
		}
	}

	private void Close()
	{
		if ((Object)(object)underlying != (Object)null)
		{
			underlying.interactable = interactable;
			underlying.blocksRaycasts = raycasts;
		}
		root.SetActive(false);
		Object.Destroy((Object)(object)root);
		root = null;
		if ((Object)(object)play != (Object)null && (Object)(object)EventSystem.current != (Object)null)
		{
			GamepadManager.Instance.SetGameObjectToSelect(play, true);
			EventSystem.current.SetSelectedGameObject(play);
		}
	}

	private void OnDestroy()
	{
		if (IsOpen)
		{
			Close();
		}
	}

	private void LateUpdate()
	{
		if (!IsOpen)
		{
			return;
		}
		if ((Object)(object)screen == (Object)null)
		{
			Close();
			return;
		}
		ScaleToScreen();
		InputSystemUIInputModule module = Module;
		Keyboard current = Keyboard.current;
		if (waitForRelease)
		{
			if (module != null)
			{
				InputActionReference submit = module.submit;
				bool? obj;
				if (submit == null)
				{
					obj = null;
				}
				else
				{
					InputAction action = submit.action;
					obj = ((action != null) ? new bool?(action.IsPressed()) : ((bool?)null));
				}
				bool? flag = obj;
				if (flag == true)
				{
					goto IL_0085;
				}
			}
			waitForRelease = false;
		}
		goto IL_0085;
		IL_015d:
		if (current != null && ((ButtonControl)current.enterKey).wasPressedThisFrame)
		{
			if (module != null)
			{
				InputActionReference submit2 = module.submit;
				bool? obj2;
				if (submit2 == null)
				{
					obj2 = null;
				}
				else
				{
					InputAction action2 = submit2.action;
					obj2 = ((action2 != null) ? new bool?(action2.WasPerformedThisFrame()) : ((bool?)null));
				}
				bool? flag = obj2;
				if (flag == true)
				{
					goto IL_01d7;
				}
			}
			int num = FocusIndex();
			if (num >= 0)
			{
				((UnityEvent)buttons[num].onClick).Invoke();
			}
		}
		goto IL_01d7;
		IL_01d7:
		int num2 = FocusIndex();
		if (num2 < 0)
		{
			Focus((!review) ? selected : 0);
		}
		else
		{
			PlaceFocusMarker(num2);
			if (!review && num2 < CharterState.Names.Length)
			{
				selected = num2;
			}
			GamepadManager instance = GamepadManager.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.GetGameObjectToSelect() != (Object)(object)((Component)buttons[num2]).gameObject)
			{
				instance.SetGameObjectToSelect(((Component)buttons[num2]).gameObject, true);
			}
		}
		RefreshPrompts();
		return;
		IL_00e3:
		Back();
		return;
		IL_0085:
		if (changedFrame == Time.frameCount)
		{
			return;
		}
		if (module != null)
		{
			InputActionReference cancel = module.cancel;
			bool? obj3;
			if (cancel == null)
			{
				obj3 = null;
			}
			else
			{
				InputAction action3 = cancel.action;
				obj3 = ((action3 != null) ? new bool?(action3.WasPerformedThisFrame()) : ((bool?)null));
			}
			bool? flag = obj3;
			if (flag == true)
			{
				goto IL_00e3;
			}
		}
		if (current != null && ((ButtonControl)current.escapeKey).wasPressedThisFrame)
		{
			goto IL_00e3;
		}
		if (current != null)
		{
			if (module != null)
			{
				InputActionReference move = module.move;
				bool? obj4;
				if (move == null)
				{
					obj4 = null;
				}
				else
				{
					InputAction action4 = move.action;
					obj4 = ((action4 != null) ? new bool?(action4.WasPerformedThisFrame()) : ((bool?)null));
				}
				bool? flag = obj4;
				if (flag == true)
				{
					goto IL_015d;
				}
			}
			if (((ButtonControl)current.downArrowKey).wasPressedThisFrame)
			{
				Step(1);
			}
			else if (((ButtonControl)current.upArrowKey).wasPressedThisFrame)
			{
				Step(-1);
			}
		}
		goto IL_015d;
	}

	private void RefreshPrompts()
	{
		GamepadManager instance = GamepadManager.Instance;
		PlayerInput obj = ((instance != null) ? instance.GetPlayerInput() : null);
		string text = ((obj != null) ? obj.currentControlScheme : null) ?? "";
		if (!(scheme == text))
		{
			scheme = text;
			InputSystemUIInputModule module = Module;
			object action;
			if (module == null)
			{
				action = null;
			}
			else
			{
				InputActionReference cancel = module.cancel;
				action = ((cancel != null) ? cancel.action : null);
			}
			string text2 = Prompt((InputAction)action, text, backIcon, "Esc");
			backHint.text = text2 + "  Back";
		}
	}

	private static string Prompt(InputAction action, string group, Image image, string keyboardFallback)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: 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_0044: Unknown result type (might be due to invalid IL or missing references)
		((Behaviour)image).enabled = false;
		if (action == null || string.IsNullOrEmpty(group))
		{
			return keyboardFallback;
		}
		int bindingIndex = InputActionRebindingExtensions.GetBindingIndex(action, group, (string)null);
		if (bindingIndex < 0)
		{
			if (!GamepadManager.Instance.IsGamepadInUse())
			{
				return keyboardFallback;
			}
			return "";
		}
		InputBinding val = action.bindings[bindingIndex];
		string effectivePath = ((InputBinding)(ref val)).effectivePath;
		if (!string.IsNullOrEmpty(effectivePath))
		{
			image.sprite = GamepadManager.Instance.GetButtonPrompt(effectivePath, false);
			((Behaviour)image).enabled = (Object)(object)image.sprite != (Object)null;
		}
		return InputActionRebindingExtensions.GetBindingDisplayString(action, bindingIndex, (DisplayStringOptions)0);
	}

	private int FocusIndex()
	{
		EventSystem current = EventSystem.current;
		GameObject obj = ((current != null) ? current.currentSelectedGameObject : null);
		return buttons.FindIndex((Button b) => (Object)(object)((Component)b).gameObject == (Object)(object)obj);
	}

	private void Step(int delta)
	{
		Focus((Math.Max(0, FocusIndex()) + delta + buttons.Count) % buttons.Count);
	}

	private void Focus(int index)
	{
		PlaceFocusMarker(index);
		GameObject gameObject = ((Component)buttons[index]).gameObject;
		GamepadManager instance = GamepadManager.Instance;
		if (instance != null)
		{
			instance.SetGameObjectToSelect(gameObject, true);
		}
		EventSystem current = EventSystem.current;
		if (current != null)
		{
			current.SetSelectedGameObject(gameObject);
		}
	}

	private void PlaceFocusMarker(int index)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_002f: 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)
		if (!((Object)(object)focusMarker == (Object)null))
		{
			RectTransform val = (RectTransform)((Component)buttons[index]).transform;
			Position(focusMarker, 32, Mathf.RoundToInt(0f - val.anchoredPosition.y) + 12, 5, Mathf.RoundToInt(val.sizeDelta.y) - 24);
		}
	}

	private void WireNavigation()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < buttons.Count; i++)
		{
			Button obj = buttons[i];
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)4;
			((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)buttons[(i + buttons.Count - 1) % buttons.Count];
			((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)buttons[(i + 1) % buttons.Count];
			((Selectable)obj).navigation = navigation;
		}
	}

	private void AddButton(string caption, int y, int height, Action action)
	{
		//IL_001f: 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_005d: Expected O, but got Unknown
		//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_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: 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)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Expected O, but got Unknown
		RectTransform val = Box((Transform)(object)page, caption.Split('\n')[0], Color.white);
		Position(val, 28, y, 796, height);
		Button val2 = ((Component)val).gameObject.AddComponent<Button>();
		((Selectable)val2).targetGraphic = (Graphic)(object)((Component)val).GetComponent<Image>();
		Image val3 = (Image)((Selectable)val2).targetGraphic;
		if ((Object)(object)buttonSkin != (Object)null)
		{
			val3.sprite = buttonSkin;
			val3.type = (Type)1;
		}
		ColorBlock colors = ((Selectable)val2).colors;
		((ColorBlock)(ref colors)).normalColor = Color32.op_Implicit(new Color32((byte)182, (byte)196, (byte)207, byte.MaxValue));
		Color highlightedColor = (((ColorBlock)(ref colors)).selectedColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)190, (byte)77, byte.MaxValue)));
		((ColorBlock)(ref colors)).highlightedColor = highlightedColor;
		((ColorBlock)(ref colors)).pressedColor = Color32.op_Implicit(new Color32((byte)235, (byte)160, (byte)62, byte.MaxValue));
		((Selectable)val2).colors = colors;
		TMP_Text obj = Label((Transform)(object)val, caption, 20, 7, 752, height - 14, 23);
		((Graphic)obj).color = Color.white;
		obj.enableAutoSizing = true;
		obj.fontSizeMin = 17f;
		obj.fontSizeMax = 23f;
		((UnityEvent)val2.onClick).AddListener((UnityAction)delegate
		{
			action();
		});
		buttons.Add(val2);
	}

	private Image Icon(int x)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		RectTransform obj = Box((Transform)(object)page, "Input prompt", Color.white);
		Position(obj, x, 578, 32, 32);
		Image component = ((Component)obj).GetComponent<Image>();
		component.preserveAspect = true;
		((Graphic)component).raycastTarget = false;
		return component;
	}

	private TMP_Text Label(Transform parent, string value, int x, int y, int w, int h, int size)
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		RectTransform obj = Child(parent, "Label");
		Position(obj, x, y, w, h);
		TextMeshProUGUI obj2 = ((Component)obj).gameObject.AddComponent<TextMeshProUGUI>();
		((TMP_Text)obj2).text = value;
		((TMP_Text)obj2).font = font;
		((TMP_Text)obj2).fontSize = size;
		((Graphic)obj2).color = Paper;
		((TMP_Text)obj2).alignment = (TextAlignmentOptions)4097;
		((Graphic)obj2).raycastTarget = false;
		return (TMP_Text)(object)obj2;
	}

	private static RectTransform Box(Transform parent, string name, Color color)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		RectTransform obj = Child(parent, name);
		((Graphic)((Component)obj).gameObject.AddComponent<Image>()).color = color;
		return obj;
	}

	private static RectTransform Child(Transform parent, string name)
	{
		//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_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected O, but got Unknown
		RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
		((Transform)val).SetParent(parent, false);
		return val;
	}

	private static void Position(RectTransform rt, int x, int y, int w, int h)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//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_002e: 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)
		Vector2 val = default(Vector2);
		((Vector2)(ref val))..ctor(0f, 1f);
		rt.pivot = val;
		Vector2 anchorMin = (rt.anchorMax = val);
		rt.anchorMin = anchorMin;
		rt.anchoredPosition = new Vector2((float)x, (float)(-y));
		rt.sizeDelta = new Vector2((float)w, (float)h);
	}

	private static void Stretch(RectTransform rt)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: 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_001d: 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)
		rt.anchorMin = Vector2.zero;
		rt.anchorMax = Vector2.one;
		Vector2 offsetMin = (rt.offsetMax = Vector2.zero);
		rt.offsetMin = offsetMin;
	}
}
internal sealed class DebtHud : MonoBehaviour
{
	private GameObject root;

	private CanvasScaler scaler;

	private TextMeshProUGUI label;

	private int shownDebt;

	private int language;

	private void LateUpdate()
	{
		CharterState run = Plugin.Instance.Run;
		bool flag = run != null && run.debt > 0 && run.openingComplete && Supplies.HasMaterialPair && (Object)(object)GameManager.Instance != (Object)null && GameManager.Instance.IsGameLoaded() && (Object)(object)UIManager.Instance != (Object)null && !UIManager.Instance.IsHidden() && !UIManager.Instance.IsHiddenByUser() && (Object)(object)OverlayManager.Instance != (Object)null && !OverlayManager.Instance.IsOpen() && ((Object)(object)PauseMenuManger.Instance == (Object)null || !PauseMenuManger.Instance.InMenu());
		if ((Object)(object)root != (Object)null && root.activeSelf != flag)
		{
			root.SetActive(flag);
		}
		if (flag)
		{
			if ((Object)(object)root == (Object)null)
			{
				Create();
			}
			scaler.scaleFactor = SettingsManager.Instance.GetUIScaling();
			int num = SettingsManager.Instance.GetLanguage();
			if (shownDebt != run.debt || language != num)
			{
				shownDebt = run.debt;
				language = num;
				((TMP_Text)label).text = $"Charter Due: {run.debt} {Supplies.OwedName}";
			}
		}
	}

	private void Create()
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		//IL_0084: 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_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: 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_014c: Expected O, but got Unknown
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		root = new GameObject("Kingdom Charters debt", new Type[3]
		{
			typeof(RectTransform),
			typeof(Canvas),
			typeof(CanvasScaler)
		});
		root.GetComponent<Canvas>().renderMode = (RenderMode)0;
		scaler = root.GetComponent<CanvasScaler>();
		GameObject val = new GameObject("Balance", new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		});
		RectTransform val2 = (RectTransform)val.transform;
		((Transform)val2).SetParent(root.transform, false);
		Vector2 val3 = default(Vector2);
		((Vector2)(ref val3))..ctor(0.5f, 0f);
		val2.pivot = val3;
		Vector2 anchorMin = (val2.anchorMax = val3);
		val2.anchorMin = anchorMin;
		val2.anchoredPosition = new Vector2(0f, 9f);
		val2.sizeDelta = new Vector2(210f, 29f);
		Image component = val.GetComponent<Image>();
		((Graphic)component).color = Color32.op_Implicit(new Color32((byte)23, (byte)26, (byte)35, (byte)230));
		((Graphic)component).raycastTarget = false;
		GameObject val5 = new GameObject("Debt", new Type[2]
		{
			typeof(RectTransform),
			typeof(TextMeshProUGUI)
		});
		label = val5.GetComponent<TextMeshProUGUI>();
		RectTransform rectTransform = ((TMP_Text)label).rectTransform;
		((Transform)rectTransform).SetParent((Transform)(object)val2, false);
		rectTransform.anchorMin = Vector2.zero;
		rectTransform.anchorMax = Vector2.one;
		rectTransform.offsetMin = new Vector2(6f, 2f);
		rectTransform.offsetMax = new Vector2(-6f, -2f);
		TMP_Text componentInChildren = ((Component)UIManager.Instance).GetComponentInChildren<TMP_Text>(true);
		if ((Object)(object)componentInChildren != (Object)null)
		{
			((TMP_Text)label).font = componentInChildren.font;
		}
		((TMP_Text)label).fontSize = 21f;
		((TMP_Text)label).enableAutoSizing = true;
		((TMP_Text)label).fontSizeMin = 14f;
		((TMP_Text)label).fontSizeMax = 21f;
		((TMP_Text)label).alignment = (TextAlignmentOptions)514;
		((Graphic)label).color = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)241, (byte)212, byte.MaxValue));
		((Graphic)label).raycastTarget = false;
		shownDebt = -1;
	}

	private void OnDestroy()
	{
		if ((Object)(object)root != (Object)null)
		{
			Object.Destroy((Object)(object)root);
		}
	}
}
internal static class Merchant
{
	[HarmonyPatch(typeof(GuestCaravan), "CheckDay")]
	private static class Appointment
	{
		private static void Postfix(GuestCaravan __instance, int day, ref bool __result)
		{
			if (Plugin.Merchant && !OtherSchedule)
			{
				bool flag = Scheduled(day + 1, __instance);
				if (!__result && (Object)(object)arriving == (Object)null && flag && Plugin.Instance.Run.firstVisit == 0)
				{
					candidate = __instance;
				}
				__result = Plugin.Instance.Run.VisitToday(day, __result, flag && (Object)(object)arriving == (Object)(object)__instance);
			}
		}
	}

	[HarmonyPatch(typeof(GameManager), "ChangeState")]
	private static class FreeSlot
	{
		private static void Postfix(GameState newState)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)newState != 1)
			{
				return;
			}
			GuestCaravan candidate = Merchant.candidate;
			Merchant.candidate = null;
			if ((Object)(object)candidate == (Object)null || !Plugin.Merchant || Plugin.Instance.Run.firstVisit != 0 || (Object)(object)WorldManager.Instance.GetGuest() != (Object)null || WorldManager.Instance.HasGuestPlaceHolder() || !DaytimeManager.Instance.IsLoading() || !RaceDataManager.Instance.HasRaceEventFlag((RaceEvent)13))
			{
				return;
			}
			arriving = candidate;
			try
			{
				((Component)candidate).gameObject.SetActive(true);
				LoadCaravan(candidate, DaytimeManager.Instance.CurrentDay());
			}
			finally
			{
				arriving = null;
			}
		}
	}

	[HarmonyPatch(typeof(Guest), "CanSpeakToday")]
	private static class EarlyDialogue
	{
		private static void Postfix(Guest __instance, ref bool __result)
		{
			if (__instance is GuestCaravan && Plugin.Merchant && Plugin.Instance.Run.firstVisit == DaytimeManager.Instance.CurrentDay() + 1)
			{
				__result = true;
			}
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "OnLoad")]
	private static class Arrival
	{
		private static void Postfix(GuestCaravan __instance, int day)
		{
			if (Plugin.Merchant && Plugin.Instance.Run.firstVisit == 0 && !((Object)(object)WorldManager.Instance.GetGuest() != (Object)(object)__instance))
			{
				Plugin.Instance.Run.firstVisit = (((Object)(object)arriving == (Object)(object)__instance) ? (day + 1) : day);
			}
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "Reroll")]
	private static class Inventory
	{
		[HarmonyPriority(800)]
		[HarmonyBefore(new string[] { "gkj.sfk.caravancommissions" })]
		private static void Prefix(UIOverlayMerchant merchant, out UIOverlayMerchant __state)
		{
			__state = pricing;
			pricing = (Plugin.Merchant ? merchant : null);
		}

		private static void Finalizer(UIOverlayMerchant __state)
		{
			pricing = __state;
		}
	}

	private sealed class Offer
	{
		internal string Item;

		internal long CoinsRequired;

		internal bool Paid;

		internal bool CanSelect(int balance)
		{
			if (!Paid)
			{
				return balance >= CoinsRequired;
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(UIOverlayMerchant), "AddItem")]
	private static class Price
	{
		private static void Postfix(UIOverlayMerchant __instance, GameObject __result, ResourceAmount[] costs, Item item)
		{
			if (pricing != __instance || (Object)(object)__result == (Object)null)
			{
				return;
			}
			UICardItem component = __result.GetComponent<UICardItem>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			long? num = RegisterImmediatePick(__instance, component, item.GetIdentifier(), costs);
			if (num.HasValue)
			{
				TextMeshProUGUI val = Description.Invoke(component);
				if (!((Object)(object)val == (Object)null))
				{
					((TMP_Text)val).text = ((num == 1) ? "Merchant Charter: 1 coin" : $"Merchant Charter: +1 coin ({num} coins required)") + "\n" + ((TMP_Text)val).text;
				}
			}
		}
	}

	[HarmonyPatch(typeof(UIOverlayMerchant), "Select", new Type[] { typeof(UICard) })]
	private static class SelectCard
	{
		private static bool Prefix(UICard selected)
		{
			if (offers.TryGetValue(selected, out var value))
			{
				return value.CanSelect(ResourceManager.Instance.GetCoins());
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UICard), "Callback")]
	private static class Dispatch
	{
		private static bool Prefix(UICard __instance, out Offer __state)
		{
			__state = selecting;
			selecting = null;
			if (!offers.TryGetValue(__instance, out var value))
			{
				return true;
			}
			if (value.Paid || __state == value)
			{
				return false;
			}
			if (!value.CanSelect(ResourceManager.Instance.GetCoins()))
			{
				OverlayManager.Instance.CloseOverlay(false);
				return false;
			}
			selecting = value;
			return true;
		}

		private static void Finalizer(Offer __state)
		{
			selecting = __state;
		}
	}

	[HarmonyPatch(typeof(ItemManager), "SpawnDragItem")]
	private static class Delivered
	{
		[HarmonyPrepare]
		private static bool Prepare()
		{
			return !Plugin.DailyCaravan;
		}

		private static void Prefix(List<DragItem> ___m_DragItems, out int __state)
		{
			__state = ((selecting == null) ? (-1) : ___m_DragItems.Count);
		}

		private static void Postfix(string itemDataName, bool fromSave, List<DragItem> ___m_DragItems, int __state)
		{
			Offer selecting = Merchant.selecting;
			if (!(__state < 0 || selecting == null || selecting.Paid || fromSave) && !(selecting.Item != itemDataName) && ___m_DragItems.Count > __state)
			{
				selecting.Paid = true;
				ResourceManager.Instance.AddToCoins(-1);
				ResourceManager.Instance.ResourceAmountChanged((ResourceType)12);
			}
		}
	}

	private const int CaravanGuest = 80;

	private static readonly Func<GuestCaravan, int> ScheduledDay = AccessTools.MethodDelegate<Func<GuestCaravan, int>>(AccessTools.DeclaredMethod(typeof(GuestCaravan), "GetDay", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<GuestCaravan, int> LoadCaravan = AccessTools.MethodDelegate<Action<GuestCaravan, int>>(AccessTools.DeclaredMethod(typeof(GuestCaravan), "OnLoad", (Type[])null, (Type[])null), (object)null, true);

	private static GuestCaravan candidate;

	private static GuestCaravan arriving;

	private static readonly MethodInfo CheckDay = AccessTools.DeclaredMethod(typeof(GuestCaravan), "CheckDay", (Type[])null, (Type[])null);

	private static readonly MethodInfo OnLoad = AccessTools.DeclaredMethod(typeof(GuestCaravan), "OnLoad", (Type[])null, (Type[])null);

	private static readonly MethodInfo WeeklyGuest = AccessTools.DeclaredMethod(typeof(WorldManager), "IsTodayGuest", (Type[])null, (Type[])null);

	private static UIOverlayMerchant pricing;

	private static readonly ConditionalWeakTable<UICard, Offer> offers = new ConditionalWeakTable<UICard, Offer>();

	private static Offer selecting;

	private static readonly FieldRef<UICardItem, TextMeshProUGUI> Description = AccessTools.FieldRefAccess<UICardItem, TextMeshProUGUI>("description");

	private static readonly Func<UIOverlayMerchant, bool> UsesDefaultPick = AccessTools.MethodDelegate<Func<UIOverlayMerchant, bool>>(AccessTools.DeclaredMethod(typeof(UIOverlayMerchant), "UseCardSelectCallback", (Type[])null, (Type[])null), (object)null, true);

	internal static bool OtherSchedule
	{
		get
		{
			if (!CustomSchedule(CheckDay) && !CustomSchedule(OnLoad))
			{
				return CustomSchedule(WeeklyGuest);
			}
			return true;
		}
	}

	private static bool Scheduled(int day, GuestCaravan guest)
	{
		if (day == ScheduledDay(guest))
		{
			return true;
		}
		RaceDataManager instance = RaceDataManager.Instance;
		return day switch
		{
			7 => instance.GetGuestWeek1() == 80, 
			14 => instance.GetGuestWeek2() == 80, 
			21 => instance.GetGuestWeek3() == 80, 
			28 => instance.GetGuestWeek4() == 80, 
			_ => false, 
		};
	}

	private static bool CustomSchedule(MethodInfo method)
	{
		Patches patchInfo = Harmony.GetPatchInfo((MethodBase)method);
		if (patchInfo == null)
		{
			return false;
		}
		foreach (string owner in patchInfo.Owners)
		{
			if (owner != "gkj.sfk.kingdomcharters")
			{
				return true;
			}
		}
		return false;
	}

	private static long? RegisterImmediatePick(UIOverlayMerchant screen, UICardItem card, string id, ResourceAmount[] costs)
	{
		if (pricing != screen || !UsesDefaultPick(screen) || offers.TryGetValue((UICard)(object)card, out var _))
		{
			return null;
		}
		long num = RequiredCoins(costs);
		offers.Add((UICard)(object)card, new Offer
		{
			Item = id,
			CoinsRequired = num
		});
		return num;
	}

	internal static long RequiredCoins(ResourceAmount[] costs)
	{
		//IL_000e: 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_0014: 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_001c: Invalid comparison between Unknown and I4
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		long num = 1L;
		if (costs != null)
		{
			foreach (ResourceAmount val in costs)
			{
				if ((int)val.type == 12 && val.amount > 0)
				{
					num += val.amount;
				}
			}
		}
		return num;
	}
}
[BepInPlugin("gkj.sfk.kingdomcharters", "Kingdom Charters", "0.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string Id = "gkj.sfk.kingdomcharters";

	internal static Plugin Instance;

	internal CharterPicker Picker;

	internal Charter Pending;

	internal CharterState Run;

	internal string RunId;

	internal bool Starting;

	private Harmony patches;

	private static readonly FieldRef<TitleScreenHeroSelectionManager, bool> TransitionStarted = AccessTools.FieldRefAccess<TitleScreenHeroSelectionManager, bool>("m_StartedSceneTransition");

	internal static bool DailyCaravan => Chainloader.PluginInfos.ContainsKey("sfk.dailycaravan");

	internal static bool Merchant
	{
		get
		{
			CharterState run = Instance.Run;
			if (run != null && run.choice == Charter.Merchant && (Object)(object)MainManager.Instance != (Object)null && !MainManager.Instance.IsChallenge())
			{
				return !DailyCaravan;
			}
			return false;
		}
	}

	internal void UnsupportedMaterials()
	{
		((BaseUnityPlugin)this).Logger.LogWarning((object)"This kingdom has no distinct stored wood and stone equivalents. Supply charter suspended.");
	}

	private void Awake()
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		Instance = this;
		Picker = ((Component)this).gameObject.AddComponent<CharterPicker>();
		((Component)this).gameObject.AddComponent<DebtHud>();
		patches = new Harmony("gkj.sfk.kingdomcharters");
		try
		{
			patches.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Kingdom Charters ready.");
		}
		catch
		{
			patches.UnpatchSelf();
			throw;
		}
	}

	internal void StartRun(TitleScreenHeroSelectionManager screen, Charter choice)
	{
		Pending = choice;
		Starting = true;
		try
		{
			screen.Play();
		}
		catch
		{
			Pending = Charter.Standard;
			throw;
		}
		finally
		{
			Starting = false;
			if ((Object)(object)screen != (Object)null && !TransitionStarted.Invoke(screen))
			{
				Pending = Charter.Standard;
			}
		}
	}

	private void OnDestroy()
	{
		if ((Object)(object)Picker != (Object)null)
		{
			Object.Destroy((Object)(object)Picker);
		}
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		Instance = null;
	}
}
[HarmonyPatch(typeof(TitleScreenHeroSelectionManager), "Play")]
internal static class ChooseBeforePlay
{
	[HarmonyPriority(0)]
	private static bool Prefix(TitleScreenHeroSelectionManager __instance, bool __runOriginal, bool ___m_StartedSceneTransition, CanvasGroup ___totalCanvasGroup, GameObject ___playButton)
	{
		Plugin instance = Plugin.Instance;
		if (!__runOriginal || instance.Starting || ___m_StartedSceneTransition || MainManager.Instance.IsChallenge())
		{
			return true;
		}
		if (!instance.Picker.IsOpen)
		{
			instance.Picker.Open(__instance, ___totalCanvasGroup, ___playButton);
		}
		return false;
	}
}
[HarmonyPatch(typeof(TitleScreenHeroSelectionManager), "Back")]
internal static class ModalBack
{
	private static bool Prefix(ref bool __result)
	{
		CharterPicker picker = Plugin.Instance.Picker;
		if (!picker.IsOpen && !picker.HandledBackThisFrame)
		{
			return true;
		}
		picker.Back();
		__result = true;
		return false;
	}
}
[HarmonyPatch(typeof(TitleScreenHeroSelectionManager), "AddCurseButton")]
[HarmonyPatch(new Type[] { typeof(CallbackContext) })]
internal static class ModalCurseUp
{
	private static bool Prefix()
	{
		return !Plugin.Instance.Picker.IsOpen;
	}
}
[HarmonyPatch(typeof(TitleScreenHeroSelectionManager), "RemoveCurseButton")]
internal static class ModalCurseDown
{
	private static bool Prefix()
	{
		return !Plugin.Instance.Picker.IsOpen;
	}
}
internal static class SaveHooks
{
	[Serializable]
	private sealed class Snapshot
	{
		public string runID;

		public string hash;

		public CharterState kingdomChartersV1;
	}

	[HarmonyPatch(typeof(JsonUtility), "FromJson", new Type[]
	{
		typeof(string),
		typeof(Type)
	})]
	private static class Read
	{
		private static void Postfix(string __0, object __result)
		{
			GameData val = (GameData)((__result is GameData) ? __result : null);
			if (val == null || string.IsNullOrEmpty(__0) || !__0.Contains("\"kingdomChartersV1\""))
			{
				return;
			}
			try
			{
				Snapshot saved = JsonConvert.DeserializeObject<Snapshot>(__0);
				Snapshot snapshot = saved;
				if (snapshot != null && snapshot.kingdomChartersV1?.Valid == true && saved.runID == val.runID && saved.hash == val.hash)
				{
					Checkpoints.GetValue(val, (GameData _) => saved.kingdomChartersV1);
				}
			}
			catch (JsonException)
			{
			}
		}
	}

	[HarmonyPatch(typeof(GameManager), "ResetScene")]
	private static class Restart
	{
		private static void Postfix(bool __runOriginal)
		{
			Plugin instance = Plugin.Instance;
			if (__runOriginal && !MainManager.Instance.IsChallenge() && GameDataManager.Instance.IsFirstLoad())
			{
				instance.Pending = instance.Run?.choice ?? Charter.Standard;
			}
		}
	}

	[HarmonyPatch(typeof(MainManager), "LoadTitleScene")]
	private static class LeaveRun
	{
		private static void Postfix()
		{
			Plugin.Instance.Pending = Charter.Standard;
		}
	}

	[HarmonyPatch(typeof(GameDataManager), "Load")]
	private static class LoadRun
	{
		private static void Prefix(GameData ___m_GameData, out CharterState __state)
		{
			__state = Restore(___m_GameData);
			Plugin.Instance.Run = null;
			Plugin.Instance.RunId = null;
		}

		private static void Postfix(GameDataManager __instance, CharterState __state)
		{
			Plugin instance = Plugin.Instance;
			Charter pending = instance.Pending;
			instance.Pending = Charter.Standard;
			if (!MainManager.Instance.IsChallenge())
			{
				instance.RunId = __instance.GetRunID();
				if (__instance.IsFirstLoad())
				{
					instance.Run = ((pending == Charter.Standard) ? null : CharterState.Start(pending));
				}
				else
				{
					instance.Run = __state;
				}
				Supplies.BindRun();
			}
		}
	}

	[HarmonyPatch(typeof(TavernSaveManager), "Load")]
	private static class TavernLoad
	{
		private static void Postfix(TavernSaveManager __instance)
		{
			GameData gameData = __instance.GetGameData();
			Plugin.Instance.RunId = gameData?.runID;
			Plugin.Instance.Run = (MainManager.Instance.IsChallenge() ? null : Restore(gameData));
		}
	}

	[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	private static class Write
	{
		private static void Prefix(string file, ref string jsonString)
		{
			Plugin instance = Plugin.Instance;
			if (instance.Run != null && !string.IsNullOrEmpty(instance.RunId) && IsNormalSave(file) && !string.IsNullOrEmpty(jsonString) && !(JsonUtility.FromJson<Snapshot>(jsonString).runID != instance.RunId))
			{
				int num = jsonString.LastIndexOf('}');
				if (num >= 0)
				{
					jsonString = jsonString.Insert(num, ",\"kingdomChartersV1\":" + JsonUtility.ToJson((object)instance.Run));
				}
			}
		}
	}

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

	private static bool IsNormalSave(string name)
	{
		if (name != null && name.EndsWith("_game", StringComparison.Ordinal))
		{
			return !name.EndsWith("_challenge_game", StringComparison.Ordinal);
		}
		return false;
	}

	private static CharterState Restore(GameData data)
	{
		if (data == null || !Checkpoints.TryGetValue(data, out var value))
		{
			return null;
		}
		return value;
	}
}
internal static class Supplies
{
	[HarmonyPatch(typeof(DialogueCollection), "Trigger")]
	private static class ReviewMaterials
	{
		private static void Prefix(ref Action<bool> callback)
		{
			CharterState run = Plugin.Instance.Run;
			if (run == null || run.openingComplete || run.choice == Charter.Merchant || !(callback?.Target is King) || callback.Method.Name != "AfterDialogue")
			{
				return;
			}
			Action<bool> next = callback;
			callback = delegate(bool accepted)
			{
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b7: 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_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Expected O, but got Unknown
				OverlayManager overlay = OverlayManager.Instance;
				UIOverlayMessage val = overlay.OverlayMessage(false);
				bool answered = false;
				val.SetMessage(CharterState.Names[(int)run.choice] + "\n" + MaterialTerms(run.choice));
				if (HasMaterialPair)
				{
					val.SetCancel("Standard Run", (UnityAction)delegate
					{
						Continue(apply: false);
					});
					val.SetAccept("Accept Charter", (UnityAction)delegate
					{
						Continue(apply: true);
					});
				}
				else
				{
					val.RemoveCancel();
					val.SetAccept("Standard Run", (UnityAction)delegate
					{
						Continue(apply: false);
					});
				}
				void Continue(bool apply)
				{
					if (!answered)
					{
						answered = true;
						if (!apply)
						{
							Plugin.Instance.Run = null;
							BindRun();
						}
						overlay.Confirm();
						next(accepted);
					}
				}
			};
		}
	}

	[HarmonyPatch(typeof(ResourceManager), "GiveStartingResources")]
	private static class Opening
	{
		[HarmonyPriority(800)]
		private static void Prefix(out bool __state)
		{
			__state = opening;
			opening = true;
		}

		private static void Finalizer(ResourceManager __instance, bool __state, Exception __exception)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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)
			try
			{
				CharterState run = Plugin.Instance.Run;
				if (__state || __exception != null || !HasMaterialPair || run == null)
				{
					return;
				}
				if (!run.openingComplete)
				{
					run.openingComplete = true;
					int num = ((run.choice == Charter.Forester) ? 3 : 2);
					BuildingCity val = Store(gift);
					if ((Object)(object)val != (Object)null)
					{
						((Building)val).GenerateResources(gift, num, false);
					}
					else
					{
						__instance.RegisterStartingResource(new ResourceAmount(gift, num));
						__instance.ResourceAmountChanged(gift);
					}
				}
				ResetBalance();
			}
			finally
			{
				opening = __state;
			}
		}
	}

	[HarmonyPatch]
	private static class OpeningScope
	{
		private static MethodBase[] TargetMethods()
		{
			return new MethodInfo[3]
			{
				AccessTools.Method(typeof(UIOverlayStarterResources), "StartGame", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(King), "AfterDialogue", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(ResourceManager), "GiveStartingFood", (Type[])null, (Type[])null)
			};
		}

		[HarmonyPriority(800)]
		private static void Prefix()
		{
			openingScopes++;
		}

		private static void Finalizer()
		{
			if (--openingScopes == 0 && !opening)
			{
				CharterState run = Plugin.Instance.Run;
				if (run != null && run.debt > 0)
				{
					ResetBalance();
				}
			}
		}
	}

	[HarmonyPatch(typeof(ResourceManager), "ResourceAmountChanged")]
	private static class Collect
	{
		private static void Prefix(ResourceManager __instance, ResourceType type)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			CharterState run = Plugin.Instance.Run;
			if (openingScopes != 0 || opening || collecting || run == null || run.debt == 0 || !run.openingComplete || !HasMaterialPair || type != owed || (Object)(object)GameManager.Instance == (Object)null || !GameManager.Instance.IsGameLoaded())
			{
				return;
			}
			BuildingCity val = Store(type);
			int num = Stock(__instance, val, type);
			int num2 = Math.Min(run.debt, num - balance);
			balance = num;
			if (num2 <= 0)
			{
				return;
			}
			collecting = true;
			try
			{
				if ((Object)(object)val == (Object)null)
				{
					__instance.GetStartingResourcesDictionary()[type] = num - num2;
				}
				else
				{
					TakeFromStorage(((Building)val).GetStorage(), type, num2);
				}
				balance = Stock(__instance, val, type);
				run.debt -= Math.Min(num2, Math.Max(0, num - balance));
			}
			finally
			{
				collecting = false;
			}
		}
	}

	private static int balance;

	private static bool collecting;

	private static bool opening;

	private static int openingScopes;

	private static ResourceType gift;

	private static ResourceType owed;

	private static readonly FieldRef<ResourcePacket, int> PacketAmount = AccessTools.FieldRefAccess<ResourcePacket, int>("m_Amount");

	internal static string OwedName => MaterialName((ResourceType)((Plugin.Instance.Run.choice == Charter.Forester) ? 4 : 2));

	internal static bool HasMaterialPair => (int)owed > 0;

	private static string MaterialName(ResourceType slot)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		ResourceData resourceData = RaceManager.Instance.GetResourceData(slot);
		if (resourceData.stringTitle != null)
		{
			return resourceData.GetName();
		}
		return ((object)Unsafe.As<ResourceType, ResourceType>(ref resourceData.type)/*cast due to .constrained prefix*/).ToString();
	}

	internal static void BindRun()
	{
		//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_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: 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_005b: 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_005f: 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_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Invalid comparison between Unknown and I4
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Invalid comparison between Unknown and I4
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: 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)
		//IL_00aa: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
		CharterState run = Plugin.Instance.Run;
		owed = (ResourceType)0;
		gift = (ResourceType)0;
		if (run != null && (run.choice == Charter.Forester || run.choice == Charter.Mason))
		{
			RaceManager instance = RaceManager.Instance;
			ResourceData resourceData = instance.GetResourceData((ResourceType)2);
			ResourceType val = (ResourceType)((resourceData != null) ? ((int)resourceData.type) : 0);
			ResourceData resourceData2 = instance.GetResourceData((ResourceType)4);
			ResourceType val2 = (ResourceType)((resourceData2 != null) ? ((int)resourceData2.type) : 0);
			if (val == val2 || (int)val == 0 || (int)val2 == 0 || (int)instance.GetBuildingTypeToTakeFrom(val) == 666 || (int)instance.GetBuildingTypeToTakeFrom(val2) == 666)
			{
				Plugin.Instance.UnsupportedMaterials();
				return;
			}
			gift = ((run.choice == Charter.Forester) ? val : val2);
			owed = ((run.choice == Charter.Forester) ? val2 : val);
			ResetBalance();
		}
	}

	internal static string MaterialTerms(Charter choice)
	{
		if (!HasMaterialPair)
		{
			return "This kingdom needs two distinct stored materials for a supply charter. Continue with Standard Run.";
		}
		string text = MaterialName((ResourceType)2);
		string text2 = MaterialName((ResourceType)4);
		if (choice != Charter.Forester)
		{
			return "Gain 2 " + text2 + ". Repay 3 " + text + " from later deliveries.";
		}
		return "Gain 3 " + text + ". Repay 2 " + text2 + " from later deliveries.";
	}

	private static BuildingCity Store(ResourceType type)
	{
		//IL_000a: 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)
		return CityManager.Instance.GetBuilding(RaceManager.Instance.GetBuildingTypeToTakeFrom(type));
	}

	private static int Stock(ResourceManager resources, BuildingCity store, ResourceType type)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)store != (Object)null)
		{
			return ((Building)store).GetResourceQuantity(type, false);
		}
		if (!resources.GetStartingResourcesDictionary().TryGetValue(type, out var value))
		{
			return 0;
		}
		return value;
	}

	private static void ResetBalance()
	{
		//IL_000c: 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)
		if (HasMaterialPair)
		{
			balance = Stock(ResourceManager.Instance, Store(owed), owed);
		}
	}

	private static void TakeFromStorage(ResourceStorage storage, ResourceType type, int payment)
	{
		//IL_0009: 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_005d: Unknown result type (might be due to invalid IL or missing references)
		if (!storage.ShouldGenerateResourcePackets())
		{
			storage.RemoveResourceWithoutPackage(type, payment);
			return;
		}
		while (payment > 0)
		{
			ResourcePacket val = storage.FindFreeResourcePacket(type);
			if (val == null || val.GetAmount() <= 0)
			{
				break;
			}
			int num = Math.Min(val.GetAmount(), payment);
			if (num == val.GetAmount())
			{
				storage.TakeResourcePacket(val.GetIdentifier(), false);
			}
			else
			{
				PacketAmount.Invoke(val) -= num;
				storage.RemoveResourceWithoutPackage(type, num);
			}
			payment -= num;
		}
	}
}