Decompiled source of CaravanCommissions v0.1.0

plugins/CaravanCommissions.dll

Decompiled 36 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Tavern;
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("CaravanCommissions")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+c93217295b914da0643abaddeaa612627d96519d")]
[assembly: AssemblyProduct("CaravanCommissions")]
[assembly: AssemblyTitle("CaravanCommissions")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace CaravanCommissions;

internal sealed class Pool
{
	internal string Title;

	internal string[] Ids;

	internal Item[] Items;

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

	private static readonly FieldRef<GuestCaravan, Races> Kingdom = AccessTools.FieldRefAccess<GuestCaravan, Races>("m_Kingdom");

	internal static string Identify(string key)
	{
		Item item = AddressablesManager.Instance.GetItem(key);
		if (item == null)
		{
			return null;
		}
		return item.GetIdentifier();
	}

	internal static List<string> Stock(GuestCaravan guest)
	{
		return (List<string>)GetItems.Invoke(guest, null);
	}

	internal static List<Pool> Eligible(GuestCaravan guest)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Expected I4, but got Unknown
		//IL_0033: 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_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Invalid comparison between Unknown and I4
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected I4, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		List<Pool> list = new List<Pool>();
		Races val = Kingdom.Invoke(guest);
		try
		{
			foreach (Races value in Enum.GetValues(typeof(Races)))
			{
				if ((int)value == 11 || value == RaceManager.Instance.GetRace())
				{
					continue;
				}
				Kingdom.Invoke(guest) = (Races)(int)value;
				string[][] array = OfferIds.Pages(OfferIds.FromPool(Stock(guest), Identify)).ToArray();
				for (int i = 0; i < array.Length; i++)
				{
					string text = Helper.Instance.GetKingdomTitle(value);
					if (array.Length > 1)
					{
						text += $" ({i + 1}/{array.Length})";
					}
					list.Add(new Pool
					{
						Title = text,
						Ids = array[i],
						Items = ((IEnumerable<string>)array[i]).Select((Func<string, Item>)AddressablesManager.Instance.GetItem).ToArray()
					});
				}
			}
			return list;
		}
		finally
		{
			Kingdom.Invoke(guest) = (Races)(int)val;
		}
	}
}
internal static class DeliveryCards
{
	private static readonly FieldRef<UIOverlayMerchant, GameObject> Prefab = AccessTools.FieldRefAccess<UIOverlayMerchant, GameObject>("itemCard");

	private static readonly FieldRef<UIOverlayMerchant, UIEffectKeywordDictionary> Keywords = AccessTools.FieldRefAccess<UIOverlayMerchant, UIEffectKeywordDictionary>("keywordDictionary");

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

	private static readonly MethodInfo Select = AccessTools.DeclaredMethod(typeof(UIOverlayMerchant), "Select", new Type[1] { typeof(UICard) }, (Type[])null);

	internal static GameObject ItemCardPrefab(UIOverlayMerchant screen)
	{
		return Prefab.Invoke(screen);
	}

	private static bool Grant(string id)
	{
		ItemManager manager = ItemManager.Instance;
		return ObserveSpawn(manager, id, delegate(string key)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			manager.SpawnDragItem(key, new Vector2(0f, 3f), false);
		});
	}

	internal static bool ObserveSpawn(ItemManager manager, string id, Action<string> spawn)
	{
		DragItem[] before = manager.GetDragItems().ToArray();
		try
		{
			spawn(id);
		}
		catch (Exception ex)
		{
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("Commission spawn hook failed: " + ex.Message));
			}
		}
		return manager.GetDragItems().Any((DragItem drop) => drop != null && drop.GetItemIdentifier() == id && !before.Any((DragItem previous) => previous == drop));
	}

	internal static void Show(UIOverlayMerchant screen, Plugin.Visit visit)
	{
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Expected O, but got Unknown
		string[] promised = Plugin.Book.items;
		string[] array = promised;
		foreach (string id in array)
		{
			if (!OfferIds.Available(id, Pool.Identify))
			{
				continue;
			}
			Transform val = (Transform)GetSelection.Invoke(screen, null);
			UICardItem card = Object.Instantiate<GameObject>(Prefab.Invoke(screen), val).GetComponent<UICardItem>();
			card.Init(AddressablesManager.Instance.GetItem(id), Keywords.Invoke(screen), true, (UnityAction)delegate
			{
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				if (visit.Available && Plugin.Book.items == promised && !((Object)(object)Plugin.Panel != (Object)null) && Plugin.IsCurrent(screen) && Plugin.Owns(screen, visit))
				{
					if (!Plugin.Book.Claim(visit.Day, visit.Number, promised, id, Pool.Identify, Grant))
					{
						OverlayManager.Instance.Cancel(true);
					}
					else
					{
						OverlayManager.Instance.Confirm();
						GameCamera.Instance.StartCutscene(Vector2.op_Implicit(Vector2.zero), 0f, (Action<bool>)GameCamera.Instance.EndCutscene, true, true);
					}
				}
			}, false, true);
			Button cardButton = ((UICard)card).GetCardButton();
			((UnityEvent)cardButton.onClick).AddListener((UnityAction)delegate
			{
				Select.Invoke(screen, new object[1] { card });
			});
			GamepadManager.Instance.SetGameObjectToSelect(((Component)cardButton).gameObject, false);
		}
	}
}
internal sealed class CommissionPanel : MonoBehaviour
{
	private const int Price = 3;

	private string[] expectedOrder;

	private static readonly FieldRef<UICardItem, string> CardId = AccessTools.FieldRefAccess<UICardItem, string>("m_ItemIdentifier");

	private string[] todayPrices;

	private BuildingType source;

	private UIOverlayMerchant merchant;

	private Plugin.Visit visit;

	private List<Pool> pools;

	private Item[] today;

	private ResourceData material;

	private ResourceType materialType;

	private TMP_Text sample;

	private CanvasGroup native;

	private bool oldInteractable;

	private bool oldRaycasts;

	private bool addedGroup;

	private readonly List<(CanvasGroup group, float alpha, bool added)> hidden = new List<(CanvasGroup, float, bool)>();

	private Button nativeButton;

	private Sprite cardFrame;

	private Sprite cardBanner;

	private static readonly Vector2 DeskSize = new Vector2(1280f, 720f);

	internal static int LastBackFrame = -1;

	private RectTransform page;

	private readonly List<Button> buttons = new List<Button>();

	private int index;

	private int enteredFrame;

	private bool reviewing;

	private TMP_Text backPrompt;

	private Image backIcon;

	private string activeScheme;

	private static readonly Color Ink = new Color(0.075f, 0.105f, 0.13f);

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

	private bool Exchange => expectedOrder != null;

	internal bool OwnsCurrentScreen => Plugin.IsCurrent(merchant);

	internal static void Open(UIOverlayMerchant merchant, Plugin.Visit visit)
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		CommissionPanel commissionPanel = new GameObject("Caravan Commissions", new Type[4]
		{
			typeof(RectTransform),
			typeof(Canvas),
			typeof(CanvasScaler),
			typeof(GraphicRaycaster)
		}).AddComponent<CommissionPanel>();
		try
		{
			Plugin.Panel = commissionPanel;
			commissionPanel.Initialize(merchant, visit);
		}
		catch
		{
			commissionPanel.Dismiss();
			throw;
		}
	}

	private unsafe void Initialize(UIOverlayMerchant screen, Plugin.Visit current)
	{
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0225: Expected O, but got Unknown
		merchant = screen;
		visit = current;
		pools = Pool.Eligible(visit.Guest);
		expectedOrder = (Plugin.Book.Pending ? Plugin.Book.items : null);
		UICardItem[] array = (from c in ((Component)screen).GetComponentsInChildren<UICardItem>()
			where OfferIds.Available(CardId.Invoke(c), Pool.Identify)
			select c).Take(3).ToArray();
		today = array.Select((UICardItem c) => AddressablesManager.Instance.GetItem(CardId.Invoke(c))).ToArray();
		todayPrices = array.Select((UICardItem c) => (!Plugin.CardPrices.TryGetValue(c, out var value)) ? "" : string.Join(" + ", value.Select(delegate(ResourceAmount cost)
		{
			//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)
			string text = cost.amount.ToString();
			ResourceData resourceData = RaceManager.Instance.GetResourceData(cost.type);
			return text + " " + (((resourceData != null) ? resourceData.GetName() : null) ?? ((object)(*(ResourceType*)(&cost.type))/*cast due to .constrained prefix*/).ToString());
		}))).ToArray();
		RefreshMaterial();
		sample = ((Component)merchant).GetComponentInChildren<TMP_Text>(true);
		Canvas component = ((Component)this).GetComponent<Canvas>();
		component.renderMode = (RenderMode)0;
		component.sortingOrder = 32766;
		Transform obj = ((Component)screen).transform.Find("Panel/Buttons/Minimize/Button");
		nativeButton = ((obj != null) ? ((Component)obj).GetComponent<Button>() : null);
		UICardItem? obj2 = array.FirstOrDefault();
		GameObject val = ((obj2 != null) ? ((Component)obj2).gameObject : null) ?? DeliveryCards.ItemCardPrefab(screen);
		Image[] array2 = (((Object)(object)val == (Object)null) ? Array.Empty<Image>() : val.GetComponentsInChildren<Image>(true));
		Image? obj3 = ((IEnumerable<Image>)array2).FirstOrDefault((Func<Image, bool>)((Image image) => ((Object)image).name == "Card" && (Object)(object)image.sprite != (Object)null));
		cardFrame = ((obj3 != null) ? obj3.sprite : null);
		Image? obj4 = ((IEnumerable<Image>)array2).FirstOrDefault((Func<Image, bool>)((Image image) => ((Object)image).name == "Banner" && (Object)(object)image.sprite != (Object)null));
		cardBanner = ((obj4 != null) ? obj4.sprite : null);
		((Graphic)((Component)Box("Input shield", ((Component)this).transform, 0f, 0f, 1f, 1f)).gameObject.AddComponent<Image>()).color = Color.clear;
		foreach (Transform item in ((Component)merchant).transform)
		{
			Transform val2 = item;
			if (!(((Object)val2).name == "Image"))
			{
				CanvasGroup val3 = ((Component)val2).GetComponent<CanvasGroup>();
				bool flag = (Object)(object)val3 == (Object)null;
				if (flag)
				{
					val3 = ((Component)val2).gameObject.AddComponent<CanvasGroup>();
				}
				hidden.Add((val3, val3.alpha, flag));
				val3.alpha = 0f;
			}
		}
		native = ((Component)merchant).GetComponent<CanvasGroup>();
		addedGroup = (Object)(object)native == (Object)null;
		if (addedGroup)
		{
			native = ((Component)merchant).gameObject.AddComponent<CanvasGroup>();
		}
		oldInteractable = native.interactable;
		oldRaycasts = native.blocksRaycasts;
		CanvasGroup obj5 = native;
		bool interactable = (native.blocksRaycasts = false);
		obj5.interactable = interactable;
		Render(0);
	}

	private void LateUpdate()
	{
		if (!OwnsCurrentScreen || !visit.Available)
		{
			Dismiss();
			return;
		}
		FitDesk();
		EventSystem current = EventSystem.current;
		GameObject val = ((current != null) ? current.currentSelectedGameObject : null);
		if ((Object)(object)val != (Object)null && val.transform.IsChildOf(((Component)this).transform) && (Object)(object)GamepadManager.Instance.GetGameObjectToSelect() != (Object)(object)val)
		{
			GamepadManager.Instance.SetGameObjectToSelect(val, true);
		}
		string currentControlScheme = GamepadManager.Instance.GetCurrentControlScheme();
		if (activeScheme != currentControlScheme)
		{
			RefreshPrompts(currentControlScheme);
		}
	}

	private static RectTransform Box(string name, Transform parent, float left, float bottom, float right, float top)
	{
		//IL_0014: 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_0038: 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_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
		((Transform)component).SetParent(parent, false);
		component.anchorMin = new Vector2(left, bottom);
		component.anchorMax = new Vector2(right, top);
		Vector2 offsetMin = (component.offsetMax = Vector2.zero);
		component.offsetMin = offsetMin;
		return component;
	}

	private void FitDesk()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: 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_0019: 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_002b: 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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		Rect rect = ((RectTransform)((Component)this).transform).rect;
		Vector2 size = ((Rect)(ref rect)).size;
		float num = Mathf.Min(size.x / DeskSize.x, size.y / DeskSize.y);
		float uIScaling = SettingsManager.Instance.GetUIScaling();
		float num2 = Mathf.Min(88f * uIScaling, size.y * 0.18f);
		float num3 = Mathf.Min(56f, size.y * 0.09f);
		float num4 = (size.y - num2 - num3) / DeskSize.y;
		((Transform)page).localScale = Vector3.one * Mathf.Min(new float[3]
		{
			num * 0.7f * uIScaling,
			num4,
			num * 0.96f
		});
		page.anchoredPosition = new Vector2(0f, (num3 - num2) * 0.5f);
	}

	private static Image Surface(RectTransform rect, Sprite sprite, Color color)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		Image val = ((Component)rect).gameObject.AddComponent<Image>();
		val.sprite = sprite;
		if ((Object)(object)sprite != (Object)null)
		{
			val.type = (Type)1;
		}
		((Graphic)val).color = color;
		return val;
	}

	private TMP_Text Label(string name, RectTransform parent, string value, float left, float bottom, float right, float top, int maxSize, TextAlignmentOptions alignment = (TextAlignmentOptions)513)
	{
		//IL_0066: 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)
		TextMeshProUGUI val = ((Component)Box(name, (Transform)(object)parent, left, bottom, right, top)).gameObject.AddComponent<TextMeshProUGUI>();
		if ((Object)(object)sample != (Object)null)
		{
			((TMP_Text)val).font = sample.font;
			((TMP_Text)val).spriteAsset = sample.spriteAsset;
		}
		((TMP_Text)val).enableAutoSizing = true;
		((TMP_Text)val).fontSizeMin = 12f;
		((TMP_Text)val).fontSizeMax = maxSize;
		((TMP_Text)val).alignment = alignment;
		((Graphic)val).raycastTarget = false;
		((Graphic)val).color = Ink;
		((TMP_Text)val).text = value;
		return (TMP_Text)(object)val;
	}

	private void Column(string title, Item[] items, float left, float right, string[] prices = null)
	{
		//IL_003a: 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_009d: 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)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		RectTransform val = Box("Offer card", (Transform)(object)page, left, 0.234f, right, 0.773f);
		Surface(val, cardFrame, ((Object)(object)cardFrame != (Object)null) ? Color.white : Paper).pixelsPerUnitMultiplier = 4f;
		RectTransform val2 = Box("Banner", (Transform)(object)val, 0.008f, 0.773f, 0.992f, 0.974f);
		Surface(val2, cardBanner, ((Object)(object)cardBanner != (Object)null) ? Color.white : Color32.op_Implicit(new Color32((byte)132, (byte)57, (byte)49, byte.MaxValue))).pixelsPerUnitMultiplier = 4f;
		((Graphic)Label("Pool", val2, title, 0.05f, 0.14f, 0.95f, 0.9f, 30, (TextAlignmentOptions)514)).color = Color.white;
		for (int i = 0; i < items.Length; i++)
		{
			float num = 0.77f - (float)i * 0.227f;
			Item val3 = items[i];
			if (!((Object)(object)val3 == (Object)null))
			{
				Image obj = ((Component)Box("Item icon", (Transform)(object)val, 0.062f, num - 0.175f, 0.155f, num - 0.01f)).gameObject.AddComponent<Image>();
				obj.sprite = val3.GetIcon();
				obj.preserveAspect = true;
				((Graphic)obj).raycastTarget = false;
				Label("Item", val, "<b>" + val3.GetTitle() + "</b>" + ((prices != null && prices[i].Length > 0) ? (" (" + prices[i] + ")") : "") + "\n" + val3.GetDescription(), 0.18f, num - 0.215f, 0.944f, num, 23, (TextAlignmentOptions)513);
			}
		}
	}

	private void Render(int focus)
	{
		//IL_006a: 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_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_047c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)page != (Object)null)
		{
			((Component)page).gameObject.SetActive(false);
			Object.Destroy((Object)(object)((Component)page).gameObject);
		}
		buttons.Clear();
		page = Box("Order desk", ((Component)this).transform, 0.5f, 0.5f, 0.5f, 0.5f);
		page.sizeDelta = DeskSize;
		FitDesk();
		enteredFrame = Time.frameCount;
		Pool pool = ((pools.Count == 0) ? null : pools[index]);
		int num = Spendable();
		string text = (((Object)(object)material == (Object)null) ? "material" : material.GetName());
		string text2 = $"Cost: {3} {text}     Available: {num} {text}";
		if (Exchange)
		{
			text2 = "This order is paid. No additional materials are needed.";
		}
		else if (num < 3)
		{
			text2 += $"     Short by {3 - num}";
		}
		((Graphic)Label("Heading", page, reviewing ? "Confirm Commission" : "Caravan Commissions", 0.06f, 0.875f, 0.94f, 0.98f, 42, (TextAlignmentOptions)514)).color = Color.white;
		string value = (Exchange ? "A promised item is unavailable. Keep your order, or exchange it for a future visit." : "Take one item today, or pay for a choice at the next caravan visit.");
		if (reviewing)
		{
			value = ((!Exchange) ? $"Spend {3} {text} and give up today's item for {pool.Title}?" : ((pool == null) ? "Close this order without an item or a refund?" : ("Replace your paid order with " + pool.Title + " for the next visit at no extra cost?")));
		}
		((Graphic)Label("Terms", page, value, 0.04f, 0.79f, 0.96f, 0.875f, 26, (TextAlignmentOptions)514)).color = Color.white;
		Column(Exchange ? "Remaining Paid Choices" : "Today's Items", today, 0.028f, 0.484f, todayPrices);
		Column((pool == null) ? "No Eligible Pool" : (pool.Title + " (Next Visit)"), pool?.Items ?? Array.Empty<Item>(), 0.516f, 0.972f);
		((Graphic)Label("Cost", page, text2, 0.04f, 0.158f, 0.96f, 0.229f, 27, (TextAlignmentOptions)514)).color = Color.white;
		if (reviewing)
		{
			AddButton("Back to Pool", 0.16f, 0.47f, delegate
			{
				reviewing = false;
				Render(2);
			});
			AddButton((!Exchange) ? "Pay and Commission" : ((pool == null) ? "Close Paid Order" : "Exchange for Free"), 0.53f, 0.84f, Pay, Exchange || num >= 3);
		}
		else
		{
			AddButton("Previous Pool", 0.028f, 0.202f, delegate
			{
				Cycle(-1);
			}, pools.Count > 1);
			AddButton("Next Pool", 0.218f, 0.388f, delegate
			{
				Cycle(1);
			}, pools.Count > 1);
			AddButton((Exchange && pool == null) ? "Close Paid Order" : "Review Order", 0.404f, 0.592f, delegate
			{
				reviewing = true;
				Render(0);
			}, Exchange || (pool != null && num >= 3));
			AddButton(Exchange ? "Back to Delivery" : "Today's Items", 0.608f, 0.785f, Dismiss);
			AddButton("Leave Caravan", 0.801f, 0.972f, Leave);
		}
		WireNavigation(focus);
		backIcon = PromptIcon(0.447f);
		backPrompt = Label("Back prompt", page, "", 0.487f, -0.02f, 0.72f, 0.045f, 20, (TextAlignmentOptions)513);
		((Graphic)backPrompt).color = Color.white;
		RefreshPrompts(GamepadManager.Instance.GetCurrentControlScheme());
	}

	private Image PromptIcon(float x)
	{
		Image obj = ((Component)Box("Button prompt", (Transform)(object)page, x, -0.009f, x + 0.033f, 0.04f)).gameObject.AddComponent<Image>();
		obj.preserveAspect = true;
		((Graphic)obj).raycastTarget = false;
		return obj;
	}

	private void RefreshPrompts(string scheme)
	{
		//IL_0098: 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)
		activeScheme = scheme;
		EventSystem current = EventSystem.current;
		BaseInputModule obj = ((current != null) ? current.currentInputModule : null);
		InputSystemUIInputModule val = (InputSystemUIInputModule)(object)((obj is InputSystemUIInputModule) ? obj : null);
		PlayerInput playerInput = GamepadManager.Instance.GetPlayerInput();
		InputActionAsset obj2 = ((playerInput != null) ? playerInput.actions : null);
		object obj3 = ((obj2 != null) ? obj2.FindAction("UI/Cancel", false) : null);
		if (obj3 == null)
		{
			if (val == null)
			{
				obj3 = null;
			}
			else
			{
				InputActionReference cancel = val.cancel;
				obj3 = ((cancel != null) ? cancel.action : null);
			}
		}
		string text = Binding((InputAction)obj3, backIcon, scheme);
		backPrompt.rectTransform.anchorMin = new Vector2(((Behaviour)backIcon).enabled ? 0.487f : 0f, -0.02f);
		backPrompt.rectTransform.anchorMax = new Vector2(((Behaviour)backIcon).enabled ? 0.72f : 1f, 0.045f);
		backPrompt.alignment = (TextAlignmentOptions)(((Behaviour)backIcon).enabled ? 513 : 514);
		backPrompt.text = (text + "  Back").Trim();
	}

	private static string Binding(InputAction action, Image image, string scheme)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: 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)
		if (scheme == "KeyboardMouse" && action != null)
		{
			KeyControl val = ((IEnumerable)(object)action.controls).OfType<KeyControl>().FirstOrDefault();
			if (val != null)
			{
				((Behaviour)image).enabled = false;
				return ((InputControl)val).displayName;
			}
		}
		int num = ((action == null || string.IsNullOrEmpty(scheme)) ? (-1) : InputActionRebindingExtensions.GetBindingIndex(action, scheme, (string)null));
		object obj;
		if (num >= 0)
		{
			GamepadManager instance = GamepadManager.Instance;
			InputBinding val2 = action.bindings[num];
			obj = instance.GetButtonPrompt(((InputBinding)(ref val2)).effectivePath, false);
		}
		else
		{
			obj = null;
		}
		Sprite val3 = (image.sprite = (Sprite)obj);
		((Behaviour)image).enabled = (Object)(object)val3 != (Object)null;
		if (num >= 0 && !((Object)(object)val3 != (Object)null))
		{
			return InputActionRebindingExtensions.GetBindingDisplayString(action, num, (DisplayStringOptions)0);
		}
		return "";
	}

	private void Cycle(int step)
	{
		index = (index + step + pools.Count) % pools.Count;
		Render((step >= 0) ? 1 : 0);
	}

	private void AddButton(string text, float left, float right, Action click, bool enabled = true)
	{
		//IL_005f: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Expected O, but got Unknown
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Invalid comparison between Unknown and I4
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		RectTransform val = Box(text, (Transform)(object)page, left, 0.056f, right, 0.144f);
		Button obj = nativeButton;
		Image val2 = ((obj != null) ? ((Selectable)obj).image : null);
		Image val3 = Surface(val, (val2 != null) ? val2.sprite : null, ((Object)(object)val2 != (Object)null) ? ((Graphic)val2).color : Color.white);
		if ((Object)(object)val2 != (Object)null)
		{
			val3.pixelsPerUnitMultiplier = val2.pixelsPerUnitMultiplier;
		}
		Button val4 = ((Component)val).gameObject.AddComponent<Button>();
		((Selectable)val4).targetGraphic = (Graphic)(object)val3;
		if ((Object)(object)nativeButton != (Object)null)
		{
			((Selectable)val4).colors = ((Selectable)nativeButton).colors;
			((Selectable)val4).spriteState = ((Selectable)nativeButton).spriteState;
			if ((int)((Selectable)nativeButton).transition != 3)
			{
				((Selectable)val4).transition = ((Selectable)nativeButton).transition;
			}
		}
		((Selectable)val4).interactable = enabled;
		((UnityEvent)val4.onClick).AddListener((UnityAction)delegate
		{
			if (Time.frameCount != enteredFrame && visit.Available)
			{
				click();
			}
		});
		Outline val5 = ((Component)val).gameObject.AddComponent<Outline>();
		((Shadow)val5).effectColor = Color.white;
		((Shadow)val5).effectDistance = new Vector2(3f, -3f);
		((Behaviour)val5).enabled = false;
		PanelInput panelInput = ((Component)val).gameObject.AddComponent<PanelInput>();
		panelInput.Owner = this;
		panelInput.FocusOutline = val5;
		Label("Label", val, text, 0.03f, 0.04f, 0.97f, 0.96f, 22, (TextAlignmentOptions)514);
		buttons.Add(val4);
	}

	private void WireNavigation(int focus)
	{
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		List<Button> list = buttons.Where((Button b) => ((Selectable)b).interactable).ToList();
		for (int num = 0; num < list.Count; num++)
		{
			Button val = list[(num + list.Count - 1) % list.Count];
			Button val2 = list[(num + 1) % list.Count];
			Button obj = list[num];
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)4;
			((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)val;
			((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)val;
			((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)val2;
			((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)val2;
			((Selectable)obj).navigation = navigation;
		}
		Focus(((Selectable)buttons[focus]).interactable ? ((Component)buttons[focus]).gameObject : ((Component)list[0]).gameObject);
	}

	internal static void Focus(GameObject target)
	{
		GamepadManager.Instance.SetGameObjectToSelect(target, true);
		if ((Object)(object)EventSystem.current != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)(object)target)
		{
			EventSystem.current.SetSelectedGameObject(target);
		}
	}

	internal void Back()
	{
		LastBackFrame = Time.frameCount;
		if (Time.frameCount != enteredFrame)
		{
			if (reviewing)
			{
				reviewing = false;
				Render(2);
			}
			else
			{
				Dismiss();
			}
		}
	}

	private void Pay()
	{
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: 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)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		if (!visit.Available)
		{
			Dismiss();
			return;
		}
		Pool pool = ((pools.Count == 0) ? null : pools[index]);
		bool flag = pool?.Ids.All((string id) => OfferIds.Available(id, Pool.Identify)) ?? false;
		bool flag2;
		if (Exchange)
		{
			flag2 = ((pool != null) ? (flag && Plugin.Book.Exchange(visit.Day, visit.Number, expectedOrder, pool.Title, pool.Ids, Pool.Identify)) : (Plugin.Book.items == expectedOrder && Plugin.Missing && Plugin.Book.Finish(visit.Day, visit.Number, collect: true)));
		}
		else
		{
			ResourceType val = materialType;
			BuildingType val2 = source;
			RefreshMaterial();
			flag2 = flag && (Object)(object)material != (Object)null && materialType == val && val2 == source && Plugin.Book.Place(visit.Day, visit.Number, pool.Title, pool.Ids, Debit);
		}
		if (!flag2)
		{
			pools = Pool.Eligible(visit.Guest);
			index = Math.Min(index, Math.Max(0, pools.Count - 1));
			reviewing = false;
			Render(2);
			return;
		}
		if (!Exchange)
		{
			ResourceManager.Instance.ResourceAmountChanged(materialType);
		}
		Dismiss();
		OverlayManager.Instance.Confirm();
	}

	private void RefreshMaterial()
	{
		//IL_0064: 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_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_009d: Unknown result type (might be due to invalid IL or missing references)
		RaceManager race = RaceManager.Instance;
		ResourceType[] array = new ResourceType[3];
		RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		material = ((IEnumerable<ResourceType>)(object)array).Select((Func<ResourceType, ResourceData>)race.GetResourceData).FirstOrDefault((Func<ResourceData, bool>)((ResourceData data) => (Object)(object)data != (Object)null && (int)data.type != 0 && (int)race.GetBuildingTypeToTakeFrom(data.type) != 666));
		materialType = (ResourceType)((!((Object)(object)material == (Object)null)) ? ((int)material.type) : 0);
		source = (BuildingType)(((Object)(object)material == (Object)null) ? 666 : ((int)race.GetBuildingTypeToTakeFrom(material.type)));
	}

	private int Spendable()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: 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)
		if ((Object)(object)material == (Object)null)
		{
			return 0;
		}
		BuildingCity building = CityManager.Instance.GetBuilding(source);
		if ((Object)(object)building != (Object)null)
		{
			return CommissionPayment.Units(((Building)building).GetStorage().GetAllResourcePackets(), material.type).Length;
		}
		if (!ResourceManager.Instance.GetStartingResourcesDictionary().TryGetValue(material.type, out var value))
		{
			return 0;
		}
		return value;
	}

	private bool Debit()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: 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)
		ResourceManager instance = ResourceManager.Instance;
		BuildingCity building = CityManager.Instance.GetBuilding(source);
		if (!((Object)(object)building == (Object)null))
		{
			return CommissionPayment.Take(CommissionPayment.Units(((Building)building).GetStorage().GetAllResourcePackets(), material.type), ((Building)building).GetStorage(), (int id) => ((Building)building).TakeResourcePacket(id, false), delegate(ResourcePacket packet)
			{
				((Building)building).AddResourcePacket(packet, false);
			});
		}
		return CommissionPayment.TakeStarting(instance.GetStartingResourcesDictionary(), material.type);
	}

	private void Leave()
	{
		Dismiss();
		Plugin.Leave(merchant, visit);
	}

	internal void Dismiss()
	{
		if ((Object)(object)Plugin.Panel != (Object)(object)this)
		{
			return;
		}
		Plugin.Panel = null;
		if ((Object)(object)native != (Object)null)
		{
			native.interactable = oldInteractable;
			native.blocksRaycasts = oldRaycasts;
			if (addedGroup)
			{
				Object.Destroy((Object)(object)native);
			}
		}
		foreach (var item in hidden)
		{
			if (!((Object)(object)item.group == (Object)null))
			{
				item.group.alpha = item.alpha;
				if (item.added)
				{
					Object.Destroy((Object)(object)item.group);
				}
			}
		}
		((Component)this).gameObject.SetActive(false);
		Transform val = (OwnsCurrentScreen ? ((Component)merchant).transform.Find("Panel/Buttons/Cancel/Button") : null);
		if ((Object)(object)val != (Object)null)
		{
			Focus(((Component)val).gameObject);
		}
		Object.Destroy((Object)(object)((Component)this).gameObject);
	}
}
internal sealed class PanelInput : MonoBehaviour, ICancelHandler, IEventSystemHandler, ISelectHandler, IDeselectHandler
{
	internal CommissionPanel Owner;

	internal Outline FocusOutline;

	public void OnSelect(BaseEventData e)
	{
		((Behaviour)FocusOutline).enabled = true;
	}

	public void OnDeselect(BaseEventData e)
	{
		((Behaviour)FocusOutline).enabled = false;
	}

	public void OnCancel(BaseEventData e)
	{
		if ((Object)(object)Owner != (Object)null)
		{
			Owner.Back();
		}
		((AbstractEventData)e).Use();
	}
}
internal static class CommissionPayment
{
	internal const int Price = 3;

	internal static ResourcePacket[] Units(IEnumerable<ResourcePacket> packets, ResourceType type)
	{
		//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)
		return packets.Where((ResourcePacket p) => p != null && !p.IsReserved() && p.GetResourceType() == type && p.GetAmount() == 1).ToArray();
	}

	internal static bool Take(ResourcePacket[] units, ResourceStorage storage, Func<int, ResourcePacket> take, Action<ResourcePacket> restore)
	{
		if (units.Length < 3)
		{
			return false;
		}
		List<ResourcePacket> list = new List<ResourcePacket>(3);
		bool flag = false;
		try
		{
			foreach (ResourcePacket item in units.Take(3))
			{
				if (item.IsReserved() || storage.GetResourcePacket(item.GetIdentifier()) != item)
				{
					return false;
				}
				list.Add(item);
				ResourcePacket val = take(item.GetIdentifier());
				if (val != item)
				{
					if (val != null)
					{
						list.Add(val);
					}
					return false;
				}
			}
			flag = list.All((ResourcePacket p) => storage.GetResourcePacket(p.GetIdentifier()) == null);
			return flag;
		}
		catch (Exception ex)
		{
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("Commission payment hook failed: " + ex.Message));
			}
			return false;
		}
		finally
		{
			if (!flag)
			{
				foreach (ResourcePacket item2 in list)
				{
					if (storage.GetResourcePacket(item2.GetIdentifier()) != null)
					{
						continue;
					}
					try
					{
						restore(item2);
					}
					catch (Exception ex2)
					{
						ManualLogSource log2 = Plugin.Log;
						if (log2 != null)
						{
							log2.LogWarning((object)("Commission refund hook failed: " + ex2.Message));
						}
					}
					if (storage.GetResourcePacket(item2.GetIdentifier()) == null)
					{
						storage.AddResourcePacket(item2, false);
					}
				}
			}
		}
	}

	internal static bool TakeStarting(Dictionary<ResourceType, int> stock, ResourceType type)
	{
		//IL_0001: 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)
		if (!stock.TryGetValue(type, out var value) || value < 3)
		{
			return false;
		}
		stock[type] = value - 3;
		return true;
	}
}
internal static class OfferIds
{
	internal static string[] FromPool(IEnumerable<string> keys, Func<string, string> identify)
	{
		return Weighted(keys, identify).Distinct().ToArray();
	}

	internal static string[] Weighted(IEnumerable<string> keys, Func<string, string> identify)
	{
		List<string> list = new List<string>();
		foreach (string item in keys ?? Enumerable.Empty<string>())
		{
			if (!string.IsNullOrEmpty(item))
			{
				string text = identify(item);
				if (!string.IsNullOrEmpty(text) && identify(text) == text)
				{
					list.Add(text);
				}
			}
		}
		return list.ToArray();
	}

	internal static string[] Draw(string[] available, Func<int, int> random)
	{
		List<string> chosen = new List<string>();
		int num = Math.Min(available.Distinct().Count(), 3);
		for (int i = 0; i < 64; i++)
		{
			if (chosen.Count >= num)
			{
				break;
			}
			int num2 = random(available.Length);
			if (num2 < 0 || num2 >= available.Length)
			{
				break;
			}
			if (!chosen.Contains(available[num2]))
			{
				chosen.Add(available[num2]);
			}
		}
		while (chosen.Count < num)
		{
			string[] array = available.Where((string id) => !chosen.Contains(id)).ToArray();
			int num3 = random(array.Length);
			chosen.Add(array[(num3 >= 0 && num3 < array.Length) ? num3 : 0]);
		}
		return chosen.ToArray();
	}

	internal static IEnumerable<string[]> Pages(string[] ids)
	{
		if (ids.Length >= 3)
		{
			for (int offset = 0; offset < ids.Length; offset += 3)
			{
				yield return new string[3]
				{
					ids[offset],
					ids[(offset + 1) % ids.Length],
					ids[(offset + 2) % ids.Length]
				};
			}
		}
	}

	internal static bool Available(string id, Func<string, string> identify)
	{
		if (!string.IsNullOrEmpty(id))
		{
			return identify(id) == id;
		}
		return false;
	}
}
[Serializable]
internal sealed class OrderBook
{
	public int day = -1;

	public int lastVisit;

	public int dawnVisit;

	public List<int> spent = new List<int>();

	public string[] items = Array.Empty<string>();

	public string pool;

	[NonSerialized]
	private bool inTransaction;

	internal bool Pending
	{
		get
		{
			if (items != null)
			{
				return items.Length == 3;
			}
			return false;
		}
	}

	internal void BeginDay(int current)
	{
		if (day != current)
		{
			day = current;
			lastVisit = (dawnVisit = 0);
			spent.Clear();
		}
	}

	internal int StartVisit(int current, bool dawn)
	{
		BeginDay(current);
		if (lastVisit == 0 && spent.Count > 0)
		{
			lastVisit = spent.Max();
			if (spent.Contains(1))
			{
				dawnVisit = 1;
			}
		}
		if (dawn && dawnVisit > 0)
		{
			return dawnVisit;
		}
		int result = ++lastVisit;
		if (dawn)
		{
			dawnVisit = result;
		}
		return result;
	}

	internal bool Available(int current, int visit)
	{
		if (current == day && visit > 0)
		{
			return !spent.Contains(visit);
		}
		return false;
	}

	private static bool Valid(string[] ids)
	{
		if (ids != null && ids.Length == 3 && !ids.Any(string.IsNullOrEmpty))
		{
			return ids.Distinct().Count() == 3;
		}
		return false;
	}

	internal bool Exchange(int current, int visit, string[] expected, string kingdom, string[] replacement, Func<string, string> identify)
	{
		if (!Pending || inTransaction || items != expected || !Available(current, visit) || items.All((string id) => OfferIds.Available(id, identify)) || !Valid(replacement) || !replacement.All((string id) => OfferIds.Available(id, identify)))
		{
			return false;
		}
		items = (string[])replacement.Clone();
		pool = kingdom;
		spent.Add(visit);
		return true;
	}

	internal bool Claim(int current, int visit, string[] expected, string id, Func<string, string> identify, Func<string, bool> grant)
	{
		if (inTransaction || !Pending || items != expected || !Available(current, visit) || !items.Contains(id) || !OfferIds.Available(id, identify))
		{
			return false;
		}
		inTransaction = true;
		try
		{
			if (!grant(id))
			{
				return false;
			}
			Settle(visit, collect: true);
			return true;
		}
		finally
		{
			inTransaction = false;
		}
	}

	internal bool Place(int current, int visit, string kingdom, string[] promised, Func<bool> pay)
	{
		if (inTransaction || Pending || !Available(current, visit) || !Valid(promised))
		{
			return false;
		}
		string[] array = (string[])promised.Clone();
		inTransaction = true;
		try
		{
			if (!pay())
			{
				return false;
			}
			spent.Add(visit);
			pool = kingdom;
			items = array;
			return true;
		}
		finally
		{
			inTransaction = false;
		}
	}

	internal bool Finish(int current, int visit, bool collect)
	{
		if (inTransaction || !Available(current, visit))
		{
			return false;
		}
		Settle(visit, collect);
		return true;
	}

	private void Settle(int visit, bool collect)
	{
		spent.Add(visit);
		if (collect)
		{
			items = Array.Empty<string>();
			pool = null;
		}
	}
}
[BepInPlugin("gkj.sfk.caravancommissions", "Caravan Commissions", "0.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
internal sealed class Plugin : BaseUnityPlugin
{
	internal sealed class Visit
	{
		internal GuestCaravan Guest;

		internal int Day;

		internal int Number;

		internal bool Available
		{
			get
			{
				if (Book.Available(Day, Number))
				{
					return DaytimeManager.Instance.CurrentDay() == Day;
				}
				return false;
			}
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "OnLoad")]
	private static class ScheduledArrival
	{
		private static void Prefix(GuestCaravan __instance, out GuestCaravan __state)
		{
			__state = scheduled;
			scheduled = __instance;
		}

		private static void Finalizer(GuestCaravan __state)
		{
			scheduled = __state;
		}
	}

	[HarmonyPatch(typeof(Guest), "OnLoad")]
	private static class Arrival
	{
		private static void Prefix(Guest __instance, int day, bool ___m_Started)
		{
			if (!___m_Started)
			{
				GuestCaravan val = (GuestCaravan)(object)((__instance is GuestCaravan) ? __instance : null);
				if (val != null)
				{
					Arrive(val, day);
				}
			}
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "OnCaravan")]
	private static class Open
	{
		private static bool Prefix(GuestCaravan __instance, out Visit __state)
		{
			__state = opening;
			opening = Current(__instance);
			return opening.Available;
		}

		private static void Finalizer(Visit __state)
		{
			opening = __state;
		}

		[HarmonyPriority(0)]
		private static void Postfix(GuestCaravan __instance, bool __runOriginal)
		{
			if (!__runOriginal || !Current(__instance).Available)
			{
				return;
			}
			UIOverlayMerchant merchant = OverlayManager.Instance.GetMerchant();
			if (!((Object)(object)merchant == (Object)null) && Owns(merchant, Current(__instance)))
			{
				if (Book.Pending)
				{
					((UIOverlayBase)merchant).SetHeaderText("Commission Delivery");
					merchant.SetText(Missing ? "Some promised items are unavailable. Choose a remaining card, exchange the order for free, or go back to defer." : ("Choose one item from " + Book.pool + ", or keep your order for another visit."));
					merchant.SetCancel(Missing ? "Exchange Order" : "Defer Delivery", CancelCallback.Invoke(merchant), false);
				}
				else
				{
					merchant.SetCancel("Compare Commissions", CancelCallback.Invoke(merchant), false);
				}
			}
		}
	}

	[HarmonyPatch(typeof(UIOverlayMerchant), "Init")]
	private static class Reuse
	{
		private static void Prefix(UIOverlayMerchant __instance)
		{
			screens.Remove(__instance);
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "Reroll")]
	private static class Inventory
	{
		private static readonly Func<Guest, int, int> RandomIndex = AccessTools.MethodDelegate<Func<Guest, int, int>>(AccessTools.DeclaredMethod(typeof(Guest), "GetRandomValue", (Type[])null, (Type[])null), (object)null, true);

		[HarmonyPriority(0)]
		[HarmonyAfter(new string[] { "sfk.dailycaravan" })]
		private static bool Prefix(GuestCaravan __instance, UIOverlayMerchant merchant, bool __runOriginal, ref bool doChangeInventory, List<string> ___m_Chosen)
		{
			if (!__runOriginal)
			{
				return true;
			}
			if (!screens.TryGetValue(merchant, out var value))
			{
				value = opening;
				if (value == null)
				{
					if (Callback.Invoke(merchant)?.Target != __instance || CancelCallback.Invoke(merchant)?.Target != __instance)
					{
						return true;
					}
					value = Current(__instance);
				}
				if (value.Guest != __instance)
				{
					return true;
				}
				screens.Add(merchant, value);
			}
			if (value.Guest != __instance)
			{
				return true;
			}
			if (Book.Pending)
			{
				___m_Chosen.Clear();
				if (value.Available)
				{
					DeliveryCards.Show(merchant, value);
				}
				return false;
			}
			string[] array = OfferIds.Weighted(doChangeInventory ? Pool.Stock(__instance) : ___m_Chosen, Pool.Identify);
			IEnumerable<string> enumerable;
			if (!doChangeInventory)
			{
				enumerable = array.Distinct();
			}
			else
			{
				IEnumerable<string> enumerable2 = OfferIds.Draw(array, (int n) => RandomIndex((Guest)(object)__instance, n));
				enumerable = enumerable2;
			}
			IEnumerable<string> source = enumerable;
			___m_Chosen.Clear();
			___m_Chosen.AddRange(source.Take(3));
			doChangeInventory = false;
			return true;
		}
	}

	[HarmonyPatch(typeof(UIOverlayMerchant), "AddItem")]
	private static class ObservePrice
	{
		private static void Postfix(UIOverlayMerchant __instance, GameObject __result, ResourceAmount[] costs)
		{
			if (screens.TryGetValue(__instance, out var _) && !((Object)(object)__result == (Object)null) && costs != null && costs.Length != 0)
			{
				UICardItem component = __result.GetComponent<UICardItem>();
				if (!((Object)(object)component == (Object)null))
				{
					CardPrices.Remove(component);
					CardPrices.Add(component, costs.ToArray());
				}
			}
		}
	}

	[HarmonyPatch(typeof(UIOverlayMerchant), "Cancel")]
	private static class Compare
	{
		private static bool Prefix(UIOverlayMerchant __instance)
		{
			if (!screens.TryGetValue(__instance, out var value) || !Owns(__instance, value))
			{
				return true;
			}
			if ((Object)(object)Panel != (Object)null)
			{
				return false;
			}
			if (!value.Available || (Book.Pending && !Missing))
			{
				if (value.Available)
				{
					Book.Finish(value.Day, value.Number, collect: false);
				}
				OverlayManager.Instance.Cancel(true);
				return false;
			}
			CommissionPanel.Open(__instance, value);
			return false;
		}
	}

	[HarmonyPatch(typeof(OverlayManager), "Cancel")]
	private static class Back
	{
		private static bool Prefix(bool force, UIOverlayBase ___m_CurrentlyOpen)
		{
			if (!force && CommissionPanel.LastBackFrame == Time.frameCount)
			{
				return false;
			}
			if ((Object)(object)Panel != (Object)null)
			{
				if (Panel.OwnsCurrentScreen)
				{
					Panel.Back();
					return false;
				}
				Panel.Dismiss();
			}
			if (!force && OverlayManager.Instance.IsOpen())
			{
				UIOverlayMerchant val = (UIOverlayMerchant)(object)((___m_CurrentlyOpen is UIOverlayMerchant) ? ___m_CurrentlyOpen : null);
				if ((Object)(object)val != (Object)null && ((Behaviour)val).isActiveAndEnabled && screens.TryGetValue(val, out var value) && Owns(val, value) && value.Available)
				{
					Leave(val, value);
					return false;
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UICardItem), "Select")]
	private static class TakeItem
	{
		private static readonly FieldRef<UICard, bool> Ready = AccessTools.FieldRefAccess<UICard, bool>("m_CanBeClicked");

		private static bool Prefix(UICardItem __instance, string ___m_ItemIdentifier, out Visit __state)
		{
			__state = null;
			UIOverlayMerchant componentInParent = ((Component)__instance).GetComponentInParent<UIOverlayMerchant>();
			if ((Object)(object)componentInParent == (Object)null || !screens.TryGetValue(componentInParent, out var value) || !Owns(componentInParent, value))
			{
				return true;
			}
			if (!value.Available || (Object)(object)Panel != (Object)null || Book.Pending)
			{
				return false;
			}
			if (Ready.Invoke((UICard)(object)__instance))
			{
				__state = value;
			}
			return true;
		}

		private static void Postfix(Visit __state, bool __runOriginal)
		{
			if (__runOriginal && __state != null)
			{
				Book.Finish(__state.Day, __state.Number, collect: true);
			}
		}
	}

	internal static OrderBook Book = new OrderBook();

	internal static CommissionPanel Panel;

	private static ConditionalWeakTable<UIOverlayMerchant, Visit> screens = new ConditionalWeakTable<UIOverlayMerchant, Visit>();

	private static ConditionalWeakTable<GuestCaravan, Visit> arrivals = new ConditionalWeakTable<GuestCaravan, Visit>();

	private static Visit opening;

	private static GuestCaravan scheduled;

	private static Func<bool> dailyDispatch;

	internal static ManualLogSource Log;

	private Harmony harmony;

	private static readonly FieldRef<UIOverlayMerchant, Action<int, ResourceAmount[]>> Callback = AccessTools.FieldRefAccess<UIOverlayMerchant, Action<int, ResourceAmount[]>>("m_Callback");

	private static readonly FieldRef<UIOverlayMerchant, Action<UIOverlayMerchant>> CancelCallback = AccessTools.FieldRefAccess<UIOverlayMerchant, Action<UIOverlayMerchant>>("m_CallbackCancel");

	private static readonly FieldRef<OverlayManager, UIOverlayBase> CurrentOverlay = AccessTools.FieldRefAccess<OverlayManager, UIOverlayBase>("m_CurrentlyOpen");

	internal static readonly ConditionalWeakTable<UICardItem, ResourceAmount[]> CardPrices = new ConditionalWeakTable<UICardItem, ResourceAmount[]>();

	internal static bool Missing
	{
		get
		{
			if (Book.Pending)
			{
				return Book.items.Any((string id) => !OfferIds.Available(id, Pool.Identify));
			}
			return false;
		}
	}

	internal static bool Owns(UIOverlayMerchant screen, Visit visit)
	{
		if (screens.TryGetValue(screen, out var value))
		{
			return value == visit;
		}
		return false;
	}

	internal static bool IsCurrent(UIOverlayMerchant screen)
	{
		if ((Object)(object)OverlayManager.Instance != (Object)null && (Object)(object)screen != (Object)null && ((Behaviour)screen).isActiveAndEnabled)
		{
			return (object)CurrentOverlay.Invoke(OverlayManager.Instance) == screen;
		}
		return false;
	}

	private void Awake()
	{
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		if (Chainloader.PluginInfos.TryGetValue("sfk.dailycaravan", out var value) && (Object)(object)value.Instance != (Object)null)
		{
			MethodInfo methodInfo = AccessTools.PropertyGetter(((object)value.Instance).GetType(), "Launching");
			if (methodInfo?.ReturnType == typeof(bool))
			{
				dailyDispatch = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), value.Instance, methodInfo);
			}
		}
		harmony = new Harmony("gkj.sfk.caravancommissions");
		harmony.PatchAll(typeof(Plugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Caravan Commissions 0.1.0 loaded");
	}

	private void OnDestroy()
	{
		if ((Object)(object)Panel != (Object)null)
		{
			Panel.Dismiss();
		}
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		dailyDispatch = null;
		Log = null;
	}

	internal static void Reset(OrderBook saved)
	{
		if ((Object)(object)Panel != (Object)null)
		{
			Panel.Dismiss();
		}
		Book = saved ?? new OrderBook();
		arrivals = new ConditionalWeakTable<GuestCaravan, Visit>();
		screens = new ConditionalWeakTable<UIOverlayMerchant, Visit>();
		opening = null;
		scheduled = null;
	}

	private static Visit Arrive(GuestCaravan guest, int day)
	{
		bool dawn = scheduled == guest || (dailyDispatch?.Invoke() ?? false);
		Visit visit = new Visit
		{
			Guest = guest,
			Number = Book.StartVisit(day, dawn),
			Day = day
		};
		arrivals.Remove(guest);
		arrivals.Add(guest, visit);
		return visit;
	}

	private static Visit Current(GuestCaravan guest)
	{
		int num = DaytimeManager.Instance.CurrentDay();
		if (!arrivals.TryGetValue(guest, out var value) || value.Day != num)
		{
			return Arrive(guest, num);
		}
		return value;
	}

	internal static void Leave(UIOverlayMerchant screen, Visit visit)
	{
		if (!Book.Pending && Owns(screen, visit))
		{
			Action<UIOverlayMerchant> action = CancelCallback.Invoke(screen);
			if (action == null)
			{
				OverlayManager.Instance.Cancel(true);
			}
			else
			{
				action(screen);
			}
		}
		else
		{
			if (Book.Pending)
			{
				Book.Finish(visit.Day, visit.Number, collect: false);
			}
			OverlayManager.Instance.Cancel(true);
		}
	}
}
internal static class SaveHooks
{
	[Serializable]
	private sealed class Envelope
	{
		public string runID;

		public string hash;

		public OrderBook caravanCommissionsV1;
	}

	private sealed class ReadContext
	{
		internal string Path;

		internal Envelope Selected;
	}

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

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

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

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

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

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

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

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

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

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

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

	[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	private static class WriteJson
	{
		private static void Prefix(string __0, ref string __1)
		{
			if (writing != null && !(__0 != writePath) && (writing.Pending || writing.spent.Count != 0))
			{
				int num = __1.LastIndexOf('}');
				if (num >= 0)
				{
					__1 = __1.Insert(num, ",\"caravanCommissionsV1\":" + JsonUtility.ToJson((object)writing));
				}
			}
		}
	}

	private const string Key = "caravanCommissionsV1";

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

	private static ReadContext reading;

	private static OrderBook writing;

	private static string writePath;

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