Decompiled source of OttoPay v1.6.2

OttoPay.dll

Decompiled 4 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using OttoPay.Compatibility;
using ServerSync;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("OttoPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("potto007")]
[assembly: AssemblyProduct("OttoPay")]
[assembly: AssemblyCopyright("Copyright © 2026 potto007. Based on CurrencyPocket, Copyright © 2021 Azumatt.")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: AssemblyFileVersion("1.6.2")]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.6.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OttoPay
{
	public class CurrencyPocket
	{
		[HarmonyPatch(typeof(InventoryGui), "Awake")]
		public static class InventoryGuiUpdatePatch
		{
			public static Button ExtractButton;

			public static Button AuraPayButton;

			public static GameObject pocketUI;

			public static Sprite coinSprite;

			[HarmonyAfter(new string[] { "org.bepinex.plugins.jewelcrafting" })]
			private static void Postfix(InventoryGui __instance)
			{
				if ((Object)(object)pocketUI == (Object)null)
				{
					CreatePocketUI(__instance);
				}
				if ((Object)(object)ExtractButton == (Object)null && (Object)(object)pocketUI != (Object)null)
				{
					CreateButton(__instance);
				}
				if ((Object)(object)AuraPayButton == (Object)null && (Object)(object)pocketUI != (Object)null && Chainloader.PluginInfos.ContainsKey("potto007.OttoAura"))
				{
					CreateAuraPayToggle(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Show")]
		private static class InventoryGuiShowPatch
		{
			private static GameObject? cached;

			private static Coroutine? coroutine;

			private static void Prefix()
			{
				UpdatePocketUI();
			}

			[HarmonyPriority(100)]
			private static void Postfix(InventoryGui __instance)
			{
				if (!OttoPayApi.IsBankMember())
				{
					return;
				}
				if (Object.op_Implicit((Object)(object)cached))
				{
					if (coroutine != null)
					{
						((MonoBehaviour)__instance).StopCoroutine(coroutine);
					}
				}
				else
				{
					cached = ((Component)__instance).gameObject;
					coroutine = ((MonoBehaviour)__instance).StartCoroutine(WaitOneFrame());
				}
				IEnumerator WaitOneFrame()
				{
					yield return null;
					Transform transform = ((Component)__instance.m_player).transform;
					int num = 0;
					while (num < transform.childCount)
					{
						Transform child = transform.GetChild(num);
						bool flag;
						switch (((Object)child).name)
						{
						case "Armor":
						case "Weight":
						case "Jewelcrafting Synergy":
						case "CoinPocketUI":
						case "Trash":
							flag = true;
							break;
						default:
							flag = false;
							break;
						}
						RectTransform component;
						if (flag)
						{
							component = ((Component)child).gameObject.GetComponent<RectTransform>();
							if (Object.op_Implicit((Object)(object)component))
							{
								string name = ((Object)child).name;
								if (!(name == "CoinPocketUI"))
								{
									if (!(name == "Weight") || MiscFunctions.IsOverlappingUIModInstalled())
									{
										goto IL_0123;
									}
								}
								else
								{
									if (MiscFunctions.IsOverlappingUIModInstalled())
									{
										goto IL_0123;
									}
									component.anchoredPosition += new Vector2(0f, -45f);
								}
							}
						}
						goto IL_0144;
						IL_0144:
						if (((Object)child).name == "selected_frame")
						{
							((Component)((Component)child).transform.Find("selected (2)")).gameObject.SetActive(false);
							((Component)((Component)child).transform.Find("selected (3)")).gameObject.SetActive(false);
						}
						num++;
						continue;
						IL_0123:
						component.anchoredPosition += new Vector2(0f, 45f);
						goto IL_0144;
					}
				}
			}
		}

		[HarmonyPatch(typeof(StoreGui), "GetPlayerCoins")]
		private static class StoreGuiGetPlayerCoinsPatch
		{
			private static void Postfix(StoreGui __instance, ref int __result)
			{
				if (OttoPayApi.IsBankMember())
				{
					__result += MiscFunctions.GetPlayerCoinsFromCustomData();
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "Pickup")]
		private static class AddItemToInventory
		{
			[HarmonyPriority(300)]
			private static bool Prefix(Humanoid __instance, GameObject go, bool autoPickupDelay, bool __runOriginal, ref bool __result)
			{
				//IL_00bf: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				if (__runOriginal)
				{
					Player val = (Player)(object)((__instance is Player) ? __instance : null);
					if (val != null)
					{
						ItemDrop component = go.GetComponent<ItemDrop>();
						if (component != null && !((Character)val).IsTeleporting() && component.CanPickup(autoPickupDelay) && component.m_nview.GetZDO() != null)
						{
							ItemData itemData = component.m_itemData;
							if (itemData.m_dropPrefab == null)
							{
								itemData.m_dropPrefab = ObjectDB.instance.GetItemPrefab(Utils.GetPrefabName(((Component)component).gameObject));
							}
							string name = component.m_itemData.m_shared.m_name;
							int stack = component.m_itemData.m_stack;
							CheckAutoPickupActive.PickingUp = false;
							if (name == "$item_coins" && OttoPayApi.IsBankMember())
							{
								MiscFunctions.UpdatePlayerCustomData(MiscFunctions.GetPlayerCoinsFromCustomData() + stack);
								UpdatePocketUI();
								ZNetScene.instance.Destroy(go);
								((Humanoid)val).m_pickupEffects.Create(((Component)val).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
								((Character)val).ShowPickupMessage(component.m_itemData, stack);
								__result = true;
								return false;
							}
							return true;
						}
					}
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Player), "AutoPickup")]
		private static class CheckAutoPickupActive
		{
			public static bool PickingUp;

			private static void Prefix()
			{
				PickingUp = true;
			}

			private static void Finalizer()
			{
				PickingUp = false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[]
		{
			typeof(ItemData),
			typeof(int)
		})]
		private static class AutoPickupItemsWithFullInventory
		{
			private static void Postfix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (!__result && CheckAutoPickupActive.PickingUp && item?.m_shared?.m_name == "$item_coins" && OttoPayApi.IsBankMember())
				{
					__result = true;
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		public static class Inventory_RemoveItem_Patch
		{
			public static void Prefix(Inventory __instance, string name, int itemQuality, bool worldLevelBased, out int __state)
			{
				__state = ((name == "$item_coins") ? __instance.CountItems(name, itemQuality, worldLevelBased) : 0);
			}

			public static void Postfix(Inventory __instance, string name, int amount, int itemQuality, bool worldLevelBased, int __state)
			{
				if (!((Object)(object)Player.m_localPlayer == (Object)null) && __instance == ((Humanoid)Player.m_localPlayer).GetInventory() && !(name != "$item_coins") && OttoPayApi.IsBankMember())
				{
					int num = __state - __instance.CountItems(name, itemQuality, worldLevelBased);
					int num2 = amount - num;
					if (num2 > 0)
					{
						int playerCoinsFromCustomData = MiscFunctions.GetPlayerCoinsFromCustomData();
						MiscFunctions.UpdatePlayerCustomData(playerCoinsFromCustomData - Math.Min(playerCoinsFromCustomData, num2));
						UpdatePocketUI();
					}
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int),
			typeof(int),
			typeof(int)
		})]
		private static class InventoryMoveItemToThisPatch
		{
			private static bool Prefix(Inventory __instance, Inventory fromInventory, ItemData item, int amount, int x, int y, ref bool __result)
			{
				Player localPlayer = Player.m_localPlayer;
				if (!Object.op_Implicit((Object)(object)localPlayer))
				{
					return true;
				}
				if (item?.m_shared?.m_name != "$item_coins" || __instance != ((Humanoid)localPlayer).GetInventory() || !OttoPayApi.IsBankMember())
				{
					return true;
				}
				ItemData itemAt = __instance.GetItemAt(x, y);
				if (itemAt != null)
				{
					SharedData shared = itemAt.m_shared;
					if (shared != null && shared.m_name == "$item_coins")
					{
						int maxStackSize = itemAt.m_shared.m_maxStackSize;
						int num = Math.Min(Math.Min(Math.Max(0, maxStackSize - itemAt.m_stack), amount), item.m_stack);
						if (num > 0)
						{
							itemAt.m_stack += num;
							item.m_stack -= num;
							if (item.m_stack <= 0 && fromInventory != null)
							{
								fromInventory.RemoveItem(item);
							}
							__instance.Changed(false, false);
							if (fromInventory != null)
							{
								fromInventory.Changed(false, false);
							}
							__result = true;
							return false;
						}
						__result = false;
						return false;
					}
				}
				int stack = item.m_stack;
				bool flag = __instance.AddItem(item, amount, x, y, false);
				if (Math.Max(0, stack - item.m_stack) > 0)
				{
					if (item.m_stack <= 0 && fromInventory != null)
					{
						fromInventory.RemoveItem(item);
					}
					if (fromInventory != null)
					{
						fromInventory.Changed(false, false);
					}
					__instance.Changed(false, false);
				}
				__result = flag;
				return false;
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__ExtractCoins;
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__11_0;

			internal void <CreateAuraPayToggle>b__11_0()
			{
				bool flag = !OttoPayApi.IsAuraPayEnabled();
				OttoPayApi.SetAuraPayEnabled(flag);
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)1, flag ? "AuraPay on: ward auras may charge your Merchant Bank balance." : "AuraPay off: ward auras will not charge your balance.", 0, (Sprite)null, false);
				}
			}
		}

		internal static bool CoinExtractionInProgress;

		internal static void UpdatePocketUI()
		{
			if ((Object)(object)InventoryGuiUpdatePatch.pocketUI == (Object)null)
			{
				return;
			}
			InventoryGuiUpdatePatch.pocketUI.SetActive(OttoPayApi.IsBankMember());
			Transform val = Utils.FindChild(InventoryGuiUpdatePatch.pocketUI.transform, "ac_text", (IterativeSearchType)0);
			if (!((Object)(object)val == (Object)null))
			{
				TextMeshProUGUI component = ((Component)val).GetComponent<TextMeshProUGUI>();
				if (!((Object)(object)component == (Object)null))
				{
					((TMP_Text)component).text = $"{MiscFunctions.GetPlayerCoinsFromCustomData()}";
					AttachWithdrawTooltip();
					UpdateAuraPayToggle();
				}
			}
		}

		internal static void UpdateAuraPayToggle()
		{
			if (!((Object)(object)InventoryGuiUpdatePatch.AuraPayButton == (Object)null))
			{
				TextMeshProUGUI componentInChildren = ((Component)InventoryGuiUpdatePatch.AuraPayButton).GetComponentInChildren<TextMeshProUGUI>();
				if (!((Object)(object)componentInChildren == (Object)null))
				{
					((TMP_Text)componentInChildren).textWrappingMode = (TextWrappingModes)0;
					((TMP_Text)componentInChildren).overflowMode = (TextOverflowModes)0;
					((TMP_Text)componentInChildren).enableAutoSizing = true;
					((TMP_Text)componentInChildren).fontSizeMin = 8f;
					bool flag = OttoPayApi.IsAuraPayEnabled();
					((TMP_Text)componentInChildren).text = (flag ? "<color=#7CFFB2>AuraPay</color>" : "<color=#8A8A8A>AuraPay</color>");
					IReadOnlyList<string> readOnlyList = OttoPayApi.AuraServiceLines();
					string text = ((readOnlyList.Count > 0) ? ("\n\n" + string.Join("\n\n", readOnlyList)) : "");
					Tooltips.Attach(((Component)InventoryGuiUpdatePatch.AuraPayButton).gameObject, "AuraPay", flag ? ("AuraPay is on.\n\nA ward aura may charge your Merchant Bank balance to repair the gear you are wearing." + text + "\n\nClick to turn it off.") : ("AuraPay is off.\n\nWard auras will not charge your Merchant Bank balance for repairs." + text + "\n\nClick to turn it on."));
				}
			}
		}

		private static void CreateAuraPayToggle(InventoryGui gui)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0066: 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_0071: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			Button obj = Object.Instantiate<Button>(gui.m_takeAllButton, InventoryGuiUpdatePatch.pocketUI.transform);
			((Object)obj).name = "AuraPayToggleButton";
			((Component)obj).transform.SetParent(InventoryGuiUpdatePatch.pocketUI.transform, false);
			Tooltips.Strip(((Component)obj).gameObject);
			obj.onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = obj.onClick;
			object obj2 = <>c.<>9__11_0;
			if (obj2 == null)
			{
				UnityAction val = delegate
				{
					bool flag = !OttoPayApi.IsAuraPayEnabled();
					OttoPayApi.SetAuraPayEnabled(flag);
					Player localPlayer = Player.m_localPlayer;
					if (localPlayer != null)
					{
						((Character)localPlayer).Message((MessageType)1, flag ? "AuraPay on: ward auras may charge your Merchant Bank balance." : "AuraPay off: ward auras will not charge your balance.", 0, (Sprite)null, false);
					}
				};
				<>c.<>9__11_0 = val;
				obj2 = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj2);
			UIGamePad component = ((Component)obj).GetComponent<UIGamePad>();
			if ((Object)(object)component != (Object)null)
			{
				if (Object.op_Implicit((Object)(object)component.m_hint))
				{
					Object.Destroy((Object)(object)component.m_hint);
				}
				component.m_hint = null;
				component.m_zinputKey = string.Empty;
				component.m_keyCode = (KeyCode)0;
			}
			((Transform)((Component)obj).GetComponent<RectTransform>()).localPosition = new Vector3(2.5f, -38f, 0f);
			((Component)obj).transform.localScale = new Vector3(0.4f, 0.4f, 1f);
			InventoryGuiUpdatePatch.AuraPayButton = obj;
			UpdateAuraPayToggle();
		}

		private static void CreatePocketUI(InventoryGui instance)
		{
			//IL_004c: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			Transform transform = ((Component)instance.m_player).transform;
			InventoryGuiUpdatePatch.pocketUI = Object.Instantiate<GameObject>(((Component)transform.Find("Armor")).gameObject, transform);
			((Object)InventoryGuiUpdatePatch.pocketUI).name = "CoinPocketUI";
			RectTransform component = InventoryGuiUpdatePatch.pocketUI.GetComponent<RectTransform>();
			OttoPayPlugin.OttoPayLogger.LogDebug((object)$"Creating pocket UI at {component.anchoredPosition}");
			if (MiscFunctions.IsOverlappingUIModInstalled())
			{
				component.anchoredPosition += new Vector2(0f, -234f);
			}
			else
			{
				RectTransform component2 = ((Component)transform.Find("Armor")).GetComponent<RectTransform>();
				RectTransform component3 = ((Component)transform.Find("Weight")).GetComponent<RectTransform>();
				InventoryGuiUpdatePatch.pocketUI.transform.SetSiblingIndex(transform.Find("Armor").GetSiblingIndex());
				component.anchoredPosition = new Vector2(component2.anchoredPosition.x, (component2.anchoredPosition.y + component3.anchoredPosition.y) / 2f);
			}
			OttoPayPlugin.OttoPayLogger.LogDebug((object)$"Creating pocket UI at {component.anchoredPosition}");
			InventoryGuiUpdatePatch.coinSprite = ObjectDB.instance.GetItemPrefab("Coins").GetComponent<ItemDrop>().m_itemData.GetIcon();
			((Component)InventoryGuiUpdatePatch.pocketUI.transform.Find("armor_icon")).GetComponent<Image>().sprite = InventoryGuiUpdatePatch.coinSprite;
			InventoryGuiUpdatePatch.pocketUI.transform.SetSiblingIndex(transform.Find("Armor").GetSiblingIndex());
			((TMP_Text)((Component)InventoryGuiUpdatePatch.pocketUI.transform.Find("ac_text")).GetComponent<TextMeshProUGUI>()).text = $"{MiscFunctions.GetPlayerCoinsFromCustomData()}";
			Tooltips.Strip(InventoryGuiUpdatePatch.pocketUI);
			InventoryGuiUpdatePatch.pocketUI.AddComponent<PocketDrop>();
		}

		private static void CreateButton(InventoryGui __instance)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)InventoryGuiUpdatePatch.ExtractButton != (Object)null))
			{
				InventoryGuiUpdatePatch.ExtractButton = Object.Instantiate<Button>(__instance.m_takeAllButton, InventoryGuiUpdatePatch.pocketUI.transform);
				((Object)InventoryGuiUpdatePatch.ExtractButton).name = "ExtractCoinsButton";
				((TMP_Text)((Component)InventoryGuiUpdatePatch.ExtractButton).GetComponentInChildren<TextMeshProUGUI>()).text = "\ud83d\udce6";
				((Component)InventoryGuiUpdatePatch.ExtractButton).transform.SetParent(InventoryGuiUpdatePatch.pocketUI.transform, false);
				InventoryGuiUpdatePatch.ExtractButton.onClick = new ButtonClickedEvent();
				ButtonClickedEvent onClick = InventoryGuiUpdatePatch.ExtractButton.onClick;
				object obj = <>O.<0>__ExtractCoins;
				if (obj == null)
				{
					UnityAction val = MiscFunctions.ExtractCoins;
					<>O.<0>__ExtractCoins = val;
					obj = (object)val;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				UIGamePad component = ((Component)InventoryGuiUpdatePatch.ExtractButton).GetComponent<UIGamePad>();
				if (Object.op_Implicit((Object)(object)component.m_hint))
				{
					Object.Destroy((Object)(object)component.m_hint);
				}
				component.m_hint = null;
				component.m_zinputKey = string.Empty;
				component.m_keyCode = (KeyCode)0;
				RectTransform val2 = ((Component)InventoryGuiUpdatePatch.ExtractButton).GetComponent<RectTransform>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)InventoryGuiUpdatePatch.ExtractButton).gameObject.AddComponent<RectTransform>();
				}
				((Transform)val2).localPosition = new Vector3(2.5f, -20f, 0f);
				((Component)InventoryGuiUpdatePatch.ExtractButton).transform.localScale = new Vector3(0.4f, 0.4f, 1f);
				Tooltips.Strip(((Component)InventoryGuiUpdatePatch.ExtractButton).gameObject);
				AttachWithdrawTooltip();
			}
		}

		internal static void AttachWithdrawTooltip()
		{
			if (!((Object)(object)InventoryGuiUpdatePatch.ExtractButton == (Object)null))
			{
				Tooltips.Attach(((Component)InventoryGuiUpdatePatch.ExtractButton).gameObject, "Withdraw coins", "Take coins from your Merchant Bank balance and put them in your inventory.\n\nChoose how many in the dialog. Hold Ctrl when you click to take them all.\n\nDrop coins on your balance to deposit them again.");
			}
		}

		private static void CreateIcon()
		{
			//IL_0024: 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)
			Sprite icon = ObjectDB.instance.GetItemPrefab("Coins").GetComponent<ItemDrop>().m_itemData.GetIcon();
			GameObject val = new GameObject("CoinIcon");
			val.transform.SetParent(InventoryGuiUpdatePatch.pocketUI.transform, false);
			Image obj = val.AddComponent<Image>();
			obj.sprite = icon;
			obj.preserveAspect = true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnSplitOk")]
	internal static class InventoryGuiOnSplitOkPatch
	{
		internal static Inventory throwAwayInventory;

		internal static void Prefix(InventoryGui __instance)
		{
			if (!(__instance.m_splitItem?.m_shared.m_name != "$item_coins") && CurrencyPocket.CoinExtractionInProgress)
			{
				__instance.m_splitInventory = throwAwayInventory;
				MiscFunctions.UpdatePlayerCustomData(MiscFunctions.GetPlayerCoinsFromCustomData() - (int)__instance.m_splitDialog.SliderValue);
				CurrencyPocket.UpdatePocketUI();
				CurrencyPocket.CoinExtractionInProgress = false;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateContainer")]
	internal static class PreventSetupDrag
	{
		private static bool Prefix(InventoryGui __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance.m_currentContainer) && __instance.m_currentContainer.IsOwner())
			{
				return true;
			}
			Inventory dragInventory = __instance.m_dragInventory;
			return dragInventory == null || !(dragInventory.m_name == "CoinPocket_CoinCount");
		}
	}
	[HarmonyPatch(typeof(StoreGui), "Show")]
	internal static class MerchantBankJoinButton
	{
		private const string JoinButtonName = "MerchantBankJoinButton";

		private const string JoinLabel = "Join Merchant Bank";

		private static Button? _joinButton;

		private static GameObject? _message;

		private static void Postfix(StoreGui __instance)
		{
			if ((Object)(object)_joinButton == (Object)null)
			{
				Create(__instance);
			}
			if ((Object)(object)_joinButton != (Object)null)
			{
				((Component)_joinButton).gameObject.SetActive(!OttoPayApi.IsBankMember());
			}
		}

		private static void Create(StoreGui gui)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: 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_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0388: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)gui.m_buyButton == (Object)null || (Object)(object)gui.m_sellButton == (Object)null)
			{
				return;
			}
			Button val = Object.Instantiate<Button>(gui.m_buyButton, ((Component)gui.m_sellButton).transform.parent);
			((Object)val).name = "MerchantBankJoinButton";
			val.onClick = new ButtonClickedEvent();
			((UnityEvent)val.onClick).AddListener((UnityAction)delegate
			{
				Join(gui);
			});
			((Selectable)val).interactable = true;
			UIGamePad component = ((Component)val).GetComponent<UIGamePad>();
			if ((Object)(object)component != (Object)null)
			{
				if (Object.op_Implicit((Object)(object)component.m_hint))
				{
					Object.Destroy((Object)(object)component.m_hint);
				}
				component.m_hint = null;
				component.m_zinputKey = string.Empty;
				component.m_keyCode = (KeyCode)0;
			}
			Localize[] componentsInChildren = ((Component)val).GetComponentsInChildren<Localize>(true);
			for (int num = 0; num < componentsInChildren.Length; num++)
			{
				Object.Destroy((Object)(object)componentsInChildren[num]);
			}
			TextMeshProUGUI[] componentsInChildren2 = ((Component)val).GetComponentsInChildren<TextMeshProUGUI>(true);
			TextMeshProUGUI[] array = componentsInChildren2;
			foreach (TextMeshProUGUI obj in array)
			{
				((TMP_Text)obj).text = "Join Merchant Bank";
				((TMP_Text)obj).textWrappingMode = (TextWrappingModes)0;
				((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
				((TMP_Text)obj).enableAutoSizing = true;
				((TMP_Text)obj).fontSizeMin = 9f;
			}
			RectTransform component2 = ((Component)gui.m_sellButton).GetComponent<RectTransform>();
			RectTransform component3 = ((Component)gui.m_buyButton).GetComponent<RectTransform>();
			RectTransform component4 = ((Component)val).GetComponent<RectTransform>();
			Rect rect = component3.rect;
			float num2 = Mathf.Max(((Rect)(ref rect)).width, 210f);
			rect = component2.rect;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(num2, Mathf.Max(((Rect)(ref rect)).height, 36f));
			component4.anchorMin = component2.anchorMin;
			component4.anchorMax = component2.anchorMax;
			component4.pivot = component2.pivot;
			Vector2 zero = Vector2.zero;
			Transform parent = ((Component)val).transform.parent;
			RectTransform val3 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			if (val3 != null)
			{
				rect = val3.rect;
				Vector2 size = ((Rect)(ref rect)).size;
				((Vector2)(ref zero))..ctor((component4.anchorMax.x - component4.anchorMin.x) * size.x, (component4.anchorMax.y - component4.anchorMin.y) * size.y);
			}
			component4.sizeDelta = val2 - zero;
			float x = component4.pivot.x;
			float x2 = val2.x;
			rect = component2.rect;
			float num3 = x * (x2 - ((Rect)(ref rect)).width);
			Vector2 anchoredPosition = component2.anchoredPosition;
			rect = component2.rect;
			component4.anchoredPosition = anchoredPosition + new Vector2(num3, ((Rect)(ref rect)).height + 8f);
			Tooltips.Strip(((Component)val).gameObject);
			Tooltips.Attach(((Component)val).gameObject, "Merchant Bank", "Join the Merchant Bank Network.\n\nCoins you pick up vanish into your Merchant Bank balance, held for you by merchant magic. They take no inventory slot and weigh nothing.\n\nAny merchant draws on your balance when you buy, and you can call coins back into your hand whenever you like.");
			_joinButton = val;
			rect = component4.rect;
			Vector2 size2 = ((Rect)(ref rect)).size;
			OttoPayPlugin.OttoPayLogger.LogInfo((object)$"Merchant Bank join button created at {component4.anchoredPosition}, size {size2}, wanted {val2}, labels {componentsInChildren2.Length}.");
			if (size2.x <= 1f || size2.y <= 1f)
			{
				OttoPayPlugin.OttoPayLogger.LogWarning((object)$"Join button has a degenerate size {size2} and will not be visible. Falling back to a fixed size.");
				Vector2 val4 = default(Vector2);
				((Vector2)(ref val4))..ctor(0.5f, 0.5f);
				component4.pivot = val4;
				Vector2 anchorMin = (component4.anchorMax = val4);
				component4.anchorMin = anchorMin;
				component4.sizeDelta = val2;
			}
		}

		private static void Join(StoreGui gui)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !OttoPayApi.IsBankMember())
			{
				OttoPayApi.JoinBank();
				string text = (((Object)(object)gui.m_trader != (Object)null) ? Localization.instance.Localize(gui.m_trader.m_name) : "The merchant") + " binds you to the Merchant Bank Network.\nCoins you pick up now go straight to your balance.";
				((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
				ShowStoreMessage(gui, text);
				if ((Object)(object)_joinButton != (Object)null)
				{
					((Component)_joinButton).gameObject.SetActive(false);
				}
				gui.FillList();
			}
		}

		private static void ShowStoreMessage(StoreGui gui, string text)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0079: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: 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_0143: 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_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)gui.m_rootPanel == (Object)null))
			{
				if ((Object)(object)_message != (Object)null)
				{
					Object.Destroy((Object)(object)_message);
				}
				GameObject val = new GameObject("OttoPayStoreMessage", new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				});
				val.transform.SetParent(gui.m_rootPanel.transform, false);
				val.transform.SetAsLastSibling();
				RectTransform val2 = (RectTransform)val.transform;
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(0.5f, 0.5f);
				val2.pivot = val3;
				Vector2 anchorMin = (val2.anchorMax = val3);
				val2.anchorMin = anchorMin;
				val2.sizeDelta = new Vector2(250f, 130f);
				val2.anchoredPosition = Vector2.zero;
				Image component = val.GetComponent<Image>();
				((Graphic)component).color = new Color(0.06f, 0.05f, 0.04f, 0.93f);
				((Graphic)component).raycastTarget = false;
				GameObject val5 = new GameObject("Text", new Type[2]
				{
					typeof(RectTransform),
					typeof(TextMeshProUGUI)
				});
				val5.transform.SetParent(val.transform, false);
				RectTransform val6 = (RectTransform)val5.transform;
				val6.anchorMin = Vector2.zero;
				val6.anchorMax = Vector2.one;
				val6.offsetMin = new Vector2(12f, 12f);
				val6.offsetMax = new Vector2(-12f, -12f);
				TextMeshProUGUI component2 = val5.GetComponent<TextMeshProUGUI>();
				((TMP_Text)component2).text = text;
				((TMP_Text)component2).alignment = (TextAlignmentOptions)514;
				((TMP_Text)component2).enableAutoSizing = true;
				((TMP_Text)component2).fontSizeMin = 10f;
				((TMP_Text)component2).fontSizeMax = 18f;
				((Graphic)component2).raycastTarget = false;
				if ((Object)(object)gui.m_coinText != (Object)null)
				{
					((TMP_Text)component2).font = gui.m_coinText.font;
					((Graphic)component2).color = ((Graphic)gui.m_coinText).color;
				}
				_message = val;
				((MonoBehaviour)gui).StartCoroutine(HideMessageAfter(6f));
			}
		}

		private static IEnumerator HideMessageAfter(float seconds)
		{
			yield return (object)new WaitForSeconds(seconds);
			if ((Object)(object)_message != (Object)null)
			{
				Object.Destroy((Object)(object)_message);
				_message = null;
			}
		}
	}
	public class MiscFunctions
	{
		public static string GetPrefabName(string name)
		{
			char[] anyOf = new char[2] { '(', ' ' };
			int num = name.IndexOfAny(anyOf);
			if (num >= 0)
			{
				return name.Substring(0, num);
			}
			return name;
		}

		internal static GameObject? GetItemPrefabFromGameObject(ItemDrop itemDropComponent, GameObject inputGameObject)
		{
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(GetPrefabName(((Object)inputGameObject).name));
			itemDropComponent.m_itemData.m_dropPrefab = itemPrefab;
			if (!((Object)(object)itemPrefab != (Object)null))
			{
				return null;
			}
			return itemPrefab;
		}

		internal static bool CheckItemDropIntegrity(ItemDrop itemDropComp)
		{
			return itemDropComp.m_itemData?.m_shared != null;
		}

		internal static void ProcessRequirements(Requirement[] requirements, int qualityLevel, Player instance, int itemQuality)
		{
			foreach (Requirement val in requirements)
			{
				if (IsValidRequirement(val))
				{
					int amount = val.GetAmount(qualityLevel);
					if (amount > 0 && val.m_resItem.m_itemData.m_shared.m_name == "$item_coins")
					{
						string value;
						int num = (instance.m_customData.TryGetValue("CoinPocket_CoinCount", out value) ? int.Parse(value) : 0);
						UpdatePlayerCustomData(num - Math.Min(num, amount), instance);
						CurrencyPocket.UpdatePocketUI();
					}
				}
			}
		}

		private static bool IsValidRequirement(Requirement requirement)
		{
			if (Object.op_Implicit((Object)(object)requirement.m_resItem))
			{
				ItemData itemData = requirement.m_resItem.m_itemData;
				if (itemData != null)
				{
					return itemData.m_shared != null;
				}
				return false;
			}
			return false;
		}

		internal static void UpdatePlayerCustomData(int coinCount, Player? player = null)
		{
			coinCount = Math.Max(0, coinCount);
			if ((Object)(object)player == (Object)null)
			{
				player = Player.m_localPlayer;
			}
			if ((Object)(object)player != (Object)null)
			{
				player.m_customData["CoinPocket_CoinCount"] = coinCount.ToString();
			}
		}

		internal static int GetPlayerCoinsFromCustomData()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && localPlayer.m_customData.TryGetValue("CoinPocket_CoinCount", out var value))
			{
				return int.Parse(value);
			}
			return 0;
		}

		internal static void ExtractCoins()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			if ((Object)(object)Player.m_localPlayer != (Object)null && GetPlayerCoinsFromCustomData() > 0)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Coins");
				InventoryGuiOnSplitOkPatch.throwAwayInventory = new Inventory("CoinPocket_CoinCount", itemPrefab.GetComponent<ItemDrop>().m_itemData.GetIcon(), 1, 1);
				InventoryGuiOnSplitOkPatch.throwAwayInventory.AddItem(itemPrefab, GetPlayerCoinsFromCustomData());
				InventoryGui.instance.ShowSplitDialog(InventoryGuiOnSplitOkPatch.throwAwayInventory.m_inventory.FirstOrDefault(), InventoryGuiOnSplitOkPatch.throwAwayInventory);
				if (ZInput.GetKey((KeyCode)306, true) || ZInput.GetKey((KeyCode)305, true))
				{
					SplitDialog splitDialog = InventoryGui.instance.m_splitDialog;
					splitDialog.SliderValue = splitDialog.m_splitSlider.maxValue;
				}
				CurrencyPocket.CoinExtractionInProgress = true;
			}
		}

		internal static bool IsOverlappingUIModInstalled()
		{
			Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos;
			if (!pluginInfos.ContainsKey("goldenrevolver.quick_stack_store"))
			{
				return pluginInfos.ContainsKey("org.bepinex.plugins.jewelcrafting");
			}
			return true;
		}
	}
	public static class OttoPayApi
	{
		internal sealed class DepositHandler
		{
			internal string Name { get; }

			public DepositHandler(string name, Func<Inventory, ItemData, int, bool> canDeposit, Func<Inventory, ItemData, int, bool> deposit, Func<Inventory, ItemData, int, string> describe)
			{
				<canDeposit>P = canDeposit;
				<deposit>P = deposit;
				<describe>P = describe;
				Name = name;
				base..ctor();
			}

			internal bool CanDeposit(Inventory inventory, ItemData item, int amount)
			{
				return Call(() => <canDeposit>P(inventory, item, amount), fallback: false);
			}

			internal bool Deposit(Inventory inventory, ItemData item, int amount)
			{
				return Call(() => <deposit>P(inventory, item, amount), fallback: false);
			}

			internal string Describe(Inventory inventory, ItemData item, int amount)
			{
				return Call(() => <describe>P(inventory, item, amount), "") ?? "";
			}

			private T Call<T>(Func<T> callback, T fallback)
			{
				try
				{
					return callback();
				}
				catch (Exception ex)
				{
					if (_depositHandlerWarnedNames.Add(Name))
					{
						OttoPayPlugin.OttoPayLogger.LogWarning((object)("OttoPayApi: deposit handler '" + Name + "' threw: " + ex.Message));
					}
					return fallback;
				}
			}
		}

		private static readonly List<(string Name, Func<string> Describe)> _auraServices = new List<(string, Func<string>)>();

		private static readonly HashSet<string> _auraServiceWarnedNames = new HashSet<string>();

		private static readonly List<DepositHandler> _depositHandlers = new List<DepositHandler>();

		private static readonly HashSet<string> _depositHandlerWarnedNames = new HashSet<string>();

		public const string AuraPayCustomData = "OttoPay_AuraPay";

		public const string BankMemberCustomData = "OttoPay_BankMember";

		public static void RegisterAuraService(string name, Func<string> describe)
		{
			for (int i = 0; i < _auraServices.Count; i++)
			{
				if (_auraServices[i].Name == name)
				{
					_auraServices[i] = (name, describe);
					CurrencyPocket.UpdateAuraPayToggle();
					return;
				}
			}
			_auraServices.Add((name, describe));
			CurrencyPocket.UpdateAuraPayToggle();
		}

		public static void UnregisterAuraService(string name)
		{
			_auraServices.RemoveAll(((string Name, Func<string> Describe) s) => s.Name == name);
			CurrencyPocket.UpdateAuraPayToggle();
		}

		internal static IReadOnlyList<string> AuraServiceLines()
		{
			List<string> list = new List<string>();
			foreach (var (text, func) in _auraServices)
			{
				string text2;
				try
				{
					text2 = func();
				}
				catch (Exception ex)
				{
					if (_auraServiceWarnedNames.Add(text))
					{
						OttoPayPlugin.OttoPayLogger.LogWarning((object)("OttoPayApi: aura service '" + text + "' describe() threw: " + ex.Message));
					}
					continue;
				}
				if (!string.IsNullOrWhiteSpace(text2))
				{
					list.Add(text2.Trim());
				}
			}
			return list;
		}

		public static void RegisterDepositHandler(string name, Func<Inventory, ItemData, int, bool> canDeposit, Func<Inventory, ItemData, int, bool> deposit, Func<Inventory, ItemData, int, string> describe)
		{
			DepositHandler depositHandler = new DepositHandler(name, canDeposit, deposit, describe);
			int num = _depositHandlers.FindIndex((DepositHandler h) => h.Name == name);
			if (num >= 0)
			{
				_depositHandlers[num] = depositHandler;
			}
			else
			{
				_depositHandlers.Add(depositHandler);
			}
		}

		public static void UnregisterDepositHandler(string name)
		{
			_depositHandlers.RemoveAll((DepositHandler h) => h.Name == name);
		}

		internal static DepositHandler? AcceptingDepositHandler(Inventory inventory, ItemData item, int amount)
		{
			DepositHandler[] array = _depositHandlers.ToArray();
			foreach (DepositHandler depositHandler in array)
			{
				if (depositHandler.CanDeposit(inventory, item, amount))
				{
					return depositHandler;
				}
			}
			return null;
		}

		public static bool IsBankMember()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			if (localPlayer.m_customData.TryGetValue("OttoPay_BankMember", out var value) && value == "1")
			{
				return true;
			}
			return MiscFunctions.GetPlayerCoinsFromCustomData() > 0;
		}

		public static void JoinBank()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				localPlayer.m_customData["OttoPay_BankMember"] = "1";
				CurrencyPocket.UpdatePocketUI();
			}
		}

		public static int GetPouchCoins()
		{
			return MiscFunctions.GetPlayerCoinsFromCustomData();
		}

		public static bool IsAuraPayEnabled()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && IsBankMember() && localPlayer.m_customData.TryGetValue("OttoPay_AuraPay", out var value))
			{
				return value == "1";
			}
			return false;
		}

		public static void SetAuraPayEnabled(bool enabled)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				localPlayer.m_customData["OttoPay_AuraPay"] = (enabled ? "1" : "0");
				CurrencyPocket.UpdateAuraPayToggle();
			}
		}

		public static bool TryDeposit(int amount)
		{
			if (amount < 0 || !IsBankMember())
			{
				return false;
			}
			if (amount == 0)
			{
				return true;
			}
			int playerCoinsFromCustomData = MiscFunctions.GetPlayerCoinsFromCustomData();
			if (playerCoinsFromCustomData > int.MaxValue - amount)
			{
				return false;
			}
			MiscFunctions.UpdatePlayerCustomData(playerCoinsFromCustomData + amount);
			CurrencyPocket.UpdatePocketUI();
			return true;
		}

		public static bool TryWithdraw(int amount)
		{
			if (amount <= 0)
			{
				return true;
			}
			if (!IsBankMember())
			{
				return false;
			}
			int playerCoinsFromCustomData = MiscFunctions.GetPlayerCoinsFromCustomData();
			if (playerCoinsFromCustomData < amount)
			{
				return false;
			}
			MiscFunctions.UpdatePlayerCustomData(playerCoinsFromCustomData - amount);
			CurrencyPocket.UpdatePocketUI();
			return true;
		}
	}
	[BepInPlugin("potto007.OttoPay", "OttoPay", "1.6.2")]
	[BepInIncompatibility("Azumatt.CurrencyPocket")]
	public class OttoPayPlugin : BaseUnityPlugin
	{
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string? Category;

			[UsedImplicitly]
			public Action<ConfigEntryBase>? CustomDrawer;
		}

		internal const string ModName = "OttoPay";

		internal const string ModVersion = "1.6.2";

		internal const string Author = "potto007";

		private const string ModGUID = "potto007.OttoPay";

		private static string ConfigFileName = "potto007.OttoPay.cfg";

		private static string ConfigFileFullPath;

		internal readonly Harmony _harmony = new Harmony("potto007.OttoPay");

		public static readonly ManualLogSource OttoPayLogger;

		internal static Sprite DownloadSprite;

		public static OttoPayPlugin instance;

		private static readonly ConfigSync ConfigSync;

		private FileSystemWatcher _watcher;

		private readonly object _reloadLock = new object();

		private DateTime _lastConfigReloadTime;

		private const long RELOAD_DELAY = 10000000L;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		private static readonly MethodInfo? LoadImageMethod;

		public void Awake()
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			instance = this;
			_serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
			DownloadSprite = loadSprite("download.png");
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		public void Start()
		{
			RapidLoadoutsCompat.Init();
			ExtraSlotsCompat.FuckOff();
		}

		private void OnDestroy()
		{
			SaveWithRespectToConfigSet();
			_watcher?.Dispose();
		}

		private void SetupWatcher()
		{
			_watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			_watcher.Changed += ReadConfigValues;
			_watcher.Created += ReadConfigValues;
			_watcher.Renamed += ReadConfigValues;
			_watcher.IncludeSubdirectories = true;
			_watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			_watcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			DateTime now = DateTime.Now;
			if (now.Ticks - _lastConfigReloadTime.Ticks < 10000000)
			{
				return;
			}
			lock (_reloadLock)
			{
				if (!File.Exists(ConfigFileFullPath))
				{
					OttoPayLogger.LogWarning((object)"Config file does not exist. Skipping reload.");
					return;
				}
				try
				{
					OttoPayLogger.LogDebug((object)"Reloading configuration...");
					SaveWithRespectToConfigSet(reload: true);
					OttoPayLogger.LogInfo((object)"Configuration reload complete.");
				}
				catch (Exception ex)
				{
					OttoPayLogger.LogError((object)("Error reloading configuration: " + ex.Message));
				}
			}
			_lastConfigReloadTime = now;
		}

		private void SaveWithRespectToConfigSet(bool reload = false)
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			if (reload)
			{
				((BaseUnityPlugin)this).Config.Reload();
			}
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			if (LoadImageMethod == null)
			{
				OttoPayLogger.LogError((object)"UnityEngine.ImageConversion.LoadImage was not found. Textures will not load.");
				return val;
			}
			LoadImageMethod.Invoke(null, new object[2]
			{
				val,
				ReadEmbeddedFileBytes("assets." + name)
			});
			return val;
		}

		internal static Sprite loadSprite(string name)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = loadTexture(name);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero);
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting;
			return val2;
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		static OttoPayPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			OttoPayLogger = Logger.CreateLogSource("OttoPay");
			DownloadSprite = null;
			instance = null;
			ConfigSync = new ConfigSync("potto007.OttoPay")
			{
				DisplayName = "OttoPay",
				CurrentVersion = "1.6.2",
				MinimumRequiredVersion = "1.6.2",
				ModRequired = false
			};
			_serverConfigLocked = null;
			LoadImageMethod = AccessTools.Method("UnityEngine.ImageConversion:LoadImage", new Type[2]
			{
				typeof(Texture2D),
				typeof(byte[])
			}, (Type[])null);
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct Constants
	{
		public const string CoinPocketUIName = "CoinPocketUI";

		public const string ExtractCoinsButtonName = "ExtractCoinsButton";

		public const string AuraPayButtonName = "AuraPayToggleButton";

		public const string ArmorName = "Armor";

		public const string WeightName = "Weight";

		public const string JewelcraftingSynergyName = "Jewelcrafting Synergy";

		public const string TrashButtonName = "Trash";

		public const string FavoritingToggleButton = "favoritingTogglingButton";

		public const string QuickStackAreaButton = "quickStackAreaButton";

		public const string RestockAreaButton = "restockAreaButton";

		public const string SortInventoryButton = "sortInventoryButton";

		internal const string CoinCountCustomData = "CoinPocket_CoinCount";

		internal const string CoinIconName = "CoinIcon";

		internal const string CoinToken = "$item_coins";

		internal const string CoinsPrefabName = "Coins";

		internal const string AcText = "ac_text";

		internal const string ArmorIconName = "armor_icon";

		internal const string RandyQuickslots = "randyknapp.mods.equipmentandquickslots";

		internal const string AzuEPIGUID = "Azumatt.AzuExtendedPlayerInventory";

		internal const string QuickStackStoreGUID = "goldenrevolver.quick_stack_store";

		internal const string JewelcraftingGUID = "org.bepinex.plugins.jewelcrafting";

		internal const string RapidLoadoutsGUID = "Azumatt.RapidLoadouts";

		internal const string OttoAuraGUID = "potto007.OttoAura";

		internal const string ExtraSlotsGuid = "shudnal.ExtraSlots";

		internal const string EsSectionName = "Mods compatibility - Reduced inventory size";
	}
	public class PocketDrop : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerMoveHandler, IPointerExitHandler, IPointerClickHandler
	{
		private const string TooltipHostName = "OttoPayBalanceTooltip";

		private UITooltip? uiTooltip;

		internal static bool clicked;

		internal static Image armorImage;

		private Material? armorMaterial;

		private void Awake()
		{
			TryCreateTooltip();
			armorImage = ((Component)((Component)this).transform.Find("armor_icon")).GetComponent<Image>();
			armorMaterial = ((Graphic)armorImage).material;
		}

		private void Update()
		{
			ItemData val = DraggedItem();
			if (val == null || (!CanDeposit(val) && HandlerFor(val) == null))
			{
				if ((Object)(object)armorImage != (Object)null && (Object)(object)armorImage.sprite != (Object)(object)CurrencyPocket.InventoryGuiUpdatePatch.coinSprite)
				{
					armorImage.sprite = CurrencyPocket.InventoryGuiUpdatePatch.coinSprite;
					((Graphic)armorImage).material = armorMaterial;
				}
			}
			else if (!((Object)(object)armorImage.sprite == (Object)(object)OttoPayPlugin.DownloadSprite))
			{
				armorImage.sprite = OttoPayPlugin.DownloadSprite;
				((Graphic)armorImage).material = null;
			}
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			if (!OverChildButton(eventData))
			{
				ShowBalanceTooltip(eventData.pointerEnter);
			}
		}

		public void OnPointerMove(PointerEventData eventData)
		{
			if (!((Object)(object)UITooltip.m_current != (Object)null) && !OverChildButton(eventData))
			{
				ShowBalanceTooltip(eventData.pointerEnter);
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			if ((Object)(object)uiTooltip != (Object)null && (Object)(object)UITooltip.m_current == (Object)(object)uiTooltip)
			{
				UITooltip.HideTooltip();
			}
		}

		private bool OverChildButton(PointerEventData eventData)
		{
			GameObject pointerEnter = eventData.pointerEnter;
			if ((Object)(object)pointerEnter == (Object)null)
			{
				return false;
			}
			Button componentInParent = pointerEnter.GetComponentInParent<Button>();
			if ((Object)(object)componentInParent != (Object)null && (Object)(object)((Component)componentInParent).transform != (Object)(object)((Component)this).transform)
			{
				return ((Component)componentInParent).transform.IsChildOf(((Component)this).transform);
			}
			return false;
		}

		private void ShowBalanceTooltip(GameObject? hovered)
		{
			//IL_00ba: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			TryCreateTooltip();
			if (!Object.op_Implicit((Object)(object)InventoryGui.m_instance) || (Object)(object)uiTooltip == (Object)null)
			{
				return;
			}
			ItemData val = DraggedItem();
			if (val != null && CanDeposit(val))
			{
				uiTooltip.Set("Deposit coins", "Click to deposit these coins in your Merchant Bank balance.", (RectTransform)null, default(Vector2));
			}
			else
			{
				if (val != null)
				{
					OttoPayApi.DepositHandler depositHandler = HandlerFor(val);
					if (depositHandler != null)
					{
						uiTooltip.Set(depositHandler.Name, depositHandler.Describe(InventoryGui.m_instance.m_dragInventory, val, InventoryGui.m_instance.m_dragAmount), (RectTransform)null, default(Vector2));
						goto IL_00c6;
					}
				}
				uiTooltip.Set("Merchant Bank", $"Balance: {MiscFunctions.GetPlayerCoinsFromCustomData()} coins.\n\nDrop coins here to deposit them. Any merchant draws on your balance when you buy.", (RectTransform)null, default(Vector2));
			}
			goto IL_00c6;
			IL_00c6:
			uiTooltip.OnHoverStart((GameObject)(((Object)(object)hovered != (Object)null) ? ((object)hovered) : ((object)((Component)this).gameObject)));
		}

		public void OnPointerClick(PointerEventData eventData)
		{
			//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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			if (!Object.op_Implicit((Object)(object)InventoryGui.m_instance))
			{
				return;
			}
			InputButton button = eventData.button;
			if ((int)button != 0)
			{
				if ((int)button == 1)
				{
					OttoPayPlugin.OttoPayLogger.LogWarning((object)"Right clicked");
				}
			}
			else
			{
				if (!Object.op_Implicit((Object)(object)InventoryGui.m_instance.m_dragGo) || InventoryGui.m_instance.m_dragItem == null || InventoryGui.m_instance.m_dragInventory == null)
				{
					return;
				}
				ItemData dragItem = InventoryGui.m_instance.m_dragItem;
				if (!CanDeposit(dragItem))
				{
					OttoPayApi.DepositHandler depositHandler = HandlerFor(dragItem);
					if (depositHandler != null && depositHandler.Deposit(InventoryGui.m_instance.m_dragInventory, dragItem, InventoryGui.m_instance.m_dragAmount))
					{
						CurrencyPocket.UpdatePocketUI();
						InventoryGui.m_instance.SetupDragItem((ItemData)null, (Inventory)null, 1);
						InventoryGuiOnSplitOkPatch.throwAwayInventory = null;
					}
					return;
				}
				clicked = true;
				MiscFunctions.UpdatePlayerCustomData(MiscFunctions.GetPlayerCoinsFromCustomData() + InventoryGui.m_instance.m_dragAmount);
				CurrencyPocket.UpdatePocketUI();
				if (InventoryGui.m_instance.m_dragAmount == InventoryGui.m_instance.m_dragItem.m_stack)
				{
					InventoryGui.m_instance.m_dragInventory.RemoveItem(InventoryGui.m_instance.m_dragItem);
				}
				else
				{
					InventoryGui.m_instance.m_dragInventory.RemoveItem(InventoryGui.m_instance.m_dragItem, InventoryGui.m_instance.m_dragAmount);
				}
				clicked = false;
				InventoryGui.m_instance.SetupDragItem((ItemData)null, (Inventory)null, 1);
				InventoryGuiOnSplitOkPatch.throwAwayInventory = null;
			}
		}

		private static ItemData? DraggedItem()
		{
			if (!Object.op_Implicit((Object)(object)InventoryGui.m_instance) || !Object.op_Implicit((Object)(object)InventoryGui.m_instance.m_dragGo))
			{
				return null;
			}
			return InventoryGui.m_instance.m_dragItem;
		}

		private static bool CanDeposit(ItemData item)
		{
			return item.m_shared.m_name == "$item_coins";
		}

		private static OttoPayApi.DepositHandler? HandlerFor(ItemData item)
		{
			Inventory val = (Object.op_Implicit((Object)(object)InventoryGui.m_instance) ? InventoryGui.m_instance.m_dragInventory : null);
			if (val == null || CanDeposit(item))
			{
				return null;
			}
			return OttoPayApi.AcceptingDepositHandler(val, item, InventoryGui.m_instance.m_dragAmount);
		}

		private void TryCreateTooltip()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			if (!((Object)(object)uiTooltip != (Object)null))
			{
				GameObject val = new GameObject("OttoPayBalanceTooltip", new Type[1] { typeof(RectTransform) });
				val.transform.SetParent(((Component)this).transform, false);
				uiTooltip = Tooltips.Attach(val, "", "");
				if ((Object)(object)uiTooltip == (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}
	}
	internal static class Tooltips
	{
		private static GameObject? _prefab;

		internal static GameObject? Prefab()
		{
			if ((Object)(object)_prefab != (Object)null)
			{
				return _prefab;
			}
			InventoryGrid val = (((Object)(object)InventoryGui.instance != (Object)null) ? InventoryGui.instance.m_playerGrid : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			UITooltip val2 = (((Object)(object)val.m_elementPrefab != (Object)null) ? val.m_elementPrefab.GetComponentInChildren<UITooltip>(true) : null);
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.m_tooltipPrefab == (Object)null)
			{
				val2 = val.m_elements.FirstOrDefault()?.m_tooltip;
			}
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.m_tooltipPrefab == (Object)null)
			{
				return null;
			}
			_prefab = val2.m_tooltipPrefab;
			OttoPayPlugin.OttoPayLogger.LogInfo((object)("Tooltips use the '" + ((Object)_prefab).name + "' prefab."));
			return _prefab;
		}

		internal static void Strip(GameObject root)
		{
			UITooltip[] componentsInChildren = root.GetComponentsInChildren<UITooltip>(true);
			foreach (UITooltip val in componentsInChildren)
			{
				OttoPayPlugin.OttoPayLogger.LogInfo((object)("Removed cloned tooltip on '" + ((Object)val).name + "' (prefab '" + (((Object)(object)val.m_tooltipPrefab != (Object)null) ? ((Object)val.m_tooltipPrefab).name : "none") + "')."));
				Object.DestroyImmediate((Object)(object)val);
			}
		}

		internal static UITooltip? Attach(GameObject? target, string topic, string text)
		{
			if ((Object)(object)target == (Object)null)
			{
				return null;
			}
			GameObject val = Prefab();
			if ((Object)(object)val == (Object)null)
			{
				OttoPayPlugin.OttoPayLogger.LogWarning((object)("No tooltip prefab found yet, so '" + topic + "' has no tooltip."));
				return null;
			}
			UITooltip obj = target.GetComponent<UITooltip>() ?? target.AddComponent<UITooltip>();
			obj.m_tooltipPrefab = val;
			obj.m_topic = topic;
			obj.m_text = text;
			return obj;
		}
	}
}
namespace OttoPay.Compatibility
{
	internal static class ExtraSlotsCompat
	{
		private static bool _handlingChange;

		public static void FuckOff()
		{
			if (Chainloader.PluginInfos.TryGetValue("shudnal.ExtraSlots", out var value))
			{
				ConfigFile config = value.Instance.Config;
				if ((0u | (AttachSanitizer(config, "Panels to show with 1 row", 1) ? 1u : 0u) | (AttachSanitizer(config, "Panels to show with 2 rows", 2) ? 1u : 0u) | (AttachSanitizer(config, "Panels to show with 3 rows", 3) ? 1u : 0u)) != 0)
				{
					config.Save();
				}
			}
		}

		private static bool AttachSanitizer(ConfigFile cfg, string key, int? maxAllowedItems)
		{
			ConfigEntry<string> entry = default(ConfigEntry<string>);
			if (!cfg.TryGetEntry<string>("Mods compatibility - Reduced inventory size", key, ref entry))
			{
				return false;
			}
			bool result = SanitizeEntry(entry, maxAllowedItems);
			entry.SettingChanged += delegate
			{
				if (_handlingChange)
				{
					return;
				}
				try
				{
					_handlingChange = true;
					SanitizeEntry(entry, maxAllowedItems);
				}
				finally
				{
					_handlingChange = false;
				}
			};
			return result;
		}

		private static bool SanitizeEntry(ConfigEntry<string> entry, int? maxAllowedItems)
		{
			string text = entry.Value ?? string.Empty;
			if (maxAllowedItems == 1 && text.Trim().Equals("CoinPocketUI", StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			string text2 = SanitizeCsv(text, "CoinPocketUI", maxAllowedItems);
			if (text2 == text)
			{
				return false;
			}
			entry.Value = text2;
			return true;
		}

		private static string SanitizeCsv(string csv, string targetEntry, int? maxAllowedItems)
		{
			if (string.IsNullOrWhiteSpace(csv))
			{
				return string.Empty;
			}
			string[] array = csv.Split(new char[1] { ',' });
			int num = 0;
			for (int i = 0; i < array.Length; i++)
			{
				if (!string.IsNullOrWhiteSpace(array[i]))
				{
					num++;
				}
			}
			if (num <= maxAllowedItems)
			{
				return csv;
			}
			List<string> list = new List<string>(array.Length);
			bool flag = false;
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text.Trim().Equals(targetEntry, StringComparison.OrdinalIgnoreCase))
				{
					flag = true;
				}
				else
				{
					list.Add(text);
				}
			}
			if (!flag)
			{
				return csv;
			}
			if (list.Count != 0)
			{
				return string.Join(",", list);
			}
			return string.Empty;
		}
	}
	public class RapidLoadoutsCompat
	{
		public static void Init()
		{
			if (Chainloader.PluginInfos.TryGetValue("Azumatt.RapidLoadouts", out var value) && value != null && Object.op_Implicit((Object)(object)value.Instance))
			{
				OttoPayPlugin.instance._harmony.PatchAll(typeof(RapidLoadoutsCompat));
			}
		}

		[HarmonyPatch("RapidLoadouts.UI.PurchasableLoadoutGui, RapidLoadouts", "GetPlayerCoins")]
		[HarmonyPostfix]
		public static void GetPlayerCoins(ref int __result, ref ItemDrop ___m_coinPrefab)
		{
			if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && !((Object)(object)___m_coinPrefab == (Object)null) && ___m_coinPrefab.m_itemData.m_shared.m_name == "$item_coins" && OttoPayApi.IsBankMember())
			{
				__result += (Player.m_localPlayer.m_customData.TryGetValue("CoinPocket_CoinCount", out var value) ? int.Parse(value) : 0);
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }));
							}).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend > 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0052:
				result = 0;
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers