Decompiled source of DLCTweaks v1.5.9

plugins/DLCTweaks/DarklightCreations.DLCTweaks.dll

Decompiled 3 hours ago
using System;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DvergrQuartermaster;
using Fred.FieldArtillery;
using FreddieQoL;
using GUIFramework;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using SoftReferenceableAssets;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DarklightCreations.DLCTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DarklightCreations.DLCTweaks")]
[assembly: AssemblyTitle("DarklightCreations.DLCTweaks")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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;
		}
	}
}
internal sealed class QuartermasterGamepadFocus
{
	private readonly GuiInputField search;

	private readonly Selectable controls;

	private readonly string placeholderText;

	private readonly string controlsHint;

	private readonly string controlsBinding;

	private readonly bool searchShortcut;

	private bool showedControllerHint;

	private bool editing;

	private GameObject previousSelection;

	internal bool Active { get; private set; }

	internal QuartermasterGamepadFocus(GuiInputField search, Selectable controls, string placeholderText, string controlsHint, string controlsBinding = null, bool searchShortcut = true)
	{
		this.search = search;
		this.controls = controls;
		this.placeholderText = placeholderText;
		this.controlsHint = controlsHint;
		this.controlsBinding = controlsBinding;
		this.searchShortcut = searchShortcut;
	}

	internal void Update(Action enter, Action<GameObject> leave, Func<bool> cancelChoices)
	{
		if (!Object.op_Implicit((Object)(object)EventSystem.current) || !((Component)search).gameObject.activeInHierarchy)
		{
			return;
		}
		bool flag = ZInput.IsExclusiveGamepadActive() && !ZInput.IsTouchActive();
		if (showedControllerHint != flag)
		{
			showedControllerHint = flag;
			Graphic placeholder = ((TMP_InputField)search).placeholder;
			TMP_Text val = (TMP_Text)(object)((placeholder is TMP_Text) ? placeholder : null);
			if (val != null)
			{
				string text = ZInput.instance.GetBoundKeyString(controlsHint, true) + " Controls";
				val.text = ((!flag) ? placeholderText : (searchShortcut ? (ZInput.instance.GetBoundKeyString("JoyLStick", true) + " Search  " + text) : text));
			}
		}
		if (Active && ((TMP_InputField)search).isFocused)
		{
			editing = true;
		}
		if (ZInput.VirtualKeyboardOpen || UnifiedPopup.IsVisible() || Console.IsVisible() || Menu.IsVisible())
		{
			return;
		}
		if (Active && ZInput.GetButtonDown("JoyButtonB"))
		{
			ZInput.ResetButtonStatus("JoyButtonB");
			if (!cancelChoices())
			{
				if (editing || ((TMP_InputField)search).isFocused)
				{
					ReturnToControls();
				}
				else
				{
					Release(leave);
				}
			}
		}
		else
		{
			if (!flag)
			{
				return;
			}
			bool flag2 = searchShortcut && ZInput.GetButtonDown("JoyLStick");
			if (flag2 || (controlsBinding != null && ZInput.GetButtonDown(controlsBinding)))
			{
				EnterControls(enter, cancelChoices);
				if (flag2)
				{
					editing = true;
					Select((Selectable)(object)search);
					search.OpenKeyboard();
				}
			}
		}
	}

	internal void EnterControls(Action enter, Func<bool> cancelChoices)
	{
		EventSystem current = EventSystem.current;
		if (Object.op_Implicit((Object)(object)current) && ((Component)search).gameObject.activeInHierarchy)
		{
			if (!Active)
			{
				previousSelection = current.currentSelectedGameObject;
				Active = true;
				enter?.Invoke();
			}
			cancelChoices();
			ReturnToControls();
		}
	}

	internal void Release(Action<GameObject> leave = null)
	{
		if (Active)
		{
			Active = false;
			editing = false;
			((TMP_InputField)search).DeactivateInputField(false);
			search.ToggleEventSystemNavigation(true);
			EventSystem current = EventSystem.current;
			if (Object.op_Implicit((Object)(object)current) && !current.alreadySelecting)
			{
				current.SetSelectedGameObject((GameObject)null);
			}
			leave?.Invoke(previousSelection);
			previousSelection = null;
		}
	}

	private void ReturnToControls()
	{
		editing = false;
		((TMP_InputField)search).DeactivateInputField(false);
		search.ToggleEventSystemNavigation(true);
		Select(controls);
	}

	internal static void Select(Selectable target)
	{
		EventSystem current = EventSystem.current;
		if (Object.op_Implicit((Object)(object)current) && !current.alreadySelecting && CanNavigateTo(target))
		{
			current.SetSelectedGameObject(((Component)target).gameObject);
		}
	}

	internal static bool Available(Selectable target)
	{
		if (Object.op_Implicit((Object)(object)target) && ((Behaviour)target).isActiveAndEnabled)
		{
			return target.IsInteractable();
		}
		return false;
	}

	internal static void RemoveTemplateHotkey(Selectable clone)
	{
		UIGamePad component = ((Component)clone).GetComponent<UIGamePad>();
		if (Object.op_Implicit((Object)(object)component))
		{
			((Behaviour)component).enabled = false;
			if (Object.op_Implicit((Object)(object)component.m_hint) && component.m_hint.transform.IsChildOf(((Component)clone).transform))
			{
				component.m_hint.SetActive(false);
			}
			Object.Destroy((Object)(object)component);
		}
	}

	private static bool CanNavigateTo(Selectable target)
	{
		if (Object.op_Implicit((Object)(object)target) && ((Behaviour)target).isActiveAndEnabled)
		{
			return target.interactable;
		}
		return false;
	}

	internal static void SetNavigation(Selectable target, Selectable left = null, Selectable right = null, Selectable up = null, Selectable down = null)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		Navigation navigation = default(Navigation);
		((Navigation)(ref navigation)).mode = (Mode)4;
		((Navigation)(ref navigation)).selectOnLeft = (CanNavigateTo(left) ? left : null);
		((Navigation)(ref navigation)).selectOnRight = (CanNavigateTo(right) ? right : null);
		((Navigation)(ref navigation)).selectOnUp = (CanNavigateTo(up) ? up : null);
		((Navigation)(ref navigation)).selectOnDown = (CanNavigateTo(down) ? down : null);
		target.navigation = navigation;
	}
}
[BepInPlugin("fred.dvergrquartermaster", "Dvergr Banker", "0.4.65")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
public sealed class QuartermasterPlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(SaveSystem), "CheckMove")]
	private static class SkipLocalCharacterMigrationCheck
	{
		private static bool Prepare()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return Version.CurrentVersion == new GameVersion(1, 0, 31);
		}

		private static bool Prefix(string saveName, SaveDataType dataType, FileSource source, ref bool __result)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			if (savingHostProfile == null || saveName != savingHostProfile.GetFilename() || (int)dataType != 1 || (int)source != 2 || !FileHelpers.LocalStorageSupportedAndAllowed)
			{
				return true;
			}
			__result = false;
			return false;
		}
	}

	[HarmonyPatch(typeof(PlayerProfile), "SavePlayerData")]
	private static class RecordNativeVaultTransfer
	{
		private static void Prefix(PlayerProfile __instance, Player player)
		{
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)player) && (Object)(object)instance.vaultEditor == (Object)(object)player && instance.dirty)
			{
				try
				{
					instance.PrepareHostTransfer(__instance, player);
				}
				catch (Exception error)
				{
					instance.ReportPendingVault(error);
					throw;
				}
			}
		}
	}

	[HarmonyPatch(typeof(PlayerProfile), "Save")]
	private static class CommitNativeVaultTransfer
	{
		private static void Postfix(PlayerProfile __instance, bool __result)
		{
			HostVaultTransfer hostVaultTransfer = (Object.op_Implicit((Object)(object)instance) ? instance.hostTransfer : null);
			if (!__result || hostVaultTransfer == null || instance.recoveringHostTransfer || __instance.GetPlayerID() != hostVaultTransfer.Actor || __instance.GetFilename() != hostVaultTransfer.Profile)
			{
				return;
			}
			try
			{
				instance.FinishHostTransfer(__instance, replay: false);
			}
			catch (Exception error)
			{
				instance.ReportPendingVault(error);
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "SaveWorld")]
	private static class KeepWorldSaveAfterHostTransfer
	{
		private static bool Prefix(ZNet __instance)
		{
			if (Object.op_Implicit((Object)(object)instance) && (instance.hostTransfer != null || instance.HasHostEdit) && instance.IsLoadedWorld(__instance.GetWorldUID()))
			{
				return instance.Flush();
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(Inventory), "TopFirst")]
	private static class FillVaultFromTop
	{
		private static bool Prefix(Inventory __instance, ref bool __result)
		{
			if (!Object.op_Implicit((Object)(object)instance) || __instance != instance.vault)
			{
				return true;
			}
			__result = true;
			return false;
		}
	}

	[HarmonyPatch(typeof(Container), "Awake")]
	private static class SkipPhysicalContainer
	{
		private static bool Prefix(Container __instance)
		{
			return !IsQuartermaster(__instance);
		}
	}

	[HarmonyPatch(typeof(Container), "GetInventory")]
	private static class SupplyVirtualInventory
	{
		private static bool Prefix(Container __instance, ref Inventory __result)
		{
			if (!IsQuartermaster(__instance))
			{
				return true;
			}
			__result = (IsRemoteContainer(__instance) ? SharedVaultLink.Snapshot : instance.vault);
			return false;
		}
	}

	[HarmonyPatch(typeof(Container), "IsOwner")]
	private static class AllowLocalInventory
	{
		private static bool Prefix(Container __instance, ref bool __result)
		{
			if (!IsQuartermaster(__instance))
			{
				return true;
			}
			__result = IsRemoteContainer(__instance) || (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.active) && (Object)(object)((Component)instance.active).gameObject == (Object)(object)((Component)__instance).gameObject);
			return false;
		}
	}

	[HarmonyPatch(typeof(Container), "SetInUse")]
	private static class CloseBankView
	{
		private static bool Prefix(Container __instance, bool inUse)
		{
			if (!IsQuartermaster(__instance))
			{
				return true;
			}
			if (!inUse && IsRemoteContainer(__instance))
			{
				SharedVaultLink.CloseRemoteBank();
				QuartermasterSearch.Close(__instance);
				InventoryGui instance = InventoryGui.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					((Selectable)instance.m_takeAllButton).interactable = QuartermasterPlugin.instance.oldTakeAll;
					((Selectable)instance.m_stackAllButton).interactable = QuartermasterPlugin.instance.oldStackAll;
				}
				QuartermasterPlugin.instance.remoteContainer = null;
			}
			if (!inUse && Object.op_Implicit((Object)(object)QuartermasterPlugin.instance) && Object.op_Implicit((Object)(object)QuartermasterPlugin.instance.active) && (Object)(object)((Component)QuartermasterPlugin.instance.active).gameObject == (Object)(object)((Component)__instance).gameObject)
			{
				QuartermasterSearch.Close(__instance);
				if (Time.unscaledTime >= QuartermasterPlugin.instance.nextSaveAttempt)
				{
					QuartermasterPlugin.instance.Flush();
				}
				QuartermasterPlugin.instance.active = null;
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Show")]
	private static class ReleaseBankWhenSwitchingContainers
	{
		private static void Prefix(Container container, Container ___m_currentContainer)
		{
			if (Object.op_Implicit((Object)(object)___m_currentContainer) && (Object)(object)___m_currentContainer != (Object)(object)container && IsQuartermaster(___m_currentContainer))
			{
				___m_currentContainer.SetInUse(false);
			}
		}
	}

	[HarmonyPatch(typeof(Container), "StackAll")]
	private static class StackIntoVirtualStorage
	{
		private static bool Prefix(Container __instance)
		{
			if (!IsQuartermaster(__instance))
			{
				return true;
			}
			if (IsRemoteContainer(__instance))
			{
				SharedVaultLink.RunRemoteBulk(InventoryGui.instance, __instance, takeAll: false);
			}
			else if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && !QuartermasterSearch.HasFilter(__instance))
			{
				instance.vault.StackAll(((Humanoid)Player.m_localPlayer).GetInventory(), true);
			}
			return false;
		}
	}

	[CompilerGenerated]
	private static class <>O
	{
		public static PopupButtonCallback <0>__Pop;
	}

	public const string Id = "fred.dvergrquartermaster";

	internal const int SlotsPerTier = 24;

	internal const int UpgradeCost = 250;

	private static QuartermasterPlugin instance;

	private QuartermasterPiece active;

	private Container remoteContainer;

	private bool oldTakeAll;

	private bool oldStackAll;

	private static readonly Lazy<Func<int>> GetVisibleEquipmentRows = new Lazy<Func<int>>(delegate
	{
		if (!Chainloader.PluginInfos.TryGetValue("randyknapp.mods.equipmentandquickslots", out var value))
		{
			return (Func<int>)null;
		}
		MethodInfo methodInfo = ((object)value.Instance).GetType().Assembly.GetType("EquipmentAndQuickSlots.API")?.GetMethod("GetVisibleRows", Type.EmptyTypes);
		return (!(methodInfo != null) || !methodInfo.IsStatic || !(methodInfo.ReturnType == typeof(int))) ? null : ((Func<int>)Delegate.CreateDelegate(typeof(Func<int>), methodInfo));
	});

	private Inventory vault;

	private BankVaultPages bankPages;

	private int vaultPage;

	private SaveFileCheckpoint vaultSave;

	private int tier;

	private Dictionary<string, SharedVaultReceipt> pendingWithdrawals = new Dictionary<string, SharedVaultReceipt>();

	private Dictionary<string, (long Sequence, Guid Id, VaultTransferOutcome Outcome)> depositReceipts = new Dictionary<string, (long, Guid, VaultTransferOutcome)>();

	private Dictionary<string, VaultOwnerSave> ownerSaves = new Dictionary<string, VaultOwnerSave>();

	private bool dirty;

	private Player vaultEditor;

	private HostVaultTransfer hostTransfer;

	private bool recoveringHostTransfer;

	private bool hostCharacterSaved;

	[ThreadStatic]
	private static PlayerProfile savingHostProfile;

	private long? loadedWorldId;

	private ZoneSystem loadedWorldScene;

	private float nextSaveAttempt;

	internal static bool RemoteVaultOpen
	{
		get
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				return Object.op_Implicit((Object)(object)instance.remoteContainer);
			}
			return false;
		}
	}

	internal static bool HostBankOpen
	{
		get
		{
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.active) && Object.op_Implicit((Object)(object)InventoryGui.instance))
			{
				return InventoryGui.instance.IsContainerOpen();
			}
			return false;
		}
	}

	private bool HasHostEdit => vaultEditor != null;

	internal static bool IsRemoteContainer(Container container)
	{
		if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.remoteContainer))
		{
			return (Object)(object)instance.remoteContainer == (Object)(object)container;
		}
		return false;
	}

	internal static bool IsOpenHostedVaultInventory(Inventory inventory)
	{
		if (inventory != null && Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.active))
		{
			return inventory == instance.vault;
		}
		return false;
	}

	internal static int TransferRows(Inventory inventory)
	{
		int height = inventory.GetHeight();
		Player localPlayer = Player.m_localPlayer;
		if (!Object.op_Implicit((Object)(object)localPlayer) || ((Humanoid)localPlayer).GetInventory() != inventory)
		{
			return height;
		}
		int num = GetVisibleEquipmentRows.Value?.Invoke() ?? height;
		if (num <= 0)
		{
			return height;
		}
		return Math.Min(num, height);
	}

	internal static bool SettleHostedVaultBeforeExport()
	{
		if (!Object.op_Implicit((Object)(object)instance) || (instance.hostTransfer == null && !instance.HasHostEdit) || !CanUseAuthoritativeWorld() || !instance.IsLoadedWorld(ZNet.instance.GetWorld()?.m_uid))
		{
			return true;
		}
		if (Time.unscaledTime >= instance.nextSaveAttempt)
		{
			return instance.Flush();
		}
		Player localPlayer = Player.m_localPlayer;
		if (localPlayer != null)
		{
			((Character)localPlayer).Message((MessageType)2, "Bank storage has not saved. The transfer is pending.", 0, (Sprite)null, false);
		}
		return false;
	}

	internal static void OpenSharedVault(QuartermasterPiece piece)
	{
		InventoryGui val = InventoryGui.instance;
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)piece) || !Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer())
		{
			return;
		}
		Container val2 = BankInventoryView(piece);
		if (IsRemoteContainer(val2))
		{
			if (val.ContainerGrid.GetInventory() != SharedVaultLink.Snapshot)
			{
				RefreshBankGrid(val, SharedVaultLink.Snapshot);
			}
			return;
		}
		val.Hide();
		instance.remoteContainer = val2;
		instance.oldTakeAll = ((Selectable)val.m_takeAllButton).interactable;
		instance.oldStackAll = ((Selectable)val.m_stackAllButton).interactable;
		val.Show(val2, 1);
		QuartermasterSearch.Open(val, val2);
		piece.PlayVoice();
	}

	internal static (int Page, int Pages) VisibleBankPages()
	{
		if (RemoteVaultOpen)
		{
			return (Page: SharedVaultLink.SnapshotPage, Pages: BankCapacity.PageCount(SharedVaultLink.SnapshotTier));
		}
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)instance.active))
		{
			return default((int, int));
		}
		return (Page: instance.vaultPage, Pages: BankCapacity.PageCount(instance.tier));
	}

	internal static void TurnBankPage(int step, Func<ItemData, bool> matches = null)
	{
		(int Page, int Pages) tuple = VisibleBankPages();
		int item = tuple.Page;
		int item2 = tuple.Pages;
		int num = item + step;
		if (num < 0 || num >= item2 || !Object.op_Implicit((Object)(object)InventoryGui.instance) || !InventoryGui.instance.IsContainerOpen())
		{
			return;
		}
		if (RemoteVaultOpen)
		{
			if (matches == null)
			{
				SharedVaultLink.TurnBankPage(num);
			}
			else
			{
				SharedVaultLink.FindBankPage(item, step, matches);
			}
			return;
		}
		try
		{
			instance.EnsureVault();
			if (matches != null)
			{
				Dictionary<SharedData, bool> evaluated = new Dictionary<SharedData, bool>();
				num = instance.bankPages.FindMatchingPage(item, step, delegate(ItemData val)
				{
					if (!evaluated.TryGetValue(val.m_shared, out var value))
					{
						evaluated.Add(val.m_shared, value = matches(val));
					}
					return value;
				});
				if (num == item)
				{
					QuartermasterSearch.ShowPageSearchMiss(step);
					return;
				}
			}
			instance.vault = instance.GetBankPage(num);
			instance.vaultPage = num;
			RefreshBankGrid(InventoryGui.instance, instance.vault);
		}
		catch (Exception error)
		{
			instance.ReportPendingVault(error);
		}
	}

	private static void RefreshBankGrid(InventoryGui gui, Inventory page)
	{
		SharedVaultLink.CancelNativeDrag(gui);
		gui.ContainerGrid.UpdateInventory(page, (Player)null, (ItemData)null);
	}

	private void Awake()
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		instance = this;
		PrefabManager.OnVanillaPrefabsAvailable += RegisterPiece;
		Harmony val = new Harmony("fred.dvergrquartermaster");
		Type[] types = typeof(QuartermasterPlugin).Assembly.GetTypes();
		foreach (Type type in types)
		{
			if ((type.Namespace == typeof(BankCapacity).Namespace || type.DeclaringType == typeof(QuartermasterPlugin) || type.DeclaringType == typeof(QuartermasterSearch)) && type.IsDefined(typeof(HarmonyPatch), inherit: false))
			{
				val.CreateClassProcessor(type).Patch();
			}
		}
	}

	private void OnDestroy()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		PrefabManager.OnVanillaPrefabsAvailable -= RegisterPiece;
		new Harmony("fred.dvergrquartermaster").UnpatchSelf();
		instance = null;
	}

	private void RegisterPiece()
	{
		PrefabManager.OnVanillaPrefabsAvailable -= RegisterPiece;
		RegisterDvergrPiece("Fred_DvergrQuartermaster", "Dvergr Banker", "Access the shared inventory bank.", delegate(GameObject prefab)
		{
			prefab.AddComponent<QuartermasterPiece>();
		});
		RegisterDvergrPiece("Fred_DvergrCropMerchant", "Crop Merchant", "Sell crops, raw livestock goods, hides and treasure. Buy seeds you have found.", delegate(GameObject prefab)
		{
			DvergrMerchant.Attach(prefab, DvergrMerchant.Shop.Crops);
		});
		RegisterDvergrPiece("Fred_DvergrTrophyMerchant", "Trophy Merchant", "Sell trophies and treasure.", delegate(GameObject prefab)
		{
			DvergrMerchant.Attach(prefab, DvergrMerchant.Shop.Trophies);
		});
		RegisterDvergrPiece("Fred_DvergrGoodsMerchant", "Goods Merchant", "Buy wood, stone and metal.", delegate(GameObject prefab)
		{
			DvergrMerchant.Attach(prefab, DvergrMerchant.Shop.Goods);
		});
		RegisterCraftingDvergr("Fred_DvergrCrafter", "Dvergr Crafter", "piece_workbench", "Workbench", 250);
		RegisterCraftingDvergr("Fred_DvergrSmith", "Dvergr Smith", "forge", "Forge", 500);
		RegisterCraftingDvergr("Fred_DvergrMasterSmith", "Dvergr Master Smith", "blackforge", "Black Forge", 1000);
	}

	private void RegisterCraftingDvergr(string prefabName, string name, string nativePrefab, string stationName, int price)
	{
		GameObject prefab = PrefabManager.Instance.GetPrefab(nativePrefab);
		CraftingStation val = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<CraftingStation>() : null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Cannot register " + name + ". Missing Valheim crafting station " + nativePrefab + "."));
		}
		else
		{
			int maximum = 1 + DvergrCrafting.RegisterLegacyUpgrades(val, name);
			RegisterDvergrPiece(prefabName, name, "Craft and repair at a " + stationName + ". Offer Coins to upgrade.", delegate(GameObject prefab2)
			{
				DvergrCrafting.Attach(prefab2, maximum);
			}, price, "Crafting", nativePrefab);
		}
	}

	private void RegisterDvergrPiece(string prefabName, string name, string description, Action<GameObject> attach, int price = 250, string category = "Furniture", string sourcePrefab = "sign")
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		//IL_0248: Invalid comparison between Unknown and I4
		PieceConfig val = new PieceConfig
		{
			Name = name,
			Description = description,
			PieceTable = "Hammer",
			Category = category
		};
		val.AddRequirement("Coins", price, false);
		CustomPiece val2 = new CustomPiece(prefabName, sourcePrefab, val);
		GameObject piecePrefab = val2.PiecePrefab;
		piecePrefab.AddComponent<DvergrBuildInvestment>();
		Piece component = piecePrefab.GetComponent<Piece>();
		component.m_craftingStation = null;
		component.m_onlyInBiome = (Biome)0;
		component.m_groundPiece = false;
		component.m_groundOnly = false;
		component.m_cultivatedGroundOnly = false;
		component.m_notOnFloor = false;
		component.m_allowedInDungeons = true;
		Sign component2 = piecePrefab.GetComponent<Sign>();
		if (Object.op_Implicit((Object)(object)component2))
		{
			Object.DestroyImmediate((Object)(object)component2);
		}
		GameObject prefab = PrefabManager.Instance.GetPrefab("Dverger");
		QuartermasterPiece.Voice = ((!Object.op_Implicit((Object)(object)prefab)) ? null : prefab.GetComponent<BaseAI>()?.m_idleSound);
		Animator val3 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponentInChildren<Animator>(true) : null);
		if (Object.op_Implicit((Object)(object)val3) && (Object)(object)((Component)val3).gameObject != (Object)(object)prefab)
		{
			GameObject val4 = Object.Instantiate<GameObject>(((Component)val3).gameObject, piecePrefab.transform, false);
			val4.transform.localPosition = Vector3.zero;
			val4.transform.localRotation = Quaternion.identity;
			MonoBehaviour[] componentsInChildren = val4.GetComponentsInChildren<MonoBehaviour>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			Collider[] componentsInChildren2 = val4.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			Renderer[] componentsInChildren3 = piecePrefab.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val5 in componentsInChildren3)
			{
				if (!((Component)val5).transform.IsChildOf(val4.transform))
				{
					val5.enabled = false;
				}
			}
			if (sourcePrefab != "sign")
			{
				componentsInChildren2 = piecePrefab.GetComponentsInChildren<Collider>(true);
				foreach (Collider val6 in componentsInChildren2)
				{
					if (!val6.isTrigger)
					{
						val6.enabled = false;
					}
				}
			}
			BoxCollider obj = piecePrefab.AddComponent<BoxCollider>();
			obj.center = new Vector3(0f, 0.75f, 0f);
			obj.size = new Vector3(0.65f, 1.5f, 0.65f);
			if ((int)SystemInfo.graphicsDeviceType != 4)
			{
				RenderHammerIcon(piecePrefab.GetComponent<Piece>(), val4);
			}
		}
		attach(piecePrefab);
		PieceManager.Instance.AddPiece(val2);
	}

	private void RenderHammerIcon(Piece piece, GameObject visual)
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = Object.Instantiate<GameObject>(visual);
		try
		{
			Animator componentInChildren = val.GetComponentInChildren<Animator>(true);
			componentInChildren.cullingMode = (AnimatorCullingMode)0;
			componentInChildren.Rebind();
			componentInChildren.Update(0f);
			DvergrPresentation.Stand(componentInChildren);
			DvergrPresentation.MaintainIdlePose(componentInChildren);
			componentInChildren.Update(0.25f);
			Sprite val2 = RenderManager.Instance.Render(val, Quaternion.Euler(4f, -22f, 0f));
			if (Object.op_Implicit((Object)(object)val2))
			{
				piece.m_icon = val2;
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Unable to render the Quartermaster's Hammer icon: " + ex.Message));
		}
		finally
		{
			Object.DestroyImmediate((Object)(object)val);
		}
	}

	internal static bool CanUseAuthoritativeWorld()
	{
		if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
		{
			return !ZNet.instance.IsDedicated();
		}
		return false;
	}

	internal static bool CanUseLocalWorld()
	{
		if (CanUseAuthoritativeWorld() && !ZNet.IsOpenServer())
		{
			return ZNet.instance.GetPeers().Count == 0;
		}
		return false;
	}

	internal static bool Open(QuartermasterPiece piece, Humanoid user, bool quoteUpgrade = false)
	{
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Expected O, but got Unknown
		if (!Object.op_Implicit((Object)(object)instance) || (Object)(object)user != (Object)(object)Player.m_localPlayer || !Object.op_Implicit((Object)(object)ZNet.instance) || !Object.op_Implicit((Object)(object)InventoryGui.instance))
		{
			return false;
		}
		if (!CanUseAuthoritativeWorld())
		{
			if (!ZNet.instance.IsServer() && SharedVaultLink.Request(piece, quoteUpgrade))
			{
				return true;
			}
			((Character)user).Message((MessageType)2, "Shared vault data is unavailable.", 0, (Sprite)null, false);
			return true;
		}
		if (SharedVaultLink.HasRemoteBankUser())
		{
			((Character)user).Message((MessageType)2, "The bank is in use.", 0, (Sprite)null, false);
			return true;
		}
		try
		{
			instance.EnsureVault();
			Container val = BankInventoryView(piece);
			if (Object.op_Implicit((Object)(object)instance.active) && (Object)(object)instance.active != (Object)(object)piece)
			{
				InventoryGui.instance.Hide();
			}
			if (!Object.op_Implicit((Object)(object)instance.active))
			{
				instance.vault = instance.GetBankPage(0);
				instance.vaultPage = 0;
			}
			instance.active = piece;
			InventoryGui.instance.Show(val, 1);
			QuartermasterSearch.Open(InventoryGui.instance, val);
			piece.PlayVoice();
			bool flag = instance.bankPages.IsFull(instance.tier);
			if (quoteUpgrade || flag)
			{
				instance.OfferLocalUpgrade(piece, (Player)user, flag);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)instance).Logger.LogError((object)ex);
			((Character)user).Message((MessageType)2, "The Banker could not load storage.", 0, (Sprite)null, false);
		}
		return true;
	}

	internal static byte[] CreateSharedSnapshot()
	{
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer())
		{
			throw new InvalidOperationException("Only the world host can read authoritative vault data.");
		}
		instance.EnsureVault();
		return instance.EncodeVault();
	}

	internal static byte[] CreateBankPageSnapshot(int page, out bool bankFull)
	{
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer())
		{
			throw new InvalidOperationException("Only the world host can read authoritative bank data.");
		}
		instance.EnsureVault();
		bankFull = instance.bankPages.IsFull(instance.tier);
		return instance.EncodeBankPage(page);
	}

	internal static int FindSharedBankPage(int page, BankPageSearch search)
	{
		instance.EnsureVault();
		if (BankCapacity.PageHeight(instance.tier, page) == 0)
		{
			throw new ArgumentOutOfRangeException("page");
		}
		return instance.bankPages.FindMatchingPage(page, search.Direction, search.Matches);
	}

	private Inventory GetBankPage(int page)
	{
		return bankPages.GetPage(tier, page, ObserveVaultPage);
	}

	private byte[] EncodeBankPage(int page)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		Inventory bankPage = GetBankPage(page);
		ZPackage val = new ZPackage();
		val.Write(tier);
		val.Write(page);
		BankVaultPages.WriteInventory(val, bankPage);
		return val.GetArray();
	}

	internal static Inventory DecodeBankPage(byte[] data, out int tier, out int page)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		ZPackage val = new ZPackage(data);
		tier = val.ReadInt();
		page = val.ReadInt();
		Inventory page2 = new BankVaultPages().GetPage(tier, page);
		BankVaultPages.ReadInventory(val, page2);
		if (val.GetPos() != val.Size())
		{
			throw new InvalidDataException("Unexpected bank page bytes.");
		}
		return page2;
	}

	internal static SharedVaultReceipt GetPendingWithdrawal(string owner)
	{
		instance.EnsureVault();
		if (!instance.pendingWithdrawals.TryGetValue(owner, out var value))
		{
			return null;
		}
		return value;
	}

	internal static SharedVaultReceipt ReserveWithdrawal(string owner, byte[] expectedDigest, Vector2i slot, int? amount, int page)
	{
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Expected O, but got Unknown
		instance.EnsureVault();
		if (instance.pendingWithdrawals.ContainsKey(owner) || instance.pendingWithdrawals.Count >= 1024 || !((ReadOnlySpan<byte>)SharedVaultReceipt.Digest(instance.EncodeBankPage(page))).SequenceEqual((ReadOnlySpan<byte>)expectedDigest))
		{
			return null;
		}
		Inventory bankPage = instance.GetBankPage(page);
		List<ItemData> allItems = bankPage.GetAllItems();
		ItemData itemAt = bankPage.GetItemAt(slot.x, slot.y);
		if (itemAt == null || itemAt.m_shared.m_questItem)
		{
			return null;
		}
		int stack = itemAt.m_stack;
		int num = amount ?? stack;
		if (num <= 0 || num > stack)
		{
			return null;
		}
		bool flag = num == stack;
		ItemData obj = (flag ? itemAt : itemAt.Clone());
		obj.m_stack = num;
		ZPackage val = new ZPackage();
		obj.Save(val);
		byte[] array = val.GetArray();
		if (array.Length > 16384)
		{
			return null;
		}
		SharedVaultReceipt sharedVaultReceipt = new SharedVaultReceipt(Guid.NewGuid(), array);
		int index = allItems.IndexOf(itemAt);
		if (flag)
		{
			allItems.RemoveAt(index);
		}
		else
		{
			itemAt.m_stack -= num;
		}
		instance.pendingWithdrawals.Add(owner, sharedVaultReceipt);
		try
		{
			instance.SaveVault();
		}
		catch
		{
			instance.pendingWithdrawals.Remove(owner);
			if (flag)
			{
				allItems.Insert(index, itemAt);
			}
			else
			{
				itemAt.m_stack = stack;
			}
			throw;
		}
		instance.NotifyCommittedPage(bankPage);
		return sharedVaultReceipt;
	}

	internal static SharedVaultReceipt ReserveBulkWithdrawal(string owner, byte[] expectedDigest, (Vector2i Slot, int Quantity)[] requested, int page)
	{
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		instance.EnsureVault();
		if (instance.pendingWithdrawals.ContainsKey(owner) || instance.pendingWithdrawals.Count >= 1024 || !((ReadOnlySpan<byte>)SharedVaultReceipt.Digest(instance.EncodeBankPage(page))).SequenceEqual((ReadOnlySpan<byte>)expectedDigest))
		{
			return null;
		}
		Inventory bankPage = instance.GetBankPage(page);
		List<ItemData> allItems = bankPage.GetAllItems();
		HashSet<Vector2i> hashSet = new HashSet<Vector2i>();
		List<(ItemData, int, int)> list = new List<(ItemData, int, int)>(requested.Length);
		ZPackage val = VaultBatch.BeginItems(requested.Length);
		for (int i = 0; i < requested.Length; i++)
		{
			(Vector2i, int) tuple = requested[i];
			ItemData itemAt = bankPage.GetItemAt(tuple.Item1.x, tuple.Item1.y);
			if (!hashSet.Add(tuple.Item1) || !VaultBatch.IsTransferable(itemAt) || tuple.Item2 <= 0 || tuple.Item2 > itemAt.m_stack)
			{
				return null;
			}
			byte[] array = VaultBatch.SerializeStack(itemAt, tuple.Item2);
			if (array.Length > 16384 || val.Size() + 4 + array.Length > 491520)
			{
				return null;
			}
			val.Write(array);
			list.Add((itemAt, itemAt.m_stack, tuple.Item2));
		}
		SharedVaultReceipt sharedVaultReceipt = new SharedVaultReceipt(Guid.NewGuid(), val.GetArray(), batch: true);
		ItemData[] collection = allItems.ToArray();
		foreach (var item2 in list)
		{
			if (item2.Item3 == item2.Item2)
			{
				allItems.Remove(item2.Item1);
				continue;
			}
			ItemData item = item2.Item1;
			item.m_stack -= item2.Item3;
		}
		instance.pendingWithdrawals.Add(owner, sharedVaultReceipt);
		try
		{
			instance.SaveVault();
		}
		catch
		{
			instance.pendingWithdrawals.Remove(owner);
			foreach (var item3 in list)
			{
				item3.Item1.m_stack = item3.Item2;
			}
			allItems.Clear();
			allItems.AddRange(collection);
			throw;
		}
		instance.NotifyCommittedPage(bankPage);
		return sharedVaultReceipt;
	}

	internal static void AcknowledgeWithdrawal(string owner, Guid id)
	{
		SharedVaultReceipt pendingWithdrawal = GetPendingWithdrawal(owner);
		if (pendingWithdrawal == null || pendingWithdrawal.Id != id)
		{
			return;
		}
		instance.ownerSaves.TryGetValue(owner, out var value);
		instance.ownerSaves[owner] = new VaultOwnerSave(value.Deposit, id);
		instance.pendingWithdrawals.Remove(owner);
		try
		{
			instance.SaveVault();
		}
		catch
		{
			instance.pendingWithdrawals.Add(owner, pendingWithdrawal);
			instance.RestoreOwnerSave(owner, value);
			throw;
		}
	}

	internal static bool MatchesCharacterSave(string owner, Guid deposit, Guid pendingDeposit, Guid withdrawal)
	{
		instance.EnsureVault();
		if (!instance.ownerSaves.TryGetValue(owner, out var value))
		{
			return true;
		}
		if (value.Deposit != Guid.Empty && value.Deposit != deposit && value.Deposit != pendingDeposit)
		{
			return false;
		}
		if (!(value.Withdrawal == Guid.Empty) && !(value.Withdrawal == withdrawal))
		{
			if (instance.pendingWithdrawals.TryGetValue(owner, out var value2))
			{
				return value2.Id == withdrawal;
			}
			return false;
		}
		return true;
	}

	private void RestoreOwnerSave(string owner, VaultOwnerSave previous)
	{
		if (previous.Deposit == Guid.Empty && previous.Withdrawal == Guid.Empty)
		{
			ownerSaves.Remove(owner);
		}
		else
		{
			ownerSaves[owner] = previous;
		}
	}

	internal static bool RearrangeVault(byte[] expectedDigest, Vector2i from, Vector2i to, int amount, int page)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		instance.EnsureVault();
		if (!((ReadOnlySpan<byte>)SharedVaultReceipt.Digest(instance.EncodeBankPage(page))).SequenceEqual((ReadOnlySpan<byte>)expectedDigest))
		{
			return false;
		}
		Inventory bankPage = instance.GetBankPage(page);
		ItemData itemAt = bankPage.GetItemAt(from.x, from.y);
		int quantity;
		VaultStackTransfer.Rearrangement rearrangement = VaultStackTransfer.PlanRearrangement(bankPage, itemAt, to, amount, out quantity);
		if (rearrangement == VaultStackTransfer.Rearrangement.Blocked)
		{
			return false;
		}
		ItemData itemAt2 = bankPage.GetItemAt(to.x, to.y);
		int stack = itemAt.m_stack;
		int stack2 = itemAt2?.m_stack ?? 0;
		List<ItemData> allItems = bankPage.GetAllItems();
		int num = -1;
		ItemData val = null;
		switch (rearrangement)
		{
		case VaultStackTransfer.Rearrangement.Swap:
			itemAt.m_gridPos = to;
			itemAt2.m_gridPos = from;
			break;
		case VaultStackTransfer.Rearrangement.Merge:
			itemAt2.m_stack += quantity;
			itemAt.m_stack -= quantity;
			if (itemAt.m_stack == 0)
			{
				num = allItems.IndexOf(itemAt);
				allItems.RemoveAt(num);
			}
			break;
		default:
			if (quantity == stack)
			{
				itemAt.m_gridPos = to;
				break;
			}
			val = itemAt.Clone();
			val.m_stack = quantity;
			val.m_gridPos = to;
			itemAt.m_stack -= quantity;
			allItems.Add(val);
			break;
		}
		try
		{
			instance.SaveVault();
		}
		catch
		{
			if (val != null)
			{
				allItems.Remove(val);
			}
			itemAt.m_gridPos = from;
			itemAt.m_stack = stack;
			if (num >= 0)
			{
				allItems.Insert(num, itemAt);
			}
			if (itemAt2 != null)
			{
				itemAt2.m_gridPos = to;
				itemAt2.m_stack = stack2;
			}
			throw;
		}
		instance.NotifyCommittedPage(bankPage);
		return true;
	}

	internal static long LastDepositSequence(string owner)
	{
		instance.EnsureVault();
		if (!instance.depositReceipts.TryGetValue(owner, out (long, Guid, VaultTransferOutcome) value))
		{
			return 0L;
		}
		return value.Item1;
	}

	internal static VaultTransferOutcome CommitSharedDeposit(string owner, long sequence, Guid id, byte[] payload, bool batch, int page, bool upgrade)
	{
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		instance.EnsureVault();
		Dictionary<string, (long, Guid, VaultTransferOutcome)> dictionary = instance.depositReceipts;
		(long, Guid, VaultTransferOutcome) value;
		bool flag = dictionary.TryGetValue(owner, out value);
		if (sequence == value.Item1)
		{
			if (!flag || !(id == value.Item2))
			{
				return VaultTransferOutcome.Retry;
			}
			return value.Item3;
		}
		if (sequence <= 0 || sequence - 1 != value.Item1 || id == Guid.Empty || (!flag && dictionary.Count >= 100000))
		{
			return VaultTransferOutcome.Retry;
		}
		VaultTransferOutcome vaultTransferOutcome = VaultTransferOutcome.Returned;
		int num = instance.tier;
		ItemData affected = null;
		int previousQuantity = 0;
		VaultInventoryPlan vaultInventoryPlan = null;
		Inventory val = ((BankCapacity.PageHeight(num, page) > 0) ? instance.GetBankPage(page) : null);
		List<ItemData> list = ((val != null) ? val.GetAllItems() : null);
		if (batch && val != null)
		{
			List<ItemData> list2 = VaultBatch.ReadItems(payload);
			if (list2 == null)
			{
				return VaultTransferOutcome.Retry;
			}
			vaultInventoryPlan = VaultBatch.PlanStackDeposit(val, list2);
		}
		else if (upgrade)
		{
			if (!BankUpgradePayment.TryRead(payload, out var num2, out var _))
			{
				return VaultTransferOutcome.Retry;
			}
			if (num2 == num && num < int.MaxValue)
			{
				instance.tier++;
				vaultTransferOutcome = VaultTransferOutcome.Accepted;
			}
		}
		else if (!batch && val != null)
		{
			Vector2i? requestedSlot;
			ItemData val2 = ReadVaultDeposit(payload, out requestedSlot);
			if (val2 == null)
			{
				return VaultTransferOutcome.Retry;
			}
			if (requestedSlot.HasValue)
			{
				if (VaultStackTransfer.TryPlace(val, requestedSlot.Value, val2, out affected, out previousQuantity))
				{
					vaultTransferOutcome = VaultTransferOutcome.Accepted;
				}
			}
			else
			{
				VaultInventoryPlan vaultInventoryPlan2 = new VaultInventoryPlan(val);
				if (vaultInventoryPlan2.Stage(val2, val2.m_stack) == val2.m_stack)
				{
					vaultInventoryPlan = vaultInventoryPlan2;
				}
			}
		}
		if (vaultInventoryPlan != null)
		{
			vaultInventoryPlan.Apply();
			vaultTransferOutcome = VaultTransferOutcome.Accepted;
		}
		instance.ownerSaves.TryGetValue(owner, out var value2);
		instance.ownerSaves[owner] = new VaultOwnerSave(id, value2.Withdrawal);
		dictionary[owner] = (sequence, id, vaultTransferOutcome);
		try
		{
			instance.SaveVault();
		}
		catch
		{
			instance.tier = num;
			vaultInventoryPlan?.Revert();
			if (affected != null)
			{
				if (previousQuantity > 0)
				{
					affected.m_stack = previousQuantity;
				}
				else
				{
					list.Remove(affected);
				}
			}
			if (flag)
			{
				dictionary[owner] = value;
			}
			else
			{
				dictionary.Remove(owner);
			}
			instance.RestoreOwnerSave(owner, value2);
			throw;
		}
		if (instance.tier != num)
		{
			instance.vault = instance.GetBankPage(instance.vaultPage);
		}
		if (affected != null || vaultInventoryPlan != null)
		{
			instance.NotifyCommittedPage(val);
		}
		return vaultTransferOutcome;
	}

	internal static ItemData ReadTransferredItem(byte[] payload)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		ZPackage val = new ZPackage(payload);
		ItemData result = DecodeTransferredItem(val);
		if (val.GetPos() != val.Size())
		{
			return null;
		}
		return result;
	}

	internal static ItemData ReadVaultDeposit(byte[] payload, out Vector2i? requestedSlot)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		ZPackage val = new ZPackage(payload);
		ItemData result = DecodeTransferredItem(val);
		requestedSlot = ((val.Size() - val.GetPos() == 8) ? new Vector2i?(val.ReadVector2i()) : ((Vector2i?)null));
		if (val.GetPos() != val.Size())
		{
			return null;
		}
		return result;
	}

	private static ItemData DecodeTransferredItem(ZPackage package)
	{
		ValueTuple<int, ItemData> valueTuple = ItemData.Load(package, (Item)110);
		int item = valueTuple.Item1;
		ItemData item2 = valueTuple.Item2;
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item);
		ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
		if (!Object.op_Implicit((Object)(object)val) || val.m_itemData.m_shared.m_questItem || item2.m_equipped || item2.m_stack < 1 || item2.m_stack > val.m_itemData.m_shared.m_maxStackSize)
		{
			return null;
		}
		item2.m_dropPrefab = itemPrefab;
		item2.m_shared = val.m_itemData.m_shared;
		return item2;
	}

	private bool IsLoadedWorld(long? worldId)
	{
		if (worldId.HasValue && loadedWorldId == worldId)
		{
			return loadedWorldScene == ZoneSystem.instance;
		}
		return false;
	}

	private void EnsureVault()
	{
		long worldUID = ZNet.instance.GetWorldUID();
		if (!IsLoadedWorld(worldUID))
		{
			LoadVault(worldUID);
		}
		if ((hostTransfer != null || HasHostEdit) && !Flush())
		{
			throw new IOException("The previous Quartermaster transfer is still waiting to save.");
		}
	}

	private static string HostTransferPath(long world)
	{
		return WorldSaveCheckpoint.PathFor(world, "vault") + ".host-transfer";
	}

	internal static bool RecoverHostVault()
	{
		if (!Object.op_Implicit((Object)(object)instance) || !CanUseAuthoritativeWorld())
		{
			return true;
		}
		long worldUID = ZNet.instance.GetWorldUID();
		try
		{
			if (File.Exists(HostTransferPath(worldUID)) || (instance.IsLoadedWorld(worldUID) && (instance.hostTransfer != null || instance.HasHostEdit)))
			{
				instance.EnsureVault();
			}
			return true;
		}
		catch (Exception error)
		{
			instance.ReportPendingVault(error);
			return false;
		}
	}

	private void LoadVault(long worldId)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Expected O, but got Unknown
		SaveFileCheckpoint saveFileCheckpoint = WorldSaveCheckpoint.Open(WorldSaveCheckpoint.PathFor(worldId, "vault"), "vault");
		ZPackage package = null;
		using (FileStream fileStream = saveFileCheckpoint.OpenRead())
		{
			if (fileStream != null)
			{
				int num = checked((int)fileStream.Length);
				using BinaryReader binaryReader = new BinaryReader(fileStream);
				byte[] array = binaryReader.ReadBytes(num);
				if (array.Length != num)
				{
					throw new EndOfStreamException("Incomplete vault file.");
				}
				package = new ZPackage(array);
			}
		}
		int loadedTier;
		BankVaultPages loaded = BankVaultPages.Read(package, out loadedTier);
		Dictionary<string, SharedVaultReceipt> receipts = SharedVaultReceipt.ReadPending(package);
		Dictionary<string, (long, Guid, VaultTransferOutcome)> deposits = SharedVaultReceipt.ReadDeposits(package);
		Dictionary<string, VaultOwnerSave> characterSaves = VaultOwnerSave.Read(package);
		HostVaultTransfer hostVaultTransfer = HostVaultTransfer.Read(HostTransferPath(worldId));
		saveFileCheckpoint.AcceptRead();
		SetVault(loaded, loadedTier, receipts, deposits, characterSaves);
		vaultSave = saveFileCheckpoint;
		loadedWorldId = worldId;
		loadedWorldScene = ZoneSystem.instance;
		hostTransfer = hostVaultTransfer;
		recoveringHostTransfer = hostVaultTransfer != null;
		hostCharacterSaved = false;
	}

	private void SetVault(BankVaultPages loaded, int loadedTier, Dictionary<string, SharedVaultReceipt> receipts, Dictionary<string, (long Sequence, Guid Id, VaultTransferOutcome Outcome)> deposits, Dictionary<string, VaultOwnerSave> characterSaves)
	{
		bankPages = loaded;
		vault = loaded.GetPage(loadedTier, vaultPage = 0);
		foreach (Inventory inventory in loaded.Inventories)
		{
			ObserveVaultPage(inventory);
		}
		pendingWithdrawals = receipts;
		depositReceipts = deposits;
		ownerSaves = characterSaves;
		tier = loadedTier;
		dirty = false;
		vaultEditor = null;
	}

	private void ObserveVaultPage(Inventory inventory)
	{
		Inventory obj = inventory;
		obj.m_onChanged = (Action)Delegate.Combine(obj.m_onChanged, (Action)delegate
		{
			dirty = true;
			if (Object.op_Implicit((Object)(object)active) && vault == inventory)
			{
				vaultEditor = Player.m_localPlayer;
			}
		});
	}

	private void NotifyCommittedPage(Inventory inventory)
	{
		bool flag = dirty;
		Player val = vaultEditor;
		try
		{
			NotifyInventoryChanged(inventory);
		}
		finally
		{
			dirty = flag;
			vaultEditor = val;
		}
	}

	internal static Inventory DecodeVault(byte[] data, out int loadedTier)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		return BankVaultPages.Read((data == null) ? ((ZPackage)null) : new ZPackage(data), out loadedTier).GetPage(loadedTier, 0);
	}

	private byte[] EncodeVault(bool includeReceipts = false)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		ZPackage val = new ZPackage();
		bankPages.Write(val, tier);
		if (includeReceipts)
		{
			SharedVaultReceipt.WritePending(val, pendingWithdrawals);
			SharedVaultReceipt.WriteDeposits(val, depositReceipts);
			VaultOwnerSave.Write(val, ownerSaves);
		}
		return val.GetArray();
	}

	private void SaveVault()
	{
		WriteVaultPayload(EncodeVault(includeReceipts: true));
	}

	private void WriteVaultPayload(byte[] data, SaveRevision expected = default(SaveRevision), Action beforeCommit = null)
	{
		vaultSave.Write(delegate(Stream stream)
		{
			stream.Write(data, 0, data.Length);
		}, expected, beforeCommit);
	}

	private void LateUpdate()
	{
		if ((dirty || hostTransfer != null) && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
		{
			World world = ZNet.instance.GetWorld();
			if (world != null && IsLoadedWorld(world.m_uid) && Time.unscaledTime >= nextSaveAttempt && !Flush() && Object.op_Implicit((Object)(object)active) && Object.op_Implicit((Object)(object)InventoryGui.instance))
			{
				InventoryGui.instance.Hide();
			}
		}
		SharedVaultLink.UpdateRemoteBank();
		WorkshopExchange.Tick();
		if (Object.op_Implicit((Object)(object)active) && Object.op_Implicit((Object)(object)InventoryGui.instance) && !CanUseAuthoritativeWorld())
		{
			InventoryGui.instance.Hide();
		}
	}

	private bool Flush()
	{
		if (!dirty && hostTransfer == null)
		{
			return true;
		}
		try
		{
			if (recoveringHostTransfer)
			{
				FinishHostTransfer(null, replay: true);
				return true;
			}
			if (hostCharacterSaved && hostTransfer != null)
			{
				FinishHostTransfer(Object.op_Implicit((Object)(object)Game.instance) ? Game.instance.GetPlayerProfile() : null, replay: false);
				return true;
			}
			if (!Object.op_Implicit((Object)(object)vaultEditor))
			{
				if (hostTransfer != null || HasHostEdit)
				{
					throw new IOException("The saved character for this transfer is unavailable.");
				}
				SaveVault();
				dirty = false;
				return true;
			}
			PlayerProfile val = (Object.op_Implicit((Object)(object)Game.instance) ? Game.instance.GetPlayerProfile() : null);
			PrepareHostTransfer(val, vaultEditor);
			if (hostTransfer == null)
			{
				return true;
			}
			val.SavePlayerData(vaultEditor);
			PlayerProfile val2 = savingHostProfile;
			savingHostProfile = val;
			try
			{
				if (!val.Save())
				{
					throw new IOException("Valheim could not save the character for this vault transfer.");
				}
			}
			finally
			{
				savingHostProfile = val2;
			}
			return hostTransfer == null;
		}
		catch (Exception error)
		{
			ReportPendingVault(error);
			return false;
		}
	}

	private void ReportPendingVault(Exception error)
	{
		nextSaveAttempt = Time.unscaledTime + 3f;
		((BaseUnityPlugin)this).Logger.LogError((object)error);
		if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, "Bank storage has not saved. The transfer is pending.", 0, (Sprite)null, false);
		}
	}

	private void PrepareHostTransfer(PlayerProfile profile, Player player)
	{
		//IL_0064: 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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Invalid comparison between Unknown and I4
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Invalid comparison between Unknown and I4
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Invalid comparison between Unknown and I4
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		if (hostTransfer != null)
		{
			if (recoveringHostTransfer || profile == null || hostTransfer.Actor != profile.GetPlayerID() || hostTransfer.Profile != profile.GetFilename())
			{
				throw new IOException("A different character owns the pending Quartermaster vault transfer.");
			}
			return;
		}
		if (profile != null && profile.GetPlayerID() == player.GetPlayerID() && !SaveSystem.HasSessionFlag((SaveSystemSessionFlags)1))
		{
			FileSource fileSource = profile.m_fileSource;
			if ((int)fileSource == 2 || (int)fileSource == 4 || (int)fileSource == 8)
			{
				long value = loadedWorldId.Value;
				if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.GetWorldUID() != value)
				{
					throw new IOException("The character has left the Quartermaster vault's world.");
				}
				byte[] payload = EncodeVault(includeReceipts: true);
				SaveRevision saveRevision = vaultSave.DescribeNext(payload);
				if (saveRevision.Digest == vaultSave.Current.Digest)
				{
					dirty = false;
					vaultEditor = null;
					return;
				}
				if (CharacterSaveCheckpoint.Stage(player, out var revision) == null)
				{
					throw new IOException("The Quartermaster needs the matching character save for this vault transfer.");
				}
				HostVaultTransfer hostVaultTransfer = new HostVaultTransfer
				{
					Actor = player.GetPlayerID(),
					Profile = profile.GetFilename(),
					Source = profile.m_fileSource,
					Id = Guid.NewGuid(),
					CharacterRevision = revision,
					Before = vaultSave.Current,
					After = saveRevision,
					Vault = payload
				};
				hostVaultTransfer.Write(HostTransferPath(value));
				hostTransfer = hostVaultTransfer;
				hostCharacterSaved = false;
				player.m_customData[HostVaultTransfer.Key(value)] = hostVaultTransfer.Id.ToString("N");
				CharacterSaveCheckpoint.Observe(player, value, "vault", saveRevision);
				return;
			}
		}
		throw new IOException("The Quartermaster cannot verify this character save.");
	}

	private void FinishHostTransfer(PlayerProfile currentProfile, bool replay)
	{
		//IL_0080: 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_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Invalid comparison between Unknown and I4
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		HostVaultTransfer transfer = hostTransfer;
		long value = loadedWorldId.Value;
		bool flag = vaultSave.Current.Matches(transfer.Before);
		bool flag2 = vaultSave.Current.Matches(transfer.After);
		if (!flag && !flag2)
		{
			throw new InvalidDataException("The pending transfer does not match the Quartermaster vault.");
		}
		FileSource val = currentProfile?.m_fileSource ?? transfer.Source;
		bool applied;
		bool flag3 = transfer.TryReadCharacter(value, val, out applied);
		if (!applied && (int)val != 2 && transfer.TryReadCharacter(value, (FileSource)2, out var applied2))
		{
			flag3 = true;
			applied = applied2;
		}
		string checkpoint = CharacterSaveCheckpoint.PathFor(transfer.Actor);
		long num = CharacterSaveCheckpoint.ReadConfirmed(checkpoint);
		hostCharacterSaved = applied;
		if (!applied)
		{
			if (!flag3 || !replay || !flag || num >= transfer.CharacterRevision)
			{
				throw new IOException("Restore the character save that matches the pending Quartermaster vault transfer.");
			}
		}
		else if (flag)
		{
			if (replay && !transfer.After.Matches(vaultSave.DescribeNext(transfer.Vault)))
			{
				throw new InvalidDataException("The pending Quartermaster vault payload has changed.");
			}
			ZPackage package = ((!replay) ? ((ZPackage)null) : new ZPackage(transfer.Vault));
			int loadedTier = 0;
			BankVaultPages bankVaultPages = (replay ? BankVaultPages.Read(package, out loadedTier) : null);
			Dictionary<string, SharedVaultReceipt> receipts = (replay ? SharedVaultReceipt.ReadPending(package) : null);
			Dictionary<string, (long, Guid, VaultTransferOutcome)> deposits = (replay ? SharedVaultReceipt.ReadDeposits(package) : null);
			Dictionary<string, VaultOwnerSave> characterSaves = (replay ? VaultOwnerSave.Read(package) : null);
			Action beforeCommit = ((num < transfer.CharacterRevision) ? ((Action)delegate
			{
				CharacterSaveCheckpoint.Confirm(checkpoint, transfer.CharacterRevision);
			}) : null);
			WriteVaultPayload(transfer.Vault, transfer.After, beforeCommit);
			if (bankVaultPages != null)
			{
				SetVault(bankVaultPages, loadedTier, receipts, deposits, characterSaves);
			}
		}
		File.Delete(HostTransferPath(value));
		hostTransfer = null;
		recoveringHostTransfer = false;
		hostCharacterSaved = false;
		dirty = false;
		vaultEditor = null;
	}

	internal static void NotifyInventoryChanged(Inventory inventory)
	{
		AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null).Invoke(inventory, new object[2] { false, false });
	}

	internal static bool OfferUpgrade(QuartermasterPiece piece, Humanoid user, ItemData item)
	{
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)ZNet.instance) || (Object)(object)user != (Object)(object)Player.m_localPlayer || item.m_shared.m_name != "$item_coins")
		{
			return false;
		}
		return Open(piece, user, quoteUpgrade: true);
	}

	private void OfferLocalUpgrade(QuartermasterPiece piece, Player player, bool vaultFull)
	{
		if (tier == int.MaxValue)
		{
			((Character)player).Message((MessageType)2, vaultFull ? "The vault is full and fully upgraded." : "Storage is fully upgraded.", 0, (Sprite)null, false);
			return;
		}
		int quotedTier = tier;
		ShowUpgradeQuote(piece, player, 250, delegate
		{
			if ((Object)(object)active == (Object)(object)piece && quotedTier == tier)
			{
				Upgrade((Humanoid)(object)player, 250);
			}
		}, vaultFull);
	}

	internal static void ShowUpgradeQuote(QuartermasterPiece piece, Player player, int cost, Action onAccept, bool vaultFull = false)
	{
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		string text = (vaultFull ? "The vault is full. " : "") + $"Add {24} stack slots for {cost} Coins?";
		PopupButtonCallback val = delegate
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			UnifiedPopup.Pop();
			if (Object.op_Implicit((Object)(object)piece) && Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && Vector3.Distance(((Component)piece).transform.position, ((Component)player).transform.position) < 5f)
			{
				onAccept();
			}
		};
		object obj = <>O.<0>__Pop;
		if (obj == null)
		{
			PopupButtonCallback val2 = UnifiedPopup.Pop;
			<>O.<0>__Pop = val2;
			obj = (object)val2;
		}
		UnifiedPopup.Push((PopupBase)new YesNoPopup("Upgrade Dvergr Bank", text, val, (PopupButtonCallback)obj, true, false));
	}

	private void Upgrade(Humanoid user, int quotedCost)
	{
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Expected O, but got Unknown
		Inventory inventory = user.GetInventory();
		if (tier == int.MaxValue || quotedCost != 250 || !Flush())
		{
			return;
		}
		if (inventory.CountItems("$item_coins", -1, true) < quotedCost)
		{
			((Character)user).Message((MessageType)2, $"You need {quotedCost} coins to upgrade.", 0, (Sprite)null, false);
			return;
		}
		inventory.RemoveItem("$item_coins", quotedCost, -1, true);
		tier++;
		vault = GetBankPage(vaultPage);
		dirty = true;
		vaultEditor = (Player)user;
		if (Flush())
		{
			((Character)user).Message((MessageType)2, "Storage upgraded.", 0, (Sprite)null, false);
		}
	}

	private static bool IsQuartermaster(Container container)
	{
		return Object.op_Implicit((Object)(object)((Component)container).GetComponent<QuartermasterPiece>());
	}

	private static Container BankInventoryView(QuartermasterPiece piece)
	{
		Container component = ((Component)piece).GetComponent<Container>();
		if (Object.op_Implicit((Object)(object)component))
		{
			return component;
		}
		component = ((Component)piece).gameObject.AddComponent<Container>();
		((Object)component).hideFlags = (HideFlags)52;
		return component;
	}
}
public sealed class QuartermasterPiece : MonoBehaviour, Interactable, Hoverable
{
	internal static EffectList Voice;

	private const float AmbientVoiceQuietPeriod = 3f;

	private static float ambientQuietUntil;

	private float nextVoice;

	private float lastVoice = float.NegativeInfinity;

	private Animator body;

	private void Start()
	{
		body = ((Component)this).GetComponentInChildren<Animator>(true);
		DvergrPresentation.Stand(body);
		nextVoice = Time.time + Random.Range(15f, 35f);
	}

	private void Update()
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if (Object.op_Implicit((Object)(object)localPlayer))
		{
			DvergrPresentation.MaintainIdlePose(body);
		}
		if (!Object.op_Implicit((Object)(object)localPlayer) || !(Time.time >= nextVoice))
		{
			return;
		}
		Vector3 val = ((Component)localPlayer).transform.position - ((Component)this).transform.position;
		if (((Vector3)(ref val)).sqrMagnitude < 100f)
		{
			if (Time.time < ambientQuietUntil)
			{
				ScheduleAmbientVoice();
			}
			else
			{
				PlayVoice();
			}
		}
	}

	internal void PlayVoice()
	{
		if (Voice != null && !(Time.time - lastVoice < 8f))
		{
			DvergrPresentation.PlayNativeVoice(((Component)this).transform);
			lastVoice = Time.time;
			ambientQuietUntil = lastVoice + 3f;
			ScheduleAmbientVoice();
		}
	}

	private void ScheduleAmbientVoice()
	{
		nextVoice = Time.time + Random.Range(28f, 42f);
	}

	public float GetHoverOffset()
	{
		return 1f;
	}

	public string GetHoverName()
	{
		return "Dvergr Banker";
	}

	public string GetHoverText()
	{
		return Localization.instance.Localize(GetHoverName() + "\n[<color=yellow><b>$KEY_Use</b></color>] Open bank");
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		if (!hold)
		{
			Humanoid obj = user;
			Player val = (Player)(object)((obj is Player) ? obj : null);
			if (val != null && !((Object)(object)val != (Object)(object)Player.m_localPlayer) && !((Character)val).IsDead() && !((Character)val).IsTeleporting() && !((Character)val).InCutscene())
			{
				if (!DvergrBuildInvestment.AllowInteraction(((Component)this).gameObject, val))
				{
					return true;
				}
				if (!CharacterSaveCheckpoint.CanInteract(val))
				{
					return true;
				}
				return RemoteSaveGuard.Interact(this, val, () => QuartermasterPlugin.Open(this, user));
			}
		}
		return false;
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		Humanoid obj = user;
		Player val = (Player)(object)((obj is Player) ? obj : null);
		if (val == null || (Object)(object)val != (Object)(object)Player.m_localPlayer || item == null)
		{
			return false;
		}
		if (!DvergrBuildInvestment.AllowInteraction(((Component)this).gameObject, val))
		{
			return true;
		}
		if (item.m_shared.m_name == "$item_coins" && Object.op_Implicit((Object)(object)ZNet.instance) && !ZNet.instance.IsServer() && !SharedVaultLink.RequireLocalCharacter(val))
		{
			return true;
		}
		if (!CharacterSaveCheckpoint.CanInteract(val))
		{
			return true;
		}
		return RemoteSaveGuard.Interact(this, val, () => QuartermasterPlugin.OfferUpgrade(this, user, item));
	}
}
internal sealed class QuartermasterSearch : MonoBehaviour
{
	internal enum Category
	{
		All,
		Materials,
		FoodAndMead,
		Weapons,
		Armor,
		Tools,
		Ammunition,
		Trophies,
		Other
	}

	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
	private static class UpdateVaultResults
	{
		private static void Postfix(InventoryGrid __instance, Inventory ___m_inventory, List<InventoryElement> ___m_elements, Vector2i ___m_selected)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: 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)
			QuartermasterSearch quartermasterSearch = Current();
			if (!Object.op_Implicit((Object)(object)quartermasterSearch) || !Object.op_Implicit((Object)(object)quartermasterSearch.container) || !((Object)(object)__instance == (Object)(object)quartermasterSearch.gui.ContainerGrid))
			{
				return;
			}
			if (___m_inventory != null)
			{
				(int, int) tuple = (QuartermasterPlugin.VisibleBankPages().Page, ___m_inventory.GetHeight());
				(int, int) renderedGrid = quartermasterSearch.renderedGrid;
				(int, int) tuple2 = tuple;
				if (renderedGrid.Item1 != tuple2.Item1 || renderedGrid.Item2 != tuple2.Item2)
				{
					ScrollRect componentInParent = ((Component)__instance.m_gridRoot).GetComponentInParent<ScrollRect>();
					if (Object.op_Implicit((Object)(object)componentInParent))
					{
						componentInParent.StopMovement();
					}
					__instance.ResetView();
					quartermasterSearch.renderedGrid = tuple;
					quartermasterSearch.jumpToMatch = quartermasterSearch.Filtering;
					quartermasterSearch.filterNeedsRefresh = quartermasterSearch.Filtering;
				}
			}
			quartermasterSearch.RenderFilter(__instance, ___m_inventory, ___m_elements);
			if (___m_inventory != null)
			{
				quartermasterSearch.CullOffscreenSlots(__instance, ___m_inventory, ___m_elements, ___m_selected);
			}
			if (quartermasterSearch.gamepad.Active && ___m_inventory != null)
			{
				int num = ___m_selected.y * ___m_inventory.GetWidth() + ___m_selected.x;
				if (num >= 0 && num < ___m_elements.Count)
				{
					___m_elements[num].m_selected.SetActive(false);
				}
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
	private static class FilterNativeSelection
	{
		private static bool Prefix(InventoryGrid grid, Vector2i pos)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return AllowsSlot(grid, pos);
		}
	}

	[HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip")]
	private static class FilterNativeTooltip
	{
		private static bool Prefix(InventoryGrid __instance, ItemData item)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return AllowsSlot(__instance, item.m_gridPos);
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")]
	private static class FilterNativeUse
	{
		private static bool Prefix(InventoryGrid grid, Vector2i pos)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return AllowsSlot(grid, pos);
		}
	}

	[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
	private static class FilterNativeDrop
	{
		private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, Vector2i pos)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if (!AllowsSlot(__instance, pos))
			{
				return false;
			}
			QuartermasterSearch quartermasterSearch = Current();
			if (Object.op_Implicit((Object)(object)quartermasterSearch) && Object.op_Implicit((Object)(object)quartermasterSearch.container) && quartermasterSearch.Filtering && fromInventory == quartermasterSearch.container.GetInventory())
			{
				return quartermasterSearch.Matches(item);
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Update")]
	private static class ProtectSearchTyping
	{
		private static void Prefix()
		{
			QuartermasterSearch quartermasterSearch = Current();
			if (Object.op_Implicit((Object)(object)quartermasterSearch) && Object.op_Implicit((Object)(object)quartermasterSearch.container) && quartermasterSearch.gui.IsContainerOpen())
			{
				quartermasterSearch.RefreshBankPagination();
				quartermasterSearch.gamepad.Update(quartermasterSearch.EnterGamepadControls, quartermasterSearch.LeaveGamepadControls, quartermasterSearch.CloseCategories);
				if (quartermasterSearch.gamepad.Active)
				{
					ZInput.ResetButtonStatus("JoyUse");
				}
				if (((TMP_InputField)quartermasterSearch.search).isFocused)
				{
					ZInput.ResetButtonStatus("Use");
					ZInput.ResetButtonStatus("Inventory");
				}
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "OnTakeAll")]
	private static class ProtectTakeAllControllerFocus
	{
		[HarmonyPriority(800)]
		private static bool Prefix(InventoryGui __instance)
		{
			return CanInvokeBulkButton(__instance, __instance.m_takeAllButton);
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "OnStackAll")]
	private static class ProtectPlaceStacksControllerFocus
	{
		[HarmonyPriority(800)]
		private static bool Prefix(InventoryGui __instance)
		{
			return CanInvokeBulkButton(__instance, __instance.m_stackAllButton);
		}
	}

	[HarmonyPatch(typeof(InventoryGrid), "UpdateGamepad")]
	private static class HoldNativeGridFocus
	{
		private static bool Prefix()
		{
			return NativeGamepadRoutesAvailable();
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "UpdateGamepad")]
	private static class HoldNativeInventoryFocus
	{
		private static bool Prefix()
		{
			return NativeGamepadRoutesAvailable();
		}
	}

	internal static readonly string[] CategoryNames = new string[9] { "All items", "Materials", "Food & mead", "Weapons", "Armor", "Tools", "Ammunition", "Trophies", "Other" };

	private static readonly FieldInfo BuildSearch = AccessTools.Field(typeof(BuildUi), "m_searchField");

	private static readonly MethodInfo SetInventoryGroup = AccessTools.Method(typeof(InventoryGui), "SetActiveGroup", new Type[2]
	{
		typeof(UIGroupHandler),
		typeof(bool)
	}, (Type[])null);

	private InventoryGui gui;

	private Container container;

	private GuiInputField search;

	private GameObject categories;

	private Button filter;

	private Button clear;

	private TMP_Text filterLabel;

	private TMP_Text results;

	private TMP_Text bulkHint;

	private TMP_Text bankPage;

	private Button previousPage;

	private Button nextPage;

	private TMP_Text previousPageLabel;

	private TMP_Text nextPageLabel;

	private (int Page, int Pages) renderedPage;

	private (int Page, int Height) renderedGrid;

	private Category category;

	private string query = "";

	private string pageSearchStatus;

	private int filterRevision;

	private bool jumpToMatch;

	private bool filterNeedsRefresh;

	private Inventory observedInventory;

	private InventoryElement renderedFirstSlot;

	private string renderedLanguage;

	private bool bulkDisabled;

	private bool takeAllEnabled;

	private bool stackAllEnabled;

	private QuartermasterGamepadFocus gamepad;

	private Navigation takeAllNavigation;

	private Navigation stackAllNavigation;

	private readonly Button[] categoryButtons = (Button[])(object)new Button[CategoryNames.Length];

	private readonly Dictionary<InventoryElement, CanvasGroup> hiddenSlots = new Dictionary<InventoryElement, CanvasGroup>();

	private readonly HashSet<Vector2i> hiddenPositions = new HashSet<Vector2i>();

	private readonly List<GameObject> offscreenSlots = new List<GameObject>();

	private InventoryElement viewportFirstSlot;

	private (int First, int Last, int Selected) visibleRows;

	private const int ViewportPaddingRows = 2;

	private const int ViewportCullingMinRows = 15;

	private bool Filtering
	{
		get
		{
			if (query.Length <= 0)
			{
				return category != Category.All;
			}
			return true;
		}
	}

	internal static int FilterRevision => Current()?.filterRevision ?? 0;

	internal static void Open(InventoryGui gui, Container container)
	{
		QuartermasterSearch quartermasterSearch = ((Component)gui.m_container).GetComponent<QuartermasterSearch>();
		if (!Object.op_Implicit((Object)(object)quartermasterSearch))
		{
			GuiInputField val = SearchTemplate();
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			quartermasterSearch = ((Component)gui.m_container).gameObject.AddComponent<QuartermasterSearch>();
			quartermasterSearch.Initialize(gui, val);
		}
		quartermasterSearch.EndSession();
		quartermasterSearch.container = container;
		((Component)quartermasterSearch.search).gameObject.SetActive(true);
		((Component)quartermasterSearch.filter).gameObject.SetActive(true);
		((Component)quartermasterSearch.clear).gameObject.SetActive(true);
		((Component)quartermasterSearch.results).gameObject.SetActive(true);
		quartermasterSearch.RefreshBankPagination();
	}

	internal static void Close(Container container)
	{
		QuartermasterSearch quartermasterSearch = Current();
		if (Object.op_Implicit((Object)(object)quartermasterSearch) && (Object)(object)quartermasterSearch.container == (Object)(object)container)
		{
			quartermasterSearch.EndSession();
		}
	}

	internal static bool HasFilter(Container container)
	{
		QuartermasterSearch quartermasterSearch = Current();
		if (Object.op_Implicit((Object)(object)quartermasterSearch) && (Object)(object)quartermasterSearch.container == (Object)(object)container)
		{
			return quartermasterSearch.Filtering;
		}
		return false;
	}

	internal static void ShowPageSearchMiss(int direction)
	{
		QuartermasterSearch quartermasterSearch = Current();
		if (Object.op_Implicit((Object)(object)quartermasterSearch) && Object.op_Implicit((Object)(object)quartermasterSearch.container) && quartermasterSearch.Filtering)
		{
			quartermasterSearch.pageSearchStatus = ((direction > 0) ? "No later matches" : "No earlier matches");
			quartermasterSearch.results.text = quartermasterSearch.pageSearchStatus;
		}
	}

	private static QuartermasterSearch Current()
	{
		InventoryGui instance = InventoryGui.instance;
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)instance.m_container))
		{
			return null;
		}
		return ((Component)instance.m_container).GetComponent<QuartermasterSearch>();
	}

	private void Initialize(InventoryGui inventoryGui, GuiInputField template)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected O, but got Unknown
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Expected O, but got Unknown
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Expected O, but got Unknown
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Expected O, but got Unknown
		//IL_023d: Unknown result type (might be due to invalid IL or missing references)
		//IL_025b: Expected O, but got Unknown
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Expected O, but got Unknown
		//IL_0308: Unknown result type (might be due to invalid IL or missing references)
		//IL_0312: Expected O, but got Unknown
		//IL_0355: Unknown result type (might be due to invalid IL or missing references)
		//IL_0373: Expected O, but got Unknown
		//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c9: Expected O, but got Unknown
		//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0409: Expected O, but got Unknown
		//IL_0488: Unknown result type (might be due to invalid IL or missing references)
		//IL_0492: Expected O, but got Unknown
		gui = inventoryGui;
		search = CloneSearch(template, ((Component)this).transform, "Quartermaster Search", "Search storage");
		Position((RectTransform)((Component)search).transform, 0.01f, 0.53f, -4f, 29f);
		((UnityEvent<string>)(object)((TMP_InputField)search).onValueChanged).AddListener((UnityAction<string>)delegate(string value)
		{
			query = value.Trim();
			RefreshFilter();
		});
		filter = MakeButton("All items", ((Component)this).transform, 0.54f, 0.83f, -4f);
		filterLabel = ((Component)filter).GetComponentInChildren<TMP_Text>();
		((UnityEvent)filter.onClick).AddListener(new UnityAction(ToggleCategories));
		gamepad = new QuartermasterGamepadFocus(search, (Selectable)(object)filter, "Search storage", "JoyDPadDown", null, searchShortcut: false);
		InventoryGrid containerGrid = gui.ContainerGrid;
		containerGrid.OnMoveToLowerInventoryGrid = (Action<Vector2i>)Delegate.Combine(containerGrid.OnMoveToLowerInventoryGrid, new Action<Vector2i>(FocusBelowVault));
		clear = MakeButton("Clear", ((Component)this).transform, 0.84f, 0.99f, -4f);
		((UnityEvent)clear.onClick).AddListener((UnityAction)delegate
		{
			((TMP_InputField)search).SetTextWithoutNotify("");
			query = "";
			SetCategory(Category.All);
		});
		results = Object.Instantiate<TMP_Text>(gui.m_containerName, ((Component)this).transform, false);
		((Object)results).name = "Quartermaster Match Count";
		results.text = "";
		((Graphic)results).raycastTarget = false;
		results.fontSize = 15f;
		results.enableAutoSizing = false;
		results.alignment = (TextAlignmentOptions)513;
		Position((RectTransform)results.transform, 0.01f, 0.4f, -35f, 23f);
		bulkHint = Object.Instantiate<TMP_Text>(results, ((Component)this).transform, false);
		((Object)bulkHint).name = "Quartermaster Filtered Bulk Hint";
		bulkHint.text = "Clear filters to use bulk actions";
		bulkHint.alignment = (TextAlignmentOptions)516;
		Position((RectTransform)bulkHint.transform, 0.41f, 0.99f, -35f, 23f);
		((Component)bulkHint).gameObject.SetActive(false);
		previousPage = MakeButton("Prev", ((Component)this).transform, 0.41f, 0.58f, -35f);
		previousPageLabel = ((Component)previousPage).GetComponentInChildren<TMP_Text>();
		((UnityEvent)previousPage.onClick).AddListener((UnityAction)delegate
		{
			TurnPage(-1);
		});
		nextPage = MakeButton("Next", ((Component)this).transform, 0.81f, 0.99f, -35f);
		nextPageLabel = ((Component)nextPage).GetComponentInChildren<TMP_Text>();
		((UnityEvent)nextPage.onClick).AddListener((UnityAction)delegate
		{
			TurnPage(1);
		});
		bankPage = Object.Instantiate<TMP_Text>(results, ((Component)this).transform, false);
		((Object)bankPage).name = "Quartermaster Bank Page";
		bankPage.alignment = (TextAlignmentOptions)514;
		Position((RectTransform)bankPage.transform, 0.59f, 0.8f, -35f, 28f);
		((Component)previousPage).gameObject.SetActive(false);
		((Component)nextPage).gameObject.SetActive(false);
		((Component)bankPage).gameObject.SetActive(false);
		categories = new GameObject("Quartermaster Categories", new Type[1] { typeof(RectTransform) });
		categories.transform.SetParent(((Component)this).transform, false);
		Position((RectTransform)categories.transform, 0f, 1f, -32f, 1f);
		for (int num = 0; num < CategoryNames.Length; num++)
		{
			Category choice = (Category)num;
			int num2 = num % 3;
			int num3 = num / 3;
			((UnityEvent)(categoryButtons[num] = MakeButton(CategoryNames[num], categories.transform, (float)num2 / 3f + 0.005f, ((float)num2 + 1f) / 3f - 0.005f, (float)(-num3) * 30f)).onClick).AddListener((UnityAction)delegate
			{
				SetCategory(choice);
			});
		}
	}

	internal static GuiInputField SearchTemplate()
	{
		if (!Object.op_Implicit((Object)(object)Hud.instance) || !Object.op_Implicit((Object)(object)Hud.instance.m_buildUi))
		{
			return null;
		}
		object? obj = BuildSearch?.GetValue(Hud.instance.m_buildUi);
		return (GuiInputField)((obj is GuiInputField) ? obj : null);
	}

	internal static GuiInputField CloneSearch(GuiInputField template, Transform parent, string name, string hint)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Expected O, but got Unknown
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Expected O, but got Unknown
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Expected O, but got Unknown
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		GuiInputField obj = Object.Instantiate<GuiInputField>(template, parent, false);
		((Object)obj).name = name;
		((TMP_InputField)obj).onValueChanged = new OnChangeEvent();
		((TMP_InputField)obj).onSelect = new SelectionEvent();
		((TMP_InputField)obj).onDeselect = new SelectionEvent();
		((TMP_InputField)obj).onSubmit = new SubmitEvent();
		((TMP_InputField)obj).onEndEdit = new SubmitEvent();
		Navigation navigation = default(Navigation);
		((Navigation)(ref navigation)).mode = (Mode)3;
		((Selectable)obj).navigation = navigation;
		((TMP_InputField)obj).shouldActivateOnSelect = false;
		((TMP_InputField)obj).restoreOriginalTextOnEscape = false;
		obj.VirtualKeyboardOnActivate = true;
		obj.VirtualKeyboardTitle = hint;
		QuartermasterGamepadFocus.RemoveTemplateHotkey((Selectable)(object)obj);
		((TMP_InputField)obj).characterLimit = 80;
		Graphic placeholder = ((TMP_InputField)obj).placeholder;
		TMP_Text val = (TMP_Text)(object)((placeholder is TMP_Text) ? placeholder : null);
		if (val != null)
		{
			val.text = hint;
		}
		return obj;
	}

	private Button MakeButton(string label, Transform parent, float left, float right, float top)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Expected O, but got Unknown
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		Button obj = Object.Instantiate<Button>(gui.m_stackAllButton, parent, false);
		((Object)obj).name = "Quartermaster " + label;
		obj.onClick = new ButtonClickedEvent();
		QuartermasterGamepadFocus.RemoveTemplateHotkey((Selectable)(object)obj);
		((Selectable)obj).interactable = true;
		Navigation navigation = ((Selectable)obj).navigation;
		((Navigation)(ref navigation)).mode = (Mode)3;
		((Selectable)obj).navigation = navigation;
		((Component)obj).GetComponentInChildren<TMP_Text>().text = label;
		Position((RectTransform)((Component)obj).transform, left, right, top, 28f);
		((Component)obj).gameObject.SetActive(true);
		return obj;
	}

	private static void Position(RectTransform rect, float left, float right, float top, float height)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		rect.anchorMin = new Vector2(left, 0f);
		rect.anchorMax = new Vector2(right, 0f);
		rect.offsetMin = new Vector2(0f, top - height);
		rect.offsetMax = new Vector2(0f, top);
		((Transform)rect).localScale = Vector3.one;
	}

	private void SetCategory(Category choice)
	{
		category = choice;
		filterLabel.text = CategoryNames[(int)choice];
		CloseCategories();
		RefreshFilter();
		if (gamepad.Active)
		{
			QuartermasterGamepadFocus.Select((Selectable)(object)filter);
		}
	}

	private void RefreshFilter()
	{
		filterRevision++;
		pageSearchStatus = null;
		filterNeedsRefresh = true;
		jumpToMatch = Filtering;
		((Selectable)clear).interactable = Filtering;
		previousPageLabel.text = (Filtering ? "Prev match" : "Prev");
		nextPageLabel.text = (Filtering ? "Next match" : "Next");
		((Component)bulkHint).gameObject.SetActive(Filtering && !((Component)bankPage).gameObject.activeSelf);
		if (Filtering && !bulkDisabled)
		{
			takeAllEnabled = ((Selectable)gui.m_takeAllButton).interactable;
			stackAllEnabled = ((Selectable)gui.m_stackAllButton).interactable;
			((Selectable)gui.m_takeAllButton).interactable = false;
			((Selectable)gui.m_stackAllButton).interactable = false;
			bulkDisabled = true;
		}
		else if (!Filtering)
		{
			WatchInventory(null);
			RestoreSlots();
			RestoreBulkActions();
			results.text = "";
		}
		if (gamepad.Active)
		{
			ConfigureGamepadControls();
		}
	}

	private void TurnPage(int direction)
	{
		pageSearchStatus = null;
		filterNeedsRefresh = Filtering;
		QuartermasterPlugin.TurnBankPage(direction, Filtering ? new Func<ItemData, bool>(Matches) : null);
	}

	private void EndSession()
	{
		gamepad.Release(delegate
		{
			RestoreBulkNavigation();
		});
		container = null;
		renderedGrid = default((int, int));
		ResetViewportSlots();
		((TMP_InputField)search).DeactivateInputField(false);
		((TMP_InputField)search).SetTextWithoutNotify("");
		query = "";
		SetCategory(Category.All);
		((Component)search).gameObject.SetActive(false);
		((Component)filter).gameObject.SetActive(false);
		((Component)clear).gameObject.SetActive(false);
		((Component)results).gameObject.SetActive(false);
		RefreshBankPagination();
	}

	private void RefreshBankPagination()
	{
		(int, int) tuple = (Object.op_Implicit((Object)(object)container) ? QuartermasterPlugin.VisibleBankPages() : default((int, int)));
		(int, int) tuple2 = tuple;
		(int, int) tuple3 = renderedPage;
		if (tuple2.Item1 == tuple3.Item1 && tuple2.Item2 == tuple3.Item2)
		{
			return;
		}
		renderedPage = tuple;
		bool flag = tuple.Item2 > 1;
		((Component)previousPage).gameObject.SetActive(flag);
		((Component)nextPage).gameObject.SetActive(flag);
		((Component)bankPage).gameObject.SetActive(flag);
		((Component)bulkHint).gameObject.SetActive(Object.op_Implicit((Object)(object)container) && Filtering && !flag);
		if (flag)
		{
			bankPage.text = $"{tuple.Item1 + 1} / {tuple.Item2}";
			EventSystem current = EventSystem.current;
			GameObject val = ((current != null) ? current.currentSelectedGameObject : null);
			((Selectable)previousPage).interactable = tuple.Item1 > 0;
			((Selectable)nextPage).interactable = tuple.Item1 + 1 < tuple.Item2;
			if (gamepad.Active && (Object)(object)val == (Object)(object)((Component)previousPage).gameObject && !((Selectable)previousPage).interactable)
			{
				QuartermasterGamepadFocus.Select((Selectable)(object)nextPage);
			}
			else if (gamepad.Active && (Object)(object)val == (Object)(object)((Component)nextPage).gameObject && !((Selectable)nextPage).interactable)
			{
				QuartermasterGamepadFocus.Select((Selectable)(object)previousPage);
			}
		}
		if (gamepad.Active)
		{
			ConfigureGamepadControls();
		}
	}

	private void ToggleCategories()
	{
		if (CloseCategories())
		{
			return;
		}
		categories.SetActive(true);
		if (gamepad.Active)
		{
			for (int i = 0; i < categoryButtons.Length; i++)
			{
				int num = i % 3;
				QuartermasterGamepadFocus.SetNavigation((Selectable)(object)categoryButtons[i], (Selectable)(object)((num > 0) ? categoryButtons[i - 1] : null), (Selectable)(object)((num + 1 < 3) ? categoryButtons[i + 1] : null), (Selectable)(object)((i >= 3) ? categoryButtons[i - 3] : null), (Selectable)(object)((i + 3 < categoryButtons.Length) ? categoryButtons[i + 3] : null));
			}
			QuartermasterGamepadFocus.Select((Selectable)(object)categoryButtons[(int)category]);
		}
	}

	private bool CloseCategories()
	{
		if (!categories.activeSelf)
		{
			return false;
		}
		categories.SetActive(false);
		if (gamepad.Active)
		{
			QuartermasterGamepadFocus.Select((Selectable)(object)filter);
		}
		return true;
	}

	private void EnterGamepadControls()
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		SetInventoryGroup?.Invoke(gui, new object[2]
		{
			gui.ContainerGrid.m_uiGroup,
			false
		});
		takeAllNavigation = ((Selectable)gui.m_takeAllButton).navigation;
		stackAllNavigation = ((Selectable)gui.m_stackAllButton).navigation;
		ConfigureGamepadControls();
	}

	private void FocusBelowVault(Vector2i position)
	{
		if (Object.op_Implicit((Object)(object)container) && !UnifiedPopup.IsVisible())
		{
			gamepad.EnterControls(EnterGamepadControls, CloseCategories);
		}
	}

	private void ConfigureGamepadControls()
	{
		Button takeAllButton = gui.m_takeAllButton;
		Button stackAllButton = gui.m_stackAllButton;
		Button val = ((((Component)previousPage).gameObject.activeSelf && ((Selectable)previousPage).interactable) ? previousPage : null);
		Button val2 = ((((Component)nextPage).gameObject.activeSelf && ((Selectable)nextPage).interactable) ? nextPage : null);
		QuartermasterGamepadFocus.SetNavigation((Selectable)(object)search, null, (Selectable)(object)filter, (Selectable)(object)takeAllButton, (Selectable)(object)(Object.op_Implicit((Object)(object)val) ? val : val2));
		QuartermasterGamepadFocus.SetNavigation((Selectable)(object)filter, (Selectable)(object)search, (Selectable)(object)clear, (Selectable)(object)takeAllButton, (Selectable)(object)(Object.op_Implicit((Object)(object)val2) ? val2 : val));
		QuartermasterGamepadFocus.SetNavigation((Selectable)(object)clear, (Selectable)(object)filter, null, (Selectable)(object)stackAllButton, (Selectable)(object)(Object.op_Implicit((Object)(object)val2) ? val2 : val));
		QuartermasterGamepadFocus.SetNavigation((Selectable)(object)takeAllButton, null, (Selectable)(object)stackAllButton, null, (Selectable)(object)filter);
		QuartermasterGamepadFocus.SetNavigation((Selectable)(object)stackAllButton, (Selectable)(object)takeAllButton, null, null, (Selectable)(object)(((Selectable)clear).interactable ? clear : filter));
		if (Object.op_Implicit((Object)(object)val))
		{
			QuartermasterGamepadFocus.SetNavigation((Selectable)(object)val, null, (Selectable)(object)val2, (Selectable)(object)search);
		}
		if (Object.op_Implicit((Object)(object)val2))
		{
			QuartermasterGamepadFocus.SetNavigation((Selectable)(object)val2, (Selectable)(object)val, null, (Selectable)(object)filter);
		}
	}

	private void RestoreBulkNavigation()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		((Selectable)gui.m_takeAllButton).navigation = takeAllNavigation;
		((Selectable)gui.m_stackAllButton).navigation = stackAllNavigation;
	}

	private void LeaveGamepadControls(GameObject previous)
	{
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		RestoreBulkNavigation();
		if (Filtering)
		{
			ItemData val = null;
			foreach (ItemData allItem in container.GetInventory().GetAllItems())
			{
				if (Matches(allItem) && (val == null || allItem.m_gridPos.y < val.m_gridPos.y || (allItem.m_gridPos.y == val.m_gridPos.y && allItem.m_gridPos.x < val.m_gridPos.x)))
				{
					val = allItem;
				}
			}
			if (val != null)
			{
				gui.ContainerGrid.SetGamepadSelection(val.m_gridPos);
			}
		}
		RectTransform gamepadSelectedElement = gui.ContainerGrid.GetGamepadSelectedElement();
		if (Object.op_Implicit((Object)(object)gamepadSelectedElement))
		{
			QuartermasterGamepadFocus.Select(((Component)gamepadSelectedElement).GetComponent<Selectable>());
		}
	}

	private void OnDestroy()
	{
		if (Object.op_Implicit((Object)(object)gui) && Object.op_Implicit((Object)(object)gui.ContainerGrid))
		{
			InventoryGrid containerGrid = gui.ContainerGrid;
			containerGrid.OnMoveToLowerInventoryGrid = (Action<Vector2i>)Delegate.Remove(containerGrid.OnMoveToLowerInventoryGrid, new Action<Vector2i>(FocusBelowVault));
		}
		WatchInventory(null);
	}

	private void WatchInventory(Inventory inventory)
	{
		if (observedInventory != inventory)
		{
			if (observedInventory != null)
			{
				Inventory obj = observedInventory;
				obj.m_onChanged = (Action)Delegate.Remove(obj.m_onChanged, new Action(InvalidateFilter));
			}
			observedInventory = inventory;
			if (observedInventory != null)
			{
				Inventory obj2 = observedInventory;
				obj2.m_onChanged = (Action)Delegate.Combine(obj2.m_onChanged, new Action(InvalidateFilter));
			}
			filterNeedsRefresh = true;
		}
	}

	private void InvalidateFilter()
	{
		filterNeedsRefresh = true;
	}

	private void RestoreBulkActions()
	{
		if (bulkDisabled)
		{
			((Selectable)gui.m_takeAllButton).interactable = takeAllEnabled;
			((Selectable)gui.m_stackAllButton).interactable = stackAllEnabled;
			bulkDisabled = false;
		}
	}

	private void RestoreSlots()
	{
		foreach (CanvasGroup value in hiddenSlots.Values)
		{
			if (Object.op_Implicit((Object)(object)value))
			{
				value.alpha = 1f;
				value.blocksRaycasts = true;
			}
		}
		hiddenSlots.Clear();
		hiddenPositions.Clear();
	}

	private void ResetViewportSlots()
	{
		foreach (GameObject offscreenSlot in offscreenSlots)
		{
			if (Object.op_Implicit((Object)(object)offscreenSlot))
			{
				offscreenSlot.SetActive(true);
			}
		}
		offscreenSlots.Clear();
		viewportFirstSlot = null;
	}

	private void CullOffscreenSlots(InventoryGrid grid, Inventory inventory, List<InventoryElement> elements, Vector2i selected)
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: 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)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: 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_014c: Unknown result type (might be due to invalid IL or missing references)
		if (inventory.GetHeight() < 15 || elements.Count == 0 || ZInput.IsTouchActive())
		{
			if (Object.op_Implicit((Object)(object)viewportFirstSlot))
			{
				ResetViewportSlots();
			}
			return;
		}
		ScrollRect componentInParent = ((Component)grid.m_gridRoot).GetComponentInParent<ScrollRect>();
		if (!Object.op_Implicit((Object)(object)componentInParent))
		{
			return;
		}
		RectTransform val = (RectTransform)(Object.op_Implicit((Object)(object)componentInParent.viewport) ? ((object)componentInParent.viewport) : ((object)(RectTransform)((Component)componentInParent).transform));
		Rect rect = val.rect;
		if (((Rect)(ref rect)).height <= 0f || grid.m_elementSpace <= 0f)
		{
			return;
		}
		RectTransform gridRoot = grid.m_gridRoot;
		InventoryElement val2 = elements[0];
		RectTransform elementRectTransform = val2.GetElementRectTransform();
		rect = elementRectTransform.rect;
		float y = ((Transform)gridRoot).InverseTransformPoint(((Transform)elementRectTransform).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center))).y;
		rect = val.rect;
		float y2 = ((Transform)gridRoot).InverseTransformPoint(((Transform)val).TransformPoint(0f, ((Rect)(ref rect)).yMax, 0f)).y;
		rect = val.rect;
		float y3 = ((Transform)gridRoot).InverseTransformPoint(((Transform)val).TransformPoint(0f, ((Rect)(ref rect)).yMin, 0f)).y;
		(int, int, int) tuple = (Mathf.FloorToInt((y - y2) / grid.m_elementSpace) - 2, Mathf.CeilToInt((y - y3) / grid.m_elementSpace) + 2, ZInput.IsExclusiveGamepadActive() ? selected.y : (-1));
		if (viewportFirstSlot == val2)
		{
			(int, int, int) tuple2 = visibleRows;
			(int, int, int) tuple3 = tuple;
			if (tuple2.Item1 == tuple3.Item1 && tuple2.Item2 == tuple3.Item2 && tuple2.Item3 == tuple3.Item3)
			{
				return;
			}
		}
		viewportFirstSlot = val2;
		visibleRows = tuple;
		offscreenSlots.Clear();
		int width = inventory.GetWidth();
		for (int i = 0; i < elements.Count; i++)
		{
			int num = i / width;
			bool flag = num == tuple.Item3 || (num >= tuple.Item1 && num <= tuple.Item2);
			GameObject gameObject = ((Component)elements[i]).gameObject;
			if (gameObject.activeSelf != flag)
			{
				gameObject.SetActive(flag);
			}
			if (!flag)
			{
				offscreenSlots.Add(gameObject);
			}
		}
	}

	private bool Matches(ItemData item)
	{
		return Matches(item, category, query);
	}

	internal static bool Matches(ItemData item, Category category, string query)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		if (category == Category.All || GetCategory(item.m_shared.m_itemType) == category)
		{
			if (query.Length != 0)
			{
				return Localization.instance.Localize(item.m_shared.m_name).IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0;
			}
			return true;
		}
		return false;
	}

	private static Category GetCategory(ItemType type)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or