Decompiled source of RuneStorage v0.1.0

BepInEx/plugins/RuneStorage.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using RuneStorage.Core;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("RuneStorage")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+6c55c5e0291d631cddc8abbf6fc0fa805fa5f8d3")]
[assembly: AssemblyProduct("RuneStorage")]
[assembly: AssemblyTitle("RuneStorage")]
[assembly: AssemblyVersion("0.1.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;
		}
	}
}
namespace RuneStorage
{
	[HarmonyPatch(typeof(Container), "Load")]
	internal static class CoreContainerLoadPatch
	{
		[HarmonyPrefix]
		private static bool BeforeLoad(Container __instance)
		{
			try
			{
				return CoreTierRuntime.PrepareInventoryForLoad(__instance);
			}
			catch (Exception ex)
			{
				RuneStorageCoreMarker runeStorageCoreMarker = CoreTierRuntime.FindMarker(__instance);
				if ((Object)(object)runeStorageCoreMarker != (Object)null)
				{
					runeStorageCoreMarker.SetReadOnly("Tier setup failed before item loading (" + ex.GetType().Name + ": " + ex.Message + ").");
					return false;
				}
				throw;
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Interact")]
	internal static class CoreContainerInteractionPatch
	{
		[HarmonyPrefix]
		private static bool BeforeInteract(Container __instance, object[] __args)
		{
			RuneStorageTerminalMarker componentInParent = ((Component)__instance).GetComponentInParent<RuneStorageTerminalMarker>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				RuneStorageTerminalPanel.Open(__args?.OfType<Player>().FirstOrDefault() ?? Player.m_localPlayer, componentInParent);
				return false;
			}
			return (Object)(object)CoreTierRuntime.FindMarker(__instance) == (Object)null;
		}
	}
	[HarmonyPatch(typeof(Container), "GetHoverName")]
	internal static class CoreContainerHoverNamePatch
	{
		[HarmonyPrefix]
		private static bool BeforeGetHoverName(Container __instance, ref string __result)
		{
			if ((Object)(object)CoreTierRuntime.FindMarker(__instance) == (Object)null)
			{
				return true;
			}
			__result = "RuneStorage Core";
			return false;
		}
	}
	[HarmonyPatch(typeof(Container), "GetHoverText")]
	internal static class CoreContainerHoverTextPatch
	{
		[HarmonyPrefix]
		private static bool BeforeGetHoverText(Container __instance, ref string __result)
		{
			RuneStorageCoreMarker runeStorageCoreMarker = CoreTierRuntime.FindMarker(__instance);
			if ((Object)(object)runeStorageCoreMarker == (Object)null)
			{
				return true;
			}
			__result = (runeStorageCoreMarker.IsReadOnly ? ("RuneStorage Core is unavailable: " + runeStorageCoreMarker.StatusMessage) : "Access storage through a nearby RuneStorage Terminal.");
			return false;
		}
	}
	[HarmonyPatch(typeof(Container), "GetHoverName")]
	internal static class TerminalContainerHoverNamePatch
	{
		[HarmonyPrefix]
		private static bool BeforeGetHoverName(Container __instance, ref string __result)
		{
			if ((Object)(object)((Component)__instance).GetComponentInParent<RuneStorageTerminalMarker>() == (Object)null)
			{
				return true;
			}
			__result = "RuneStorage Terminal";
			return false;
		}
	}
	[HarmonyPatch(typeof(Container), "GetHoverText")]
	internal static class TerminalContainerHoverTextPatch
	{
		[HarmonyPrefix]
		private static bool BeforeGetHoverText(Container __instance, ref string __result)
		{
			if ((Object)(object)((Component)__instance).GetComponentInParent<RuneStorageTerminalMarker>() == (Object)null)
			{
				return true;
			}
			string text = "Open RuneStorage";
			if (Localization.instance != null)
			{
				text = Localization.instance.Localize("[<color=yellow><b>$KEY_Use</b></color>] Open RuneStorage");
			}
			__result = text;
			return false;
		}
	}
	internal static class CorePiece
	{
		private const string PieceName = "piece_runestorage_core";

		private const string VisualPrefabName = "RuneStorage_Core_Visual";

		private const string IconAssetPath = "Assets/RuneStorage/Core/Icons/RuneStorage_Core_Icon.png";

		private const string BundleResourceSuffix = ".Assets.AssetBundles.runestorage_core";

		private static bool _registered;

		private static AssetBundle _visualBundle;

		public static void Register()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			if (_registered)
			{
				return;
			}
			string text = FindVerifiedBuildPiecePrefabName();
			if (text == null || !LoadBundle())
			{
				return;
			}
			GameObject val = _visualBundle.LoadAsset<GameObject>("RuneStorage_Core_Visual");
			Sprite val2 = _visualBundle.LoadAsset<Sprite>("Assets/RuneStorage/Core/Icons/RuneStorage_Core_Icon.png");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"RuneStorage Core visual 'RuneStorage_Core_Visual' was not found in the embedded AssetBundle.");
				return;
			}
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogError((object)"RuneStorage Core icon 'Assets/RuneStorage/Core/Icons/RuneStorage_Core_Icon.png' was not found in the embedded AssetBundle.");
				return;
			}
			PieceConfig val3 = new PieceConfig();
			val3.PieceTable = "Hammer";
			val3.Category = "RuneStorage";
			val3.Name = "RuneStorage Core";
			val3.Description = "The storage core for a nearby RuneStorage Terminal.";
			val3.CraftingStation = CraftingStations.Forge;
			val3.Icon = val2;
			val3.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig
				{
					Item = "Bronze",
					Amount = 10,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "FineWood",
					Amount = 10,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "SurtlingCore",
					Amount = 4,
					Recover = true
				}
			};
			CustomPiece val4 = new CustomPiece("piece_runestorage_core", text, val3);
			AttachVisual(val4.PiecePrefab, val);
			Container[] componentsInChildren = val4.PiecePrefab.GetComponentsInChildren<Container>(true);
			if (componentsInChildren.Length != 1)
			{
				Plugin.Log.LogError((object)(string.Format("RuneStorage Core clone '{0}' must contain exactly one inherited Container; found {1}. ", "piece_runestorage_core", componentsInChildren.Length) + "Refusing to register a Core without a single native storage inventory."));
				return;
			}
			if (!CoreTierCapacity.TryGetDimensions(1, out var width, out var height))
			{
				Plugin.Log.LogError((object)"Tier I RuneStorage Core dimensions are missing; refusing to register the Core.");
				return;
			}
			componentsInChildren[0].m_width = width;
			componentsInChildren[0].m_height = height;
			val4.PiecePrefab.AddComponent<RuneStorageCoreMarker>();
			Piece component = val4.PiecePrefab.GetComponent<Piece>();
			if ((Object)(object)component == (Object)null)
			{
				Plugin.Log.LogError((object)"RuneStorage Core clone 'piece_runestorage_core' has no Piece component after named cloning.");
				return;
			}
			component.m_canBeRemoved = true;
			PieceManager.Instance.AddPiece(val4);
			_registered = true;
			Plugin.Log.LogInfo((object)("Registered piece_runestorage_core with verified base prefab '" + text + "', visual 'RuneStorage_Core_Visual', Core icon, Forge requirement, Hammer costs 10 Bronze, 10 Fine Wood, and 4 Surtling Cores, " + $"and native Container capacity {width}x{height} ({width * height} slots)."));
		}

		private static string FindVerifiedBuildPiecePrefabName()
		{
			GameObject prefab = Cache.GetPrefab<GameObject>("piece_chest_wood");
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.Log.LogError((object)"No verified RuneStorage Core build-piece base was found in PrefabManager.Cache. Probed: piece_chest_wood");
				return null;
			}
			if ((Object)(object)prefab.GetComponent<Piece>() == (Object)null)
			{
				Plugin.Log.LogError((object)"PrefabManager.Cache contains 'piece_chest_wood', but it has no Piece component; refusing to register the Core.");
				return null;
			}
			Plugin.Log.LogInfo((object)"Verified RuneStorage Core base prefab in PrefabManager.Cache: 'piece_chest_wood'.");
			return "piece_chest_wood";
		}

		private static bool LoadBundle()
		{
			if ((Object)(object)_visualBundle != (Object)null)
			{
				return true;
			}
			Assembly assembly = typeof(CorePiece).Assembly;
			string text = assembly.GetManifestResourceNames().FirstOrDefault((string name) => name.EndsWith(".Assets.AssetBundles.runestorage_core", StringComparison.OrdinalIgnoreCase));
			if (text == null)
			{
				Plugin.Log.LogError((object)("Embedded Core AssetBundle ending with '.Assets.AssetBundles.runestorage_core' was not found. Resources: " + string.Join(", ", assembly.GetManifestResourceNames())));
				return false;
			}
			using (Stream stream = assembly.GetManifestResourceStream(text))
			{
				using MemoryStream memoryStream = new MemoryStream();
				if (stream == null)
				{
					Plugin.Log.LogError((object)("Embedded Core AssetBundle resource '" + text + "' returned a null stream."));
					return false;
				}
				stream.CopyTo(memoryStream);
				_visualBundle = AssetBundle.LoadFromMemory(memoryStream.ToArray());
			}
			if ((Object)(object)_visualBundle == (Object)null)
			{
				Plugin.Log.LogError((object)"AssetBundle.LoadFromMemory returned null for the RuneStorage Core bundle.");
				return false;
			}
			Plugin.Log.LogInfo((object)("Loaded RuneStorage Core AssetBundle resource '" + text + "'."));
			return true;
		}

		private static void AttachVisual(GameObject functionalPrefab, GameObject visualSource)
		{
			//IL_0031: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(visualSource);
			((Object)val).name = "RuneStorage_Core_Visual";
			val.SetActive(true);
			val.transform.SetParent(functionalPrefab.transform, false);
			val.transform.localPosition = Vector3.zero;
			val.transform.localRotation = Quaternion.identity;
			val.transform.localScale = Vector3.one;
			Renderer[] componentsInChildren = functionalPrefab.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren)
			{
				if (!((Object)(object)((Component)val2).transform == (Object)(object)val.transform) && !((Component)val2).transform.IsChildOf(val.transform))
				{
					val2.enabled = false;
				}
			}
		}
	}
	internal static class CoreRemovalGuard
	{
		private const float NoticeCooldownSeconds = 2f;

		private static float _lastNoticeTime = -10f;

		internal static void NoticeBlocked()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			string text = ((Humanoid)localPlayer).GetCurrentWeapon()?.m_shared?.m_name;
			if (!string.IsNullOrEmpty(text) && text.IndexOf("hammer", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (!(realtimeSinceStartup - _lastNoticeTime < 2f))
				{
					_lastNoticeTime = realtimeSinceStartup;
					((Character)localPlayer).Message((MessageType)2, "This RuneStorage Core still holds items. Empty it before removing it.", 0, (Sprite)null, false);
				}
			}
		}

		internal static bool BlocksRemoval(Component root)
		{
			if ((Object)(object)root == (Object)null)
			{
				return false;
			}
			if ((Object)(object)(root.GetComponent<RuneStorageCoreMarker>() ?? root.GetComponentInChildren<RuneStorageCoreMarker>(true) ?? root.GetComponentInParent<RuneStorageCoreMarker>()) == (Object)null)
			{
				return false;
			}
			Container val = root.GetComponent<Container>() ?? root.GetComponentInChildren<Container>(true);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Inventory inventory = val.GetInventory();
			if (inventory != null)
			{
				return inventory.GetAllItems().Any((ItemData item) => item != null && item.m_stack > 0);
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Piece), "CanBeRemoved")]
	internal static class CorePieceRemovalPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Piece __instance, ref bool __result)
		{
			if (__result && CoreRemovalGuard.BlocksRemoval((Component)(object)__instance))
			{
				__result = false;
				CoreRemovalGuard.NoticeBlocked();
			}
		}
	}
	[HarmonyPatch(typeof(Container), "CanBeRemoved")]
	internal static class CoreContainerRemovalPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Container __instance, ref bool __result)
		{
			if (__result && CoreRemovalGuard.BlocksRemoval((Component)(object)__instance))
			{
				__result = false;
				CoreRemovalGuard.NoticeBlocked();
			}
		}
	}
	internal static class CoreTierRuntime
	{
		internal const string TierZdoKey = "RuneStorageCoreTier";

		internal const int InitialTier = 1;

		internal static bool PrepareInventoryForLoad(Container container)
		{
			RuneStorageCoreMarker runeStorageCoreMarker = FindMarker(container);
			if ((Object)(object)runeStorageCoreMarker == (Object)null)
			{
				return true;
			}
			ZNetView val = FindNetworkView(container);
			if ((Object)(object)val == (Object)null)
			{
				runeStorageCoreMarker.SetReadOnly("The Core's ZNetView could not be found.");
				return false;
			}
			ZDO zDO = val.GetZDO();
			if (zDO == null)
			{
				runeStorageCoreMarker.SetReadOnly("The Core's ZDO is not available yet.");
				return false;
			}
			int num = default(int);
			bool flag = zDO.GetInt("RuneStorageCoreTier", ref num);
			if (!flag)
			{
				num = 1;
			}
			if (!CoreTierCapacity.TryGetDimensions(num, out var width, out var height))
			{
				runeStorageCoreMarker.SetReadOnly($"Saved capacity tier {num} is not supported.");
				return false;
			}
			Inventory inventory = container.GetInventory();
			if (inventory == null)
			{
				runeStorageCoreMarker.SetReadOnly("The native Container has no Inventory.");
				return false;
			}
			if (inventory.GetWidth() != width)
			{
				runeStorageCoreMarker.SetReadOnly($"The native inventory width is {inventory.GetWidth()}, but tier {num} requires width {width}.");
				return false;
			}
			int height2 = inventory.GetHeight();
			if (height2 > height)
			{
				runeStorageCoreMarker.SetReadOnly($"The live inventory has {height2} rows, but saved tier {num} allows only {height}; refusing to hide items.");
				return false;
			}
			if (height2 < height)
			{
				inventory.SetHeight(height);
			}
			if (!flag && val.IsOwner())
			{
				zDO.Set("RuneStorageCoreTier", num);
			}
			runeStorageCoreMarker.ClearReadOnly();
			if (runeStorageCoreMarker.ShouldLogTier(num))
			{
				Plugin.Log.LogInfo((object)$"RuneStorage Core '{((Object)runeStorageCoreMarker).name}' loaded at tier {num} ({width * height} slots).");
			}
			return true;
		}

		internal static RuneStorageCoreMarker FindMarker(Container container)
		{
			if (!((Object)(object)container == (Object)null))
			{
				return ((Component)container).GetComponentInParent<RuneStorageCoreMarker>();
			}
			return null;
		}

		private static ZNetView FindNetworkView(Container container)
		{
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null)
			{
				return component;
			}
			component = ((Component)container).GetComponentInParent<ZNetView>();
			if ((Object)(object)component != (Object)null)
			{
				return component;
			}
			return ((Component)container).GetComponentInChildren<ZNetView>(true);
		}
	}
	internal static class RuneStorageCoreAccess
	{
		internal const float TerminalUseDistance = 5f;

		internal const float CoreRange = 12f;

		private static readonly MethodInfo CheckAccessMethod = AccessTools.Method(typeof(Container), "CheckAccess", (Type[])null, (Type[])null);

		private static readonly FieldInfo PrivateAreaList = AccessTools.Field(typeof(PrivateArea), "m_allAreas");

		private static readonly MethodInfo PrivateAreaIsEnabled = AccessTools.Method(typeof(PrivateArea), "IsEnabled", (Type[])null, (Type[])null);

		private static readonly MethodInfo PrivateAreaIsInside = AccessTools.Method(typeof(PrivateArea), "IsInside", new Type[2]
		{
			typeof(Vector3),
			typeof(float)
		}, (Type[])null);

		private static readonly MethodInfo PrivateAreaIsPermitted = AccessTools.Method(typeof(PrivateArea), "IsPermitted", new Type[1] { typeof(long) }, (Type[])null);

		internal static bool TryResolve(Player player, RuneStorageTerminalMarker terminal, out RuneStorageCoreMarker marker, out Container container, out string reason)
		{
			//IL_003a: 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_0070: Unknown result type (might be due to invalid IL or missing references)
			marker = null;
			container = null;
			if ((Object)(object)player == (Object)null || (Object)(object)terminal == (Object)null)
			{
				reason = "The terminal or player is no longer available. Move closer and try again.";
				return false;
			}
			if (Vector3.Distance(((Component)player).transform.position, ((Component)terminal).transform.position) > 5f)
			{
				reason = "Move closer to the RuneStorage Terminal.";
				return false;
			}
			if (!HasAreaAccess(((Component)terminal).transform.position, player.GetPlayerID()))
			{
				reason = "This RuneStorage Terminal is inside a ward you do not have access to.";
				return false;
			}
			RuneStorageCoreMarker[] array = (from candidate in Object.FindObjectsByType<RuneStorageCoreMarker>((FindObjectsSortMode)0)
				where (Object)(object)candidate != (Object)null && Vector3.Distance(((Component)candidate).transform.position, ((Component)terminal).transform.position) <= 12f
				select candidate).ToArray();
			if (array.Length == 0)
			{
				reason = "No RuneStorage Core found within 12 meters of this terminal.";
				return false;
			}
			if (array.Length > 1)
			{
				reason = "More than one RuneStorage Core is in range. Keep only one near this terminal.";
				return false;
			}
			marker = array[0];
			Container[] componentsInChildren = ((Component)marker).GetComponentsInChildren<Container>(true);
			if (componentsInChildren.Length != 1)
			{
				reason = $"The RuneStorage Core has {componentsInChildren.Length} native containers; exactly one is required.";
				marker = null;
				return false;
			}
			container = componentsInChildren[0];
			if (marker.IsReadOnly)
			{
				reason = marker.StatusMessage ?? "The RuneStorage Core is read-only because its saved data could not be loaded safely.";
				return false;
			}
			if (container.GetInventory() == null)
			{
				reason = "The RuneStorage Core inventory is not ready. Close this panel and try again.";
				return false;
			}
			if (!HasAccess(container, player.GetPlayerID()))
			{
				reason = "You do not have access to this RuneStorage Core.";
				return false;
			}
			reason = null;
			return true;
		}

		internal static bool HasAreaAccess(Vector3 point, long playerId)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (PrivateAreaList == null || PrivateAreaIsEnabled == null || PrivateAreaIsInside == null || PrivateAreaIsPermitted == null)
			{
				Plugin.Log.LogWarning((object)"RuneStorage could not verify ward access (PrivateArea members not found); denying terminal and Core access.");
				return false;
			}
			try
			{
				if (!(PrivateAreaList.GetValue(null) is IEnumerable enumerable))
				{
					return false;
				}
				foreach (object item in enumerable)
				{
					PrivateArea val = (PrivateArea)((item is PrivateArea) ? item : null);
					if (val != null && Convert.ToBoolean(PrivateAreaIsEnabled.Invoke(val, null)) && Convert.ToBoolean(PrivateAreaIsInside.Invoke(val, new object[2] { point, 0f })) && !Convert.ToBoolean(PrivateAreaIsPermitted.Invoke(val, new object[1] { playerId })))
					{
						return false;
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"RuneStorage ward access check failed: {ex.GetBaseException()}");
				return false;
			}
		}

		private static bool HasAccess(Container container, long playerId)
		{
			if (CheckAccessMethod == null)
			{
				return false;
			}
			try
			{
				object obj = CheckAccessMethod.Invoke(container, new object[1] { playerId });
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)$"RuneStorage Core access check failed: {ex.GetBaseException()}");
				return false;
			}
		}
	}
	internal sealed class RuneStorageCoreMarker : MonoBehaviour
	{
		private const string CraftRequestRpc = "RuneStorage_CraftRequest";

		private const string CraftResultRpc = "RuneStorage_CraftResult";

		private const string TransferRequestRpc = "RuneStorage_TransferRequest";

		private const string TransferResultRpc = "RuneStorage_TransferResult";

		private const string UpgradeRequestRpc = "RuneStorage_UpgradeRequest";

		private const string UpgradeResultRpc = "RuneStorage_UpgradeResult";

		private static readonly MethodInfo GetPeerMethod = AccessTools.Method(typeof(ZRoutedRpc), "GetPeer", new Type[1] { typeof(long) }, (Type[])null);

		private bool _loadIssueLogged;

		private int _lastLoggedTier;

		private ZNetView _networkView;

		internal bool IsReadOnly { get; private set; }

		internal string StatusMessage { get; private set; }

		internal bool IsOwner
		{
			get
			{
				if ((Object)(object)_networkView != (Object)null)
				{
					return _networkView.IsOwner();
				}
				return false;
			}
		}

		internal ZDO Zdo
		{
			get
			{
				if (!((Object)(object)_networkView != (Object)null))
				{
					return null;
				}
				return _networkView.GetZDO();
			}
		}

		private void Start()
		{
			_networkView = ((Component)this).GetComponent<ZNetView>();
			if ((Object)(object)_networkView == (Object)null)
			{
				_networkView = ((Component)this).GetComponentInParent<ZNetView>();
			}
			if ((Object)(object)_networkView == (Object)null)
			{
				_networkView = ((Component)this).GetComponentInChildren<ZNetView>(true);
			}
			if ((Object)(object)_networkView == (Object)null)
			{
				Plugin.Log.LogWarning((object)("RuneStorage Core '" + ((Object)this).name + "' has no ZNetView for crafting requests."));
				return;
			}
			_networkView.Register<string, bool, string>("RuneStorage_CraftRequest", (Action<long, string, bool, string>)ReceiveCraftRequest);
			_networkView.Register<string, string>("RuneStorage_CraftResult", (Action<long, string, string>)ReceiveCraftResult);
			_networkView.Register<string, string, string, int, int, string>("RuneStorage_TransferRequest", (Method<string, string, string, int, int, string>)ReceiveTransferRequest);
			_networkView.Register<string, bool, string, string>("RuneStorage_TransferResult", (Method<string, bool, string, string>)ReceiveTransferResult);
			_networkView.Register<string, string, string>("RuneStorage_UpgradeRequest", (Action<long, string, string, string>)ReceiveUpgradeRequest);
			_networkView.Register<string, bool, string>("RuneStorage_UpgradeResult", (Action<long, string, bool, string>)ReceiveUpgradeResult);
		}

		private void OnDestroy()
		{
			if (!((Object)(object)_networkView == (Object)null))
			{
				_networkView.Unregister("RuneStorage_CraftRequest");
				_networkView.Unregister("RuneStorage_CraftResult");
				_networkView.Unregister("RuneStorage_TransferRequest");
				_networkView.Unregister("RuneStorage_TransferResult");
				_networkView.Unregister("RuneStorage_UpgradeRequest");
				_networkView.Unregister("RuneStorage_UpgradeResult");
			}
		}

		internal bool SendUpgradeRequest(string requestId, bool paidFromPlayer, string payload)
		{
			if ((Object)(object)_networkView == (Object)null || string.IsNullOrEmpty(requestId))
			{
				return false;
			}
			_networkView.InvokeRPC("RuneStorage_UpgradeRequest", new object[3]
			{
				requestId,
				paidFromPlayer ? "player" : "core",
				payload ?? string.Empty
			});
			return true;
		}

		private void ReceiveUpgradeRequest(long sender, string requestId, string source, string payload)
		{
			if ((Object)(object)_networkView == (Object)null || !_networkView.IsOwner() || string.IsNullOrEmpty(requestId) || requestId.Length > 64)
			{
				return;
			}
			bool ok = false;
			string text = "The upgrade request failed validation. Nothing was upgraded.";
			try
			{
				Player val = FindPlayerForPeer(sender);
				Container val2 = ((Component)this).GetComponent<Container>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)this).GetComponentInChildren<Container>(true);
				}
				RuneStorageTerminalMarker terminal;
				string reason;
				if ((Object)(object)val == (Object)null)
				{
					text = "The Core could not verify the requesting player. Nothing was upgraded.";
				}
				else if ((Object)(object)val2 == (Object)null)
				{
					text = "The Core's native inventory could not be found. Nothing was upgraded.";
				}
				else if (!TryFindTerminalForPlayer(val, out terminal, out reason))
				{
					text = reason;
				}
				else if (source != "core" && source != "player")
				{
					text = "Unknown payment source. Nothing was upgraded.";
				}
				else if (source == "player" && string.IsNullOrEmpty(payload))
				{
					text = "The ingredients for this upgrade were not sent. Nothing was upgraded.";
				}
				else
				{
					List<ItemData> list = null;
					if (source == "player")
					{
						list = RuneStorageTransfers.DeserializeItems(payload);
						if (list == null)
						{
							text = "The ingredients could not be read. Nothing was upgraded.";
						}
					}
					if (source == "core" || list != null)
					{
						text = RuneStorageCoreUpgrade.Upgrade(val, terminal, val2, this, (source == "player") ? RuneStorageUpgradeSource.Player : RuneStorageUpgradeSource.Core, list, out ok);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage upgrade request validation failed: {arg}");
				text = "The upgrade stopped during validation. Check the Core before trying again.";
				ok = false;
			}
			_networkView.InvokeRPC(sender, "RuneStorage_UpgradeResult", new object[3]
			{
				requestId,
				ok,
				text ?? string.Empty
			});
		}

		private void ReceiveUpgradeResult(long sender, string requestId, bool ok, string message)
		{
			ZDO val = (((Object)(object)_networkView != (Object)null) ? _networkView.GetZDO() : null);
			if (val != null && val.GetOwner() == sender)
			{
				RuneStorageTerminalPanel.ReceiveUpgradeStatus(this, requestId, ok, message);
			}
		}

		internal bool SendTransferRequest(string kind, string identity, int amount, int expectedQuantity, string payload, string requestId)
		{
			if ((Object)(object)_networkView == (Object)null || string.IsNullOrEmpty(kind) || string.IsNullOrEmpty(requestId))
			{
				return false;
			}
			_networkView.InvokeRPC("RuneStorage_TransferRequest", new object[6]
			{
				requestId,
				kind,
				identity ?? string.Empty,
				amount,
				expectedQuantity,
				payload ?? string.Empty
			});
			return true;
		}

		private void ReceiveTransferRequest(long sender, string requestId, string kind, string identity, int amount, int expectedQuantity, string payload)
		{
			if ((Object)(object)_networkView == (Object)null || !_networkView.IsOwner() || string.IsNullOrEmpty(requestId) || requestId.Length > 64)
			{
				return;
			}
			bool ok = false;
			string message = "The transfer request failed validation. No items were moved.";
			string responsePayload = string.Empty;
			try
			{
				Player val = FindPlayerForPeer(sender);
				Container val2 = ((Component)this).GetComponent<Container>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)this).GetComponentInChildren<Container>(true);
				}
				RuneStorageTerminalMarker terminal;
				string reason;
				if ((Object)(object)val == (Object)null)
				{
					message = "The Core could not verify the requesting player. No items were moved.";
				}
				else if ((Object)(object)val2 == (Object)null)
				{
					message = "The Core's native inventory could not be found. No items were moved.";
				}
				else if (!TryFindTerminalForPlayer(val, out terminal, out reason))
				{
					message = reason;
				}
				else
				{
					RuneStorageTransfers.HandleRemoteRequest(this, val2, val, kind, identity, amount, expectedQuantity, payload, out ok, out message, out responsePayload);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage transfer request validation failed: {arg}");
				message = "The transfer stopped during validation. Check both inventories before trying again.";
				ok = false;
			}
			_networkView.InvokeRPC(sender, "RuneStorage_TransferResult", new object[4]
			{
				requestId,
				ok,
				message ?? string.Empty,
				responsePayload ?? string.Empty
			});
		}

		private void ReceiveTransferResult(long sender, string requestId, bool ok, string message, string payload)
		{
			ZDO val = (((Object)(object)_networkView != (Object)null) ? _networkView.GetZDO() : null);
			if (val != null && val.GetOwner() == sender)
			{
				string status = RuneStorageTransfers.Complete(this, requestId, ok, message, payload);
				RuneStorageTerminalPanel.ReceiveTransferStatus(this, status);
			}
		}

		internal bool SendCraftRequest(string recipeIdentity, bool outputToCore, string requestId)
		{
			if ((Object)(object)_networkView == (Object)null || string.IsNullOrEmpty(recipeIdentity) || string.IsNullOrEmpty(requestId))
			{
				return false;
			}
			_networkView.InvokeRPC("RuneStorage_CraftRequest", new object[3] { recipeIdentity, outputToCore, requestId });
			return true;
		}

		private void ReceiveCraftRequest(long sender, string recipeIdentity, bool outputToCore, string requestId)
		{
			if ((Object)(object)_networkView == (Object)null || !_networkView.IsOwner() || string.IsNullOrEmpty(requestId) || requestId.Length > 64)
			{
				return;
			}
			string text = "The craft request failed validation. No ingredients were used.";
			try
			{
				Player val = FindPlayerForPeer(sender);
				RuneStorageTerminalMarker terminal;
				string reason;
				if ((Object)(object)val == (Object)null)
				{
					text = "The Core could not verify the requesting player. No ingredients were used.";
				}
				else if (!TryFindTerminalForPlayer(val, out terminal, out reason))
				{
					text = reason;
				}
				else
				{
					Container val2 = ((Component)this).GetComponent<Container>();
					if ((Object)(object)val2 == (Object)null)
					{
						val2 = ((Component)this).GetComponentInChildren<Container>(true);
					}
					text = (((Object)(object)val2 == (Object)null) ? "The Core's native inventory could not be found. No ingredients were used." : RuneStorageCrafting.Craft(val, terminal, this, recipeIdentity, outputToCore));
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage craft request validation failed: {arg}");
				text = "The craft request stopped during validation. Check both inventories before trying again.";
			}
			_networkView.InvokeRPC(sender, "RuneStorage_CraftResult", new object[2] { requestId, text });
		}

		private void ReceiveCraftResult(long sender, string requestId, string result)
		{
			ZDO val = (((Object)(object)_networkView != (Object)null) ? _networkView.GetZDO() : null);
			if (val != null && val.GetOwner() == sender)
			{
				RuneStorageTerminalPanel.ReceiveCraftResult(this, requestId, result);
			}
		}

		private bool TryFindTerminalForPlayer(Player player, out RuneStorageTerminalMarker terminal, out string reason)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			terminal = null;
			List<RuneStorageTerminalMarker> list = new List<RuneStorageTerminalMarker>();
			RuneStorageTerminalMarker[] array = Object.FindObjectsByType<RuneStorageTerminalMarker>((FindObjectsSortMode)0);
			foreach (RuneStorageTerminalMarker runeStorageTerminalMarker in array)
			{
				if (!((Object)(object)runeStorageTerminalMarker == (Object)null) && !(Vector3.Distance(((Component)player).transform.position, ((Component)runeStorageTerminalMarker).transform.position) > 5f) && RuneStorageCoreAccess.TryResolve(player, runeStorageTerminalMarker, out var marker, out var _, out var _) && (Object)(object)marker == (Object)(object)this)
				{
					list.Add(runeStorageTerminalMarker);
				}
			}
			if (list.Count == 1)
			{
				terminal = list[0];
				reason = null;
				return true;
			}
			reason = ((list.Count == 0) ? "Move within range of a RuneStorage Terminal connected to this Core." : "More than one RuneStorage Terminal is connected to this Core nearby. Use one terminal at a time.");
			return false;
		}

		private static Player FindPlayerForPeer(long peerId)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			ZRoutedRpc instance = ZRoutedRpc.instance;
			ZNetPeer val = (ZNetPeer)((instance != null && GetPeerMethod != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if (val == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			GameObject val2 = ZNetScene.instance.FindInstance(val.m_characterID);
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			Player component = val2.GetComponent<Player>();
			if (!((Object)(object)component != (Object)null))
			{
				return val2.GetComponentInChildren<Player>(true);
			}
			return component;
		}

		internal void SetReadOnly(string reason)
		{
			IsReadOnly = true;
			StatusMessage = reason;
			if (!_loadIssueLogged)
			{
				_loadIssueLogged = true;
				Plugin.Log.LogError((object)("RuneStorage Core '" + ((Object)this).name + "' is read-only: " + reason));
			}
		}

		internal void ClearReadOnly()
		{
			IsReadOnly = false;
			StatusMessage = null;
			_loadIssueLogged = false;
		}

		internal bool ShouldLogTier(int tier)
		{
			if (_lastLoggedTier == tier)
			{
				return false;
			}
			_lastLoggedTier = tier;
			return true;
		}
	}
	internal enum RuneStorageUpgradeSource
	{
		Core,
		Player
	}
	internal static class RuneStorageCoreUpgrade
	{
		internal static int CurrentTier(ZDO zdo)
		{
			int result = default(int);
			if (zdo == null || !zdo.GetInt("RuneStorageCoreTier", ref result))
			{
				return 1;
			}
			return result;
		}

		internal static string ItemNameOf(ItemData item)
		{
			if (item == null || item.m_shared == null)
			{
				return null;
			}
			if (!((Object)(object)item.m_dropPrefab != (Object)null))
			{
				return item.m_shared.m_name;
			}
			return ((Object)item.m_dropPrefab).name;
		}

		internal static long StoredCount(Inventory inventory, string itemName, bool excludeEquipped)
		{
			if (inventory == null || string.IsNullOrEmpty(itemName))
			{
				return 0L;
			}
			return (from item in inventory.GetAllItems()
				where item != null && item.m_stack > 0 && (!excludeEquipped || !item.m_equipped) && string.Equals(ItemNameOf(item), itemName, StringComparison.Ordinal)
				select item).Sum((Func<ItemData, long>)((ItemData item) => item.m_stack));
		}

		internal static string SourceLabel(RuneStorageUpgradeSource source)
		{
			if (source != RuneStorageUpgradeSource.Player)
			{
				return "the Core";
			}
			return "your inventory";
		}

		internal static string Describe(Container core, Player player, int currentTier, RuneStorageUpgradeSource source)
		{
			CoreTierCapacity.TryGetSlotCount(currentTier, out var slots);
			if (currentTier >= 3)
			{
				return $"The Core is at its highest tier: Tier {CoreTierUpgrades.RomanNumeral(currentTier)}, {slots} slots.";
			}
			int num = currentTier + 1;
			if (!CoreTierUpgrades.TryGetUpgrade(num, out var stationName, out var requirements) || !CoreTierCapacity.TryGetSlotCount(num, out var slots2))
			{
				return "This tier has no upgrade defined.";
			}
			Inventory inventory = ((source != RuneStorageUpgradeSource.Player) ? (((Object)(object)core != (Object)null) ? core.GetInventory() : null) : (((Object)(object)player != (Object)null) ? ((Humanoid)player).GetInventory() : null));
			bool excludeEquipped = source == RuneStorageUpgradeSource.Player;
			List<string> list = new List<string>();
			list.Add($"Tier {CoreTierUpgrades.RomanNumeral(currentTier)} now: {slots} slots. Tier {CoreTierUpgrades.RomanNumeral(num)}: {slots2} slots.");
			list.Add("Needs a nearby " + stationName + ". Paid from " + SourceLabel(source) + ":");
			List<string> list2 = list;
			TierUpgradeRequirement[] array = requirements;
			for (int i = 0; i < array.Length; i++)
			{
				TierUpgradeRequirement tierUpgradeRequirement = array[i];
				long num2 = StoredCount(inventory, tierUpgradeRequirement.ItemName, excludeEquipped);
				list2.Add(string.Format("  {0} {1}  (in {2}: {3})", tierUpgradeRequirement.Amount, tierUpgradeRequirement.ItemName, SourceLabel(source), num2.ToString("N0", CultureInfo.InvariantCulture)));
			}
			list2.Add((source == RuneStorageUpgradeSource.Player) ? "Equipped items are never used. Upgrading keeps every stored item and its position." : "Upgrading keeps every stored item and its position.");
			return string.Join("\n", list2);
		}

		internal static bool HasPayment(Inventory inventory, TierUpgradeRequirement[] requirements)
		{
			if (inventory == null || requirements == null)
			{
				return false;
			}
			return requirements.All((TierUpgradeRequirement requirement) => StoredCount(inventory, requirement.ItemName, excludeEquipped: true) >= requirement.Amount);
		}

		internal static List<ItemData> TakePayment(Inventory inventory, TierUpgradeRequirement[] requirements)
		{
			if (!HasPayment(inventory, requirements))
			{
				return null;
			}
			List<ItemData> list = new List<ItemData>();
			for (int i = 0; i < requirements.Length; i++)
			{
				TierUpgradeRequirement tierUpgradeRequirement = requirements[i];
				int num = tierUpgradeRequirement.Amount;
				foreach (ItemData item in OrderedMatches(inventory, tierUpgradeRequirement.ItemName, excludeEquipped: true))
				{
					if (num <= 0)
					{
						break;
					}
					int num2 = Math.Min(num, item.m_stack);
					ItemData val = item.Clone();
					val.m_stack = num2;
					list.Add(val);
					item.m_stack -= num2;
					num -= num2;
					if (item.m_stack <= 0)
					{
						inventory.RemoveItem(item);
					}
				}
			}
			RuneStorageTransfers.NotifyChanged(inventory);
			return list;
		}

		internal static bool PaymentMatches(List<ItemData> payment, TierUpgradeRequirement[] requirements)
		{
			if (payment == null || requirements == null)
			{
				return false;
			}
			if (payment.Any((ItemData item) => item == null || item.m_shared == null || item.m_stack <= 0 || item.m_equipped))
			{
				return false;
			}
			for (int num = 0; num < requirements.Length; num++)
			{
				TierUpgradeRequirement requirement = requirements[num];
				if (payment.Where((ItemData item) => string.Equals(ItemNameOf(item), requirement.ItemName, StringComparison.Ordinal)).Sum((Func<ItemData, long>)((ItemData item) => item.m_stack)) != requirement.Amount)
				{
					return false;
				}
			}
			int num2 = requirements.Sum((TierUpgradeRequirement tierUpgradeRequirement) => tierUpgradeRequirement.Amount);
			return ((IEnumerable<ItemData>)payment).Sum((Func<ItemData, long>)((ItemData item) => item.m_stack)) == num2;
		}

		internal static string Upgrade(Player player, RuneStorageTerminalMarker terminal, Container core, RuneStorageCoreMarker marker, RuneStorageUpgradeSource source, List<ItemData> requesterPayment, out bool ok)
		{
			ok = false;
			if ((Object)(object)player == (Object)null || (Object)(object)terminal == (Object)null || (Object)(object)core == (Object)null || (Object)(object)marker == (Object)null)
			{
				return "The terminal or Core is no longer available. Nothing was upgraded.";
			}
			if (!RuneStorageCoreAccess.TryResolve(player, terminal, out var marker2, out var container, out var reason))
			{
				return reason;
			}
			if ((Object)(object)marker2 != (Object)(object)marker || (Object)(object)container != (Object)(object)core)
			{
				return "The Core connected to this terminal changed. Reopen the terminal and try again.";
			}
			if (!core.IsOwner())
			{
				return "The Core owner must run this upgrade. Nothing was upgraded.";
			}
			ZDO zdo = marker.Zdo;
			if (zdo == null)
			{
				return "The Core's saved data is not ready. Nothing was upgraded.";
			}
			Inventory inventory = core.GetInventory();
			if (inventory == null)
			{
				return "The Core's inventory is not ready. Nothing was upgraded.";
			}
			int num = CurrentTier(zdo);
			if (num >= 3)
			{
				return "The Core is already at Tier " + CoreTierUpgrades.RomanNumeral(num) + ".";
			}
			int num2 = num + 1;
			if (!CoreTierUpgrades.IsNextTier(num, num2) || !CoreTierUpgrades.TryGetUpgrade(num2, out var stationName, out var requirements) || !CoreTierCapacity.TryGetDimensions(num2, out var width, out var height))
			{
				return "This upgrade is not defined. Nothing was upgraded.";
			}
			string text = CoreTierUpgrades.RomanNumeral(num2);
			if (!RuneStorageCrafting.IsStationNearbyNamed(marker, terminal, stationName))
			{
				return "A nearby " + stationName + " is required for Tier " + text + ". No items were used.";
			}
			TierUpgradeRequirement[] array = requirements;
			for (int i = 0; i < array.Length; i++)
			{
				TierUpgradeRequirement tierUpgradeRequirement = array[i];
				if ((Object)(object)ObjectDB.instance == (Object)null || (Object)(object)ObjectDB.instance.GetItemPrefab(tierUpgradeRequirement.ItemName) == (Object)null)
				{
					Plugin.Log.LogError((object)("RuneStorage tier upgrade blocked: ObjectDB has no item named '" + tierUpgradeRequirement.ItemName + "'."));
					return "Valheim has no item named " + tierUpgradeRequirement.ItemName + ", so Tier " + text + " cannot be paid for yet. No items were used.";
				}
			}
			bool num3 = source == RuneStorageUpgradeSource.Player && requesterPayment != null;
			Inventory val = null;
			bool excludeEquipped = source == RuneStorageUpgradeSource.Player;
			if (num3)
			{
				if (!PaymentMatches(requesterPayment, requirements))
				{
					return "The ingredients sent for Tier " + text + " did not match the approved cost. Nothing was upgraded.";
				}
			}
			else
			{
				val = ((source == RuneStorageUpgradeSource.Player) ? ((Humanoid)player).GetInventory() : inventory);
				if (val == null)
				{
					return "The payment inventory is not ready. Nothing was upgraded.";
				}
				array = requirements;
				for (int i = 0; i < array.Length; i++)
				{
					TierUpgradeRequirement tierUpgradeRequirement2 = array[i];
					long num4 = StoredCount(val, tierUpgradeRequirement2.ItemName, excludeEquipped);
					if (num4 < tierUpgradeRequirement2.Amount)
					{
						return $"{SourceLabel(source)} needs {tierUpgradeRequirement2.Amount - num4} more {tierUpgradeRequirement2.ItemName} for Tier {text}. No items were used.";
					}
				}
			}
			if (!RuneStorageTransactions.TryBeginCoreOperation(marker, out var operationId))
			{
				return "The Core is already handling another operation. Try again in a moment.";
			}
			try
			{
				if (val != null)
				{
					array = requirements;
					for (int i = 0; i < array.Length; i++)
					{
						TierUpgradeRequirement tierUpgradeRequirement3 = array[i];
						ConsumeItems(val, tierUpgradeRequirement3.ItemName, tierUpgradeRequirement3.Amount, excludeEquipped);
					}
					RuneStorageTransfers.NotifyChanged(val);
				}
				zdo.Set("RuneStorageCoreTier", num2);
				if (inventory.GetHeight() < height)
				{
					inventory.SetHeight(height);
				}
				Plugin.Log.LogInfo((object)$"RuneStorage Core upgraded to Tier {text} ({width * height} slots), paid from {SourceLabel(source)}.");
				ok = true;
				return $"Upgraded the Core to Tier {text} ({width * height} slots), paid from {SourceLabel(source)}.";
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage tier upgrade failed: {arg}");
				marker.SetReadOnly("A tier upgrade stopped partway. The Core is read-only until its items are checked.");
				return "The upgrade stopped partway through. The Core is read-only; check its items before trying again.";
			}
			finally
			{
				RuneStorageTransactions.EndCoreOperation(operationId);
			}
		}

		private static IEnumerable<ItemData> OrderedMatches(Inventory inventory, string itemName, bool excludeEquipped)
		{
			return (from candidate in inventory.GetAllItems()
				where candidate != null && candidate.m_stack > 0 && (!excludeEquipped || !candidate.m_equipped) && string.Equals(ItemNameOf(candidate), itemName, StringComparison.Ordinal)
				orderby candidate.m_gridPos.y, candidate.m_gridPos.x
				select candidate).ToList();
		}

		private static void ConsumeItems(Inventory inventory, string itemName, int amount, bool excludeEquipped)
		{
			int num = amount;
			foreach (ItemData item in OrderedMatches(inventory, itemName, excludeEquipped).ToList())
			{
				if (num <= 0)
				{
					break;
				}
				int num2 = Math.Min(num, item.m_stack);
				item.m_stack -= num2;
				num -= num2;
				if (item.m_stack <= 0 && !inventory.RemoveItem(item))
				{
					Plugin.Log.LogError((object)("RuneStorage could not remove an emptied '" + itemName + "' stack after a tier upgrade."));
				}
			}
			if (num > 0)
			{
				throw new InvalidOperationException($"Only {amount - num} of {amount} {itemName} were available during the upgrade.");
			}
		}
	}
	internal sealed class RuneStorageCraftingStationGroup
	{
		internal string Identity { get; set; }

		internal string DisplayName { get; set; }

		internal int NearbyLevel { get; set; }

		internal bool RequiresStation { get; set; }

		internal List<RuneStorageCraftingRecipe> Recipes { get; } = new List<RuneStorageCraftingRecipe>();

		internal List<Recipe> SourceRecipes { get; } = new List<Recipe>();
	}
	internal sealed class RuneStorageCraftingIngredient
	{
		internal string Identity { get; set; }

		internal string SharedName { get; set; }

		internal string DisplayName { get; set; }

		internal int WorldLevel { get; set; }

		internal int Required { get; set; }

		internal int Available { get; set; }
	}
	internal sealed class RuneStorageCraftingRecipe
	{
		internal string Identity { get; set; }

		internal string DisplayName { get; set; }

		internal Sprite Icon { get; set; }

		internal int OutputAmount { get; set; }

		internal int RequiredStationLevel { get; set; }

		internal int NearbyStationLevel { get; set; }

		internal bool StationAvailable { get; set; }

		internal bool IngredientsAvailable { get; set; }

		internal bool OutputAvailable { get; set; }

		internal bool IsSupported { get; set; }

		internal string IngredientSummary { get; set; }

		internal string DisabledReason { get; set; }

		internal List<RuneStorageCraftingIngredient> Ingredients { get; set; }

		internal Recipe Recipe { get; set; }

		internal bool CanCraft
		{
			get
			{
				if (IsSupported && StationAvailable && IngredientsAvailable)
				{
					return OutputAvailable;
				}
				return false;
			}
		}
	}
	internal static class RuneStorageCrafting
	{
		internal const string HandCraftingStationId = "RuneStorage_HandCrafting";

		internal static List<RuneStorageCraftingStationGroup> GetStationGroups(Player player, RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal)
		{
			Dictionary<string, RuneStorageCraftingStationGroup> dictionary = new Dictionary<string, RuneStorageCraftingStationGroup>(StringComparer.Ordinal);
			if ((Object)(object)player == (Object)null || (Object)(object)core == (Object)null || (Object)(object)terminal == (Object)null || (Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_recipes == null)
			{
				return new List<RuneStorageCraftingStationGroup>();
			}
			Dictionary<string, int> nearbyLevels = new Dictionary<string, int>(StringComparer.Ordinal);
			List<CraftingStation> sceneFallback = null;
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				if (IsRecipeKnownForCatalog(player, recipe))
				{
					CraftingStation requiredStation = recipe.GetRequiredStation(1);
					string stationIdentity = GetStationIdentity(requiredStation);
					if (!dictionary.TryGetValue(stationIdentity, out var value))
					{
						value = new RuneStorageCraftingStationGroup
						{
							Identity = stationIdentity,
							DisplayName = GetStationDisplayName(requiredStation),
							RequiresStation = ((Object)(object)requiredStation != (Object)null),
							NearbyLevel = ((!((Object)(object)requiredStation == (Object)null)) ? GetNearbyLevel(requiredStation) : 0)
						};
						dictionary.Add(stationIdentity, value);
					}
					value.SourceRecipes.Add(recipe);
				}
			}
			LogCraftingCatalog(player, core, terminal, dictionary.Values, ref sceneFallback);
			return dictionary.Values.OrderBy<RuneStorageCraftingStationGroup, string>((RuneStorageCraftingStationGroup group) => group.DisplayName, StringComparer.OrdinalIgnoreCase).ThenBy<RuneStorageCraftingStationGroup, string>((RuneStorageCraftingStationGroup group) => group.Identity, StringComparer.Ordinal).ToList();
			int GetNearbyLevel(CraftingStation station)
			{
				string stationIdentity2 = GetStationIdentity(station);
				if (!nearbyLevels.TryGetValue(stationIdentity2, out var value2))
				{
					value2 = FindBestNearbyLevel(core, terminal, station, ref sceneFallback);
					nearbyLevels.Add(stationIdentity2, value2);
				}
				return value2;
			}
		}

		internal static void BuildRecipeViews(Player player, Container core, RuneStorageCraftingStationGroup group, bool outputToCore)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)core == (Object)null || group == null)
			{
				return;
			}
			Inventory inventory = core.GetInventory();
			if (inventory == null)
			{
				return;
			}
			Dictionary<string, int> inventoryCounts = BuildInventoryCounts(inventory);
			group.Recipes.Clear();
			foreach (Recipe sourceRecipe in group.SourceRecipes)
			{
				group.Recipes.Add(BuildRecipeView(player, inventory, inventoryCounts, sourceRecipe, group, outputToCore));
			}
			Plugin.Log.LogInfo((object)($"Crafting preview: tab='{group.DisplayName}', source={group.SourceRecipes.Count}, " + string.Format("views={0}, recipes=[{1}].", group.Recipes.Count, string.Join(", ", group.Recipes.Select((RuneStorageCraftingRecipe recipe) => recipe.DisplayName)))));
		}

		internal static string Craft(Player player, RuneStorageTerminalMarker terminal, RuneStorageCoreMarker expectedCore, string recipeIdentity, bool outputToCore)
		{
			if (!RuneStorageCoreAccess.TryResolve(player, terminal, out var marker, out var container, out var reason))
			{
				return reason;
			}
			if ((Object)(object)marker != (Object)(object)expectedCore)
			{
				return "The Core connected to this terminal changed. Reopen the terminal and try again.";
			}
			if (!container.IsOwner())
			{
				return "The Core owner must validate this craft. The request was not run locally.";
			}
			if (!RuneStorageTransactions.TryBeginCoreOperation(marker, out var operationId))
			{
				return "The Core is already handling another operation. Try again in a moment.";
			}
			List<ItemData> removed = null;
			bool flag = false;
			try
			{
				if (!RuneStorageCoreAccess.TryResolve(player, terminal, out var marker2, out var container2, out reason))
				{
					return reason;
				}
				if ((Object)(object)marker2 != (Object)(object)marker || (Object)(object)container2 != (Object)(object)container)
				{
					return "The Core connected to this terminal changed. Reopen the terminal and try again.";
				}
				if (marker.IsReadOnly)
				{
					return marker.StatusMessage ?? "The Core is read-only. No ingredients were used.";
				}
				Recipe val = ResolveRecipe(player, recipeIdentity);
				if ((Object)(object)val == (Object)null)
				{
					return "That recipe is no longer available. The recipe list has been refreshed.";
				}
				CraftingStation requiredStation = val.GetRequiredStation(1);
				int num = (((Object)(object)requiredStation != (Object)null) ? val.GetRequiredStationLevel(1) : 0);
				if ((Object)(object)requiredStation != (Object)null && !HasNearbyStationAtLevel(marker, terminal, requiredStation, num))
				{
					return $"A nearby {GetStationDisplayName(requiredStation)} at level {num} or higher is required.";
				}
				Inventory inventory = container.GetInventory();
				Inventory inventory2 = ((Humanoid)player).GetInventory();
				if (inventory == null || inventory2 == null)
				{
					return "A player or Core inventory is unavailable. No ingredients were used.";
				}
				List<RuneStorageCraftingIngredient> ingredients = GetIngredients(val, BuildInventoryCounts(inventory));
				if (!IsSupportedRecipe(val, ingredients, out var reason2))
				{
					return reason2;
				}
				RuneStorageCraftingIngredient runeStorageCraftingIngredient = ingredients.FirstOrDefault((RuneStorageCraftingIngredient ingredient) => ingredient.Available < ingredient.Required);
				if (runeStorageCraftingIngredient != null)
				{
					return $"The Core needs {runeStorageCraftingIngredient.Required - runeStorageCraftingIngredient.Available} more {runeStorageCraftingIngredient.DisplayName}. No ingredients were used.";
				}
				Inventory val2 = (outputToCore ? inventory : inventory2);
				ItemData val3 = CreateOutput(val, player);
				if (val3 == null)
				{
					return "Valheim could not create this recipe's output. No ingredients were used.";
				}
				if (!CanAcceptOutput(val2, inventory, val3, ingredients, outputToCore))
				{
					return outputToCore ? "The Core has no room for the complete output after this craft. No ingredients were used." : "Your inventory has no room for the complete output. No ingredients were used.";
				}
				string identity = RuneStorageItemGroups.GetIdentity(val3);
				if (!TryConsumeIngredients(inventory, ingredients, out removed))
				{
					if (!RestoreIngredients(inventory, removed, marker))
					{
						return marker.StatusMessage ?? "Ingredient recovery failed. The Core is now read-only to protect its contents.";
					}
					return "The Core ingredients changed before the craft could be committed. Nothing was crafted.";
				}
				flag = true;
				long num2 = CountExactIdentity(val2, identity);
				bool flag2;
				try
				{
					flag2 = val2.AddItem(val3);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"RuneStorage output delivery failed: {arg}");
					flag2 = false;
				}
				long num3 = CountExactIdentity(val2, identity) - num2;
				if (!flag2 || num3 != val.m_amount)
				{
					if (num3 > 0 && !RemoveExactIdentity(val2, identity, num3))
					{
						marker.SetReadOnly("RuneStorage could not reverse partial craft output delivery.");
						flag = false;
						return "Output delivery was incomplete and could not be safely reversed. The Core is read-only; inspect both inventories before continuing.";
					}
					if (!RestoreIngredients(inventory, removed, marker))
					{
						return marker.StatusMessage ?? "Output delivery and ingredient recovery failed. The Core is now read-only.";
					}
					flag = false;
					return "The output could not be added. The ingredients were restored; free inventory space and try again.";
				}
				flag = false;
				return "Crafted " + GetItemDisplayName(val.m_item.m_itemData) + " x" + val.m_amount.ToString(CultureInfo.InvariantCulture) + " to " + (outputToCore ? "the Core" : "your inventory") + ".";
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"RuneStorage craft failed: {arg2}");
				if (flag && !RestoreIngredients(container.GetInventory(), removed, marker))
				{
					return marker.StatusMessage ?? "The craft failed and ingredient recovery was incomplete. The Core is now read-only.";
				}
				return "The craft stopped after an inventory error. Check the Core and output inventory before trying again.";
			}
			finally
			{
				RuneStorageTransactions.EndCoreOperation(operationId);
			}
		}

		internal static Recipe ResolveRecipe(Player player, string recipeIdentity)
		{
			if ((Object)(object)player == (Object)null || string.IsNullOrEmpty(recipeIdentity) || (Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_recipes == null)
			{
				return null;
			}
			return ((IEnumerable<Recipe>)ObjectDB.instance.m_recipes).FirstOrDefault((Func<Recipe, bool>)((Recipe recipe) => IsNormalRecipe(recipe) && IsRecipeUnlocked(player, recipe) && string.Equals(GetRecipeIdentity(recipe), recipeIdentity, StringComparison.Ordinal)));
		}

		private static bool IsRecipeKnownForCatalog(Player player, Recipe recipe)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || recipe.m_item.m_itemData == null || recipe.m_item.m_itemData.m_shared == null || !IsDlcAvailable(recipe.m_item.m_itemData))
			{
				return false;
			}
			if (!PlayerKnowsRecipe(player, recipe) && (!((Object)(object)ZoneSystem.instance != (Object)null) || !ZoneSystem.instance.GetGlobalKey((GlobalKeys)28)))
			{
				return player.NoCostCheat();
			}
			return true;
		}

		private static bool IsRecipeUnlocked(Player player, Recipe recipe)
		{
			if ((Object)(object)player == (Object)null || !IsNormalRecipe(recipe))
			{
				return false;
			}
			if (!IsDlcAvailable(recipe.m_item.m_itemData))
			{
				return false;
			}
			if (PlayerKnowsRecipe(player, recipe))
			{
				return true;
			}
			if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey((GlobalKeys)28))
			{
				return true;
			}
			return player.NoCostCheat();
		}

		private static bool PlayerKnowsRecipe(Player player, Recipe recipe)
		{
			if ((Object)(object)player != (Object)null && (Object)(object)recipe != (Object)null && (Object)(object)recipe.m_item != (Object)null && recipe.m_item.m_itemData != null && recipe.m_item.m_itemData.m_shared != null)
			{
				return player.IsRecipeKnown(recipe.m_item.m_itemData.m_shared.m_name);
			}
			return false;
		}

		private static bool IsDlcAvailable(ItemData item)
		{
			string text = ((item != null && item.m_shared != null) ? item.m_shared.m_dlc : null);
			if (!string.IsNullOrEmpty(text))
			{
				if ((Object)(object)DLCMan.instance != (Object)null)
				{
					return DLCMan.instance.IsDLCInstalled(text);
				}
				return false;
			}
			return true;
		}

		private static RuneStorageCraftingRecipe BuildRecipeView(Player player, Inventory coreInventory, Dictionary<string, int> inventoryCounts, Recipe recipe, RuneStorageCraftingStationGroup stationGroup, bool outputToCore)
		{
			List<RuneStorageCraftingIngredient> ingredients = GetIngredients(recipe, inventoryCounts);
			bool num = IsNormalRecipe(recipe);
			bool flag;
			string reason;
			if (num)
			{
				flag = IsSupportedRecipe(recipe, ingredients, out reason);
			}
			else
			{
				flag = false;
				reason = GetNonCraftableRecipeReason(recipe);
			}
			int num2 = (stationGroup.RequiresStation ? recipe.GetRequiredStationLevel(1) : 0);
			bool flag2 = !stationGroup.RequiresStation || stationGroup.NearbyLevel >= num2;
			bool flag3 = ingredients.All((RuneStorageCraftingIngredient ingredient) => ingredient.Available >= ingredient.Required);
			ItemData val = CreateOutput(recipe, player);
			Inventory inventory = ((Humanoid)player).GetInventory();
			bool flag4 = val != null && (outputToCore ? CanAcceptOutput(coreInventory, coreInventory, val, ingredients, outputToCore: true) : (inventory != null && inventory.CanAddItem(val, val.m_stack)));
			string text = ((!stationGroup.RequiresStation) ? "No station required" : (flag2 ? $"{stationGroup.DisplayName} Lv. {num2} required; nearby Lv. {stationGroup.NearbyLevel}" : ((stationGroup.NearbyLevel > 0) ? $"Needs {stationGroup.DisplayName} Lv. {num2}; nearby station is Lv. {stationGroup.NearbyLevel}" : ("No " + stationGroup.DisplayName + " within crafting range"))));
			string text2 = ((ingredients.Count == 0) ? "No Core ingredients required" : string.Join("   ", ingredients.Select((RuneStorageCraftingIngredient ingredient) => ingredient.DisplayName + " " + ingredient.Available.ToString(CultureInfo.InvariantCulture) + "/" + ingredient.Required.ToString(CultureInfo.InvariantCulture))));
			string disabledReason = ((!num) ? reason : ((!flag) ? reason : ((!flag2) ? text : ((!flag3) ? "The Core does not hold all required ingredients." : (flag4 ? null : (outputToCore ? "The Core cannot fit the full output." : "Your inventory cannot fit the full output."))))));
			return new RuneStorageCraftingRecipe
			{
				Identity = GetRecipeIdentity(recipe),
				DisplayName = GetItemDisplayName(recipe.m_item.m_itemData),
				Icon = recipe.m_item.m_itemData.GetIcon(),
				OutputAmount = recipe.m_amount,
				RequiredStationLevel = num2,
				NearbyStationLevel = stationGroup.NearbyLevel,
				StationAvailable = flag2,
				IngredientsAvailable = flag3,
				OutputAvailable = flag4,
				IsSupported = flag,
				IngredientSummary = text + "   |   " + text2,
				DisabledReason = disabledReason,
				Ingredients = ingredients,
				Recipe = recipe
			};
		}

		private static bool IsNormalRecipe(Recipe recipe)
		{
			if ((Object)(object)recipe != (Object)null && recipe.m_enabled && (Object)(object)recipe.m_item != (Object)null && recipe.m_item.m_itemData != null && recipe.m_item.m_itemData.m_shared != null)
			{
				return !recipe.m_noCraftOnlyUpgrade;
			}
			return false;
		}

		private static string GetNonCraftableRecipeReason(Recipe recipe)
		{
			if ((Object)(object)recipe == (Object)null)
			{
				return "Valheim's recipe data is unavailable.";
			}
			if (!recipe.m_enabled)
			{
				return "Valheim currently disables this recipe.";
			}
			if (recipe.m_noCraftOnlyUpgrade)
			{
				return "This recipe is reserved for upgrading an existing item.";
			}
			return "Valheim does not mark this as a normal crafting recipe.";
		}

		private static bool IsSupportedRecipe(Recipe recipe, List<RuneStorageCraftingIngredient> ingredients, out string reason)
		{
			if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || recipe.m_item.m_itemData == null || recipe.m_amount <= 0)
			{
				reason = "Valheim marked this recipe as incomplete. It cannot be crafted from RuneStorage.";
				return false;
			}
			if ((Object)(object)recipe.m_craftingStation != (Object)null && (Object)(object)recipe.GetRequiredStation(1) == (Object)null)
			{
				reason = "Valheim could not resolve this recipe's required crafting station.";
				return false;
			}
			if (recipe.m_requireOnlyOneIngredient)
			{
				reason = "This recipe uses Valheim's alternative-ingredient rule, which RuneStorage does not support yet.";
				return false;
			}
			bool usesUpgraderResources = UsesUpgraderResources(recipe);
			if (recipe.m_resources != null && recipe.m_resources.Any(delegate(Requirement requirement)
			{
				if (requirement == null)
				{
					return true;
				}
				if (requirement.m_upgraderResource != usesUpgraderResources || requirement.GetAmount(1) <= 0)
				{
					return false;
				}
				return (Object)(object)requirement.m_resItem == (Object)null || requirement.m_resItem.m_itemData == null || requirement.m_resItem.m_itemData.m_shared == null || string.IsNullOrEmpty(requirement.m_resItem.m_itemData.m_shared.m_name);
			}))
			{
				reason = "This recipe has an ingredient RuneStorage cannot safely identify.";
				return false;
			}
			if (ingredients == null || ingredients.Any((RuneStorageCraftingIngredient ingredient) => ingredient.Required <= 0 || string.IsNullOrEmpty(ingredient.SharedName)))
			{
				reason = "This recipe has an ingredient RuneStorage cannot safely identify.";
				return false;
			}
			reason = null;
			return true;
		}

		private static Dictionary<string, int> BuildInventoryCounts(Inventory inventory)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			if (inventory == null)
			{
				return dictionary;
			}
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem != null && allItem.m_shared != null && !string.IsNullOrEmpty(allItem.m_shared.m_name) && allItem.m_stack > 0)
				{
					string ingredientIdentity = GetIngredientIdentity(allItem.m_shared.m_name, allItem.m_worldLevel);
					dictionary.TryGetValue(ingredientIdentity, out var value);
					dictionary[ingredientIdentity] = (int)Math.Min(2147483647L, (long)value + (long)allItem.m_stack);
				}
			}
			return dictionary;
		}

		private static List<RuneStorageCraftingIngredient> GetIngredients(Recipe recipe, Dictionary<string, int> inventoryCounts)
		{
			Dictionary<string, RuneStorageCraftingIngredient> dictionary = new Dictionary<string, RuneStorageCraftingIngredient>(StringComparer.Ordinal);
			if ((Object)(object)recipe == (Object)null || recipe.m_resources == null)
			{
				return new List<RuneStorageCraftingIngredient>();
			}
			bool flag = UsesUpgraderResources(recipe);
			Requirement[] resources = recipe.m_resources;
			checked
			{
				foreach (Requirement val in resources)
				{
					if ((val != null && val.m_upgraderResource != flag) || val == null || (Object)(object)val.m_resItem == (Object)null || val.m_resItem.m_itemData == null || val.m_resItem.m_itemData.m_shared == null)
					{
						continue;
					}
					ItemData itemData = val.m_resItem.m_itemData;
					string name = itemData.m_shared.m_name;
					int amount = val.GetAmount(1);
					if (!string.IsNullOrEmpty(name) && amount > 0)
					{
						string ingredientIdentity = GetIngredientIdentity(name, itemData.m_worldLevel);
						if (!dictionary.TryGetValue(ingredientIdentity, out var value))
						{
							value = new RuneStorageCraftingIngredient
							{
								Identity = ingredientIdentity,
								SharedName = name,
								DisplayName = GetItemDisplayName(itemData),
								WorldLevel = itemData.m_worldLevel
							};
							dictionary.Add(ingredientIdentity, value);
						}
						value.Required += amount;
					}
				}
				List<RuneStorageCraftingIngredient> list = dictionary.Values.OrderBy<RuneStorageCraftingIngredient, string>((RuneStorageCraftingIngredient ingredient) => ingredient.DisplayName, StringComparer.OrdinalIgnoreCase).ThenBy<RuneStorageCraftingIngredient, string>((RuneStorageCraftingIngredient ingredient) => ingredient.Identity, StringComparer.Ordinal).ToList();
				if (inventoryCounts != null)
				{
					foreach (RuneStorageCraftingIngredient item in list)
					{
						inventoryCounts.TryGetValue(item.Identity, out var value2);
						item.Available = value2;
					}
				}
				return list;
			}
		}

		private static bool UsesUpgraderResources(Recipe recipe)
		{
			CraftingStation val = (((Object)(object)recipe != (Object)null) ? recipe.GetRequiredStation(1) : null);
			if ((Object)(object)val != (Object)null)
			{
				return val.m_upgrader;
			}
			return false;
		}

		private static int CountIngredient(Inventory inventory, RuneStorageCraftingIngredient ingredient)
		{
			if (inventory == null || ingredient == null)
			{
				return 0;
			}
			long val = (from item in inventory.GetAllItems()
				where MatchesIngredient(item, ingredient)
				select item).Sum((Func<ItemData, long>)((ItemData item) => Math.Max(0, item.m_stack)));
			return (int)Math.Min(2147483647L, val);
		}

		private static long CountExactIdentity(Inventory inventory, string identity)
		{
			if (inventory == null || string.IsNullOrEmpty(identity))
			{
				return 0L;
			}
			return (from item in inventory.GetAllItems()
				where string.Equals(RuneStorageItemGroups.GetIdentity(item), identity, StringComparison.Ordinal)
				select item).Sum((Func<ItemData, long>)((ItemData item) => Math.Max(0, item.m_stack)));
		}

		private static bool RemoveExactIdentity(Inventory inventory, string identity, long requested)
		{
			if (inventory == null || string.IsNullOrEmpty(identity) || requested < 0)
			{
				return false;
			}
			long num = CountExactIdentity(inventory, identity);
			long num2 = requested;
			ItemData[] array = (from candidate in inventory.GetAllItems()
				where string.Equals(RuneStorageItemGroups.GetIdentity(candidate), identity, StringComparison.Ordinal)
				select candidate).ToArray();
			foreach (ItemData val in array)
			{
				if (num2 <= 0)
				{
					break;
				}
				int num4 = (int)Math.Min(num2, val.m_stack);
				if (num4 > 0)
				{
					long num5 = CountExactIdentity(inventory, identity);
					bool flag;
					try
					{
						flag = inventory.RemoveItem(val, num4);
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"RuneStorage could not reverse craft output: {arg}");
						return false;
					}
					long num6 = CountExactIdentity(inventory, identity);
					long num7 = Math.Max(0L, num5 - num6);
					num2 -= num7;
					if (!flag || num7 != num4)
					{
						break;
					}
				}
			}
			if (num2 == 0L)
			{
				return num - CountExactIdentity(inventory, identity) == requested;
			}
			return false;
		}

		private static bool MatchesIngredient(ItemData item, RuneStorageCraftingIngredient ingredient)
		{
			if (item != null && item.m_shared != null && ingredient != null && string.Equals(item.m_shared.m_name, ingredient.SharedName, StringComparison.Ordinal))
			{
				return item.m_worldLevel == ingredient.WorldLevel;
			}
			return false;
		}

		private static List<CraftingStation> FindNearbyStations(RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal, CraftingStation requiredStation, ref List<CraftingStation> sceneFallback)
		{
			if ((Object)(object)core == (Object)null || (Object)(object)terminal == (Object)null || (Object)(object)requiredStation == (Object)null)
			{
				return new List<CraftingStation>();
			}
			if (sceneFallback == null)
			{
				sceneFallback = Object.FindObjectsByType<CraftingStation>((FindObjectsSortMode)0).ToList();
			}
			return sceneFallback.Where((CraftingStation station) => (Object)(object)station != (Object)null && ((Behaviour)station).isActiveAndEnabled && SameStationType(station, requiredStation) && IsWithinRuneStorageCraftingRange(station, requiredStation, core, terminal)).Distinct().ToList();
		}

		private static int FindBestNearbyLevel(RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal, CraftingStation requiredStation, ref List<CraftingStation> sceneFallback)
		{
			int num = 0;
			foreach (CraftingStation item in FindNearbyStations(core, terminal, requiredStation, ref sceneFallback))
			{
				num = Math.Max(num, item.GetLevel(true));
			}
			return num;
		}

		private static bool HasNearbyStationAtLevel(RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal, CraftingStation requiredStation, int requiredLevel)
		{
			List<CraftingStation> sceneFallback = null;
			foreach (CraftingStation item in FindNearbyStations(core, terminal, requiredStation, ref sceneFallback))
			{
				if (item.GetLevel(true) >= requiredLevel)
				{
					return true;
				}
			}
			return false;
		}

		internal static bool IsStationNearbyNamed(RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal, string stationName)
		{
			if ((Object)(object)core == (Object)null || (Object)(object)terminal == (Object)null || string.IsNullOrEmpty(stationName))
			{
				return false;
			}
			CraftingStation[] array = Object.FindObjectsByType<CraftingStation>((FindObjectsSortMode)0);
			foreach (CraftingStation val in array)
			{
				if (!((Object)(object)val == (Object)null) && ((Behaviour)val).isActiveAndEnabled && (SameStationName(val.m_name, stationName) || SameStationName(((Object)((Component)val).gameObject).name, stationName)) && IsWithinRuneStorageCraftingRange(val, val, core, terminal))
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsWithinRuneStorageCraftingRange(CraftingStation station, CraftingStation requiredStation, RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			float num = ((station.m_useDistance > 0f) ? station.m_useDistance : requiredStation.m_useDistance);
			if (num <= 0f)
			{
				return false;
			}
			Bounds visualBoundsOrPoint = GetVisualBoundsOrPoint(((Component)station).gameObject);
			Bounds visualBoundsOrPoint2 = GetVisualBoundsOrPoint(((Component)core).gameObject);
			Bounds visualBoundsOrPoint3 = GetVisualBoundsOrPoint(((Component)terminal).gameObject);
			if (!(GetBoundsSeparation(visualBoundsOrPoint, visualBoundsOrPoint2) < num))
			{
				return GetBoundsSeparation(visualBoundsOrPoint, visualBoundsOrPoint3) < num;
			}
			return true;
		}

		private static Bounds GetVisualBoundsOrPoint(GameObject root)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
			bool flag = false;
			Bounds bounds = default(Bounds);
			((Bounds)(ref bounds))..ctor(root.transform.position, Vector3.zero);
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled && ((Component)val).gameObject.activeInHierarchy)
				{
					if (!flag)
					{
						bounds = val.bounds;
						flag = true;
					}
					else
					{
						((Bounds)(ref bounds)).Encapsulate(val.bounds);
					}
				}
			}
			return bounds;
		}

		private static float GetBoundsSeparation(Bounds first, Bounds second)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: 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_00b0: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(Mathf.Max(0f, Mathf.Max(((Bounds)(ref first)).min.x - ((Bounds)(ref second)).max.x, ((Bounds)(ref second)).min.x - ((Bounds)(ref first)).max.x)), Mathf.Max(0f, Mathf.Max(((Bounds)(ref first)).min.y - ((Bounds)(ref second)).max.y, ((Bounds)(ref second)).min.y - ((Bounds)(ref first)).max.y)), Mathf.Max(0f, Mathf.Max(((Bounds)(ref first)).min.z - ((Bounds)(ref second)).max.z, ((Bounds)(ref second)).min.z - ((Bounds)(ref first)).max.z)));
			return ((Vector3)(ref val)).magnitude;
		}

		private static void LogCraftingCatalog(Player player, RuneStorageCoreMarker core, RuneStorageTerminalMarker terminal, IEnumerable<RuneStorageCraftingStationGroup> groups, ref List<CraftingStation> sceneFallback)
		{
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			if (sceneFallback == null)
			{
				sceneFallback = Object.FindObjectsByType<CraftingStation>((FindObjectsSortMode)0).ToList();
			}
			List<RuneStorageCraftingStationGroup> source = groups.ToList();
			int num = source.Where((RuneStorageCraftingStationGroup group) => !group.RequiresStation).SelectMany((RuneStorageCraftingStationGroup group) => group.SourceRecipes).Count();
			int num2 = source.Sum((RuneStorageCraftingStationGroup group) => group.SourceRecipes.Count);
			List<Recipe> list = (from recipe in ObjectDB.instance.m_recipes
				where PlayerKnowsRecipe(player, recipe)
				where (Object)(object)recipe.GetRequiredStation(1) == (Object)null
				select recipe).ToList();
			string text = string.Join("; ", list.Take(40).Select(delegate(Recipe recipe)
			{
				ItemData itemData = recipe.m_item.m_itemData;
				bool flag = IsDlcAvailable(itemData);
				string arg = ((!recipe.m_enabled) ? "disabled" : (recipe.m_noCraftOnlyUpgrade ? "upgrade-only" : ((!flag) ? "DLC unavailable" : "included")));
				return $"{GetItemDisplayName(itemData)} [enabled={recipe.m_enabled}, upgradeOnly={recipe.m_noCraftOnlyUpgrade}, " + $"repairStation={(Object)(object)recipe.m_repairStation != (Object)null}, dlcAvailable={flag}, catalog={arg}]";
			}));
			string text2 = string.Join(", ", from @group in source
				where @group.RequiresStation && @group.NearbyLevel > 0
				select $"{@group.DisplayName} Lv.{@group.NearbyLevel}");
			string text3 = string.Join("; ", from entry in (from station in sceneFallback
					where (Object)(object)station != (Object)null
					select new
					{
						Station = station,
						CoreDistance = Vector3.Distance(((Component)station).transform.position, ((Component)core).transform.position),
						TerminalDistance = Vector3.Distance(((Component)station).transform.position, ((Component)terminal).transform.position),
						CoreVisualGap = GetBoundsSeparation(GetVisualBoundsOrPoint(((Component)station).gameObject), GetVisualBoundsOrPoint(((Component)core).gameObject)),
						TerminalVisualGap = GetBoundsSeparation(GetVisualBoundsOrPoint(((Component)station).gameObject), GetVisualBoundsOrPoint(((Component)terminal).gameObject))
					} into entry
					orderby Math.Min(entry.CoreDistance, entry.TerminalDistance)
					select entry).Take(10)
				select entry.Station.m_name + "/" + NormalizePrefabName(((Object)((Component)entry.Station).gameObject).name) + " " + $"active={((Behaviour)entry.Station).isActiveAndEnabled} use={entry.Station.m_useDistance:0.##}m " + $"root={((Component)entry.Station).transform.position} core={entry.CoreDistance:0.##}m " + $"terminal={entry.TerminalDistance:0.##}m visualGapCore={entry.CoreVisualGap:0.##}m " + $"visualGapTerminal={entry.TerminalVisualGap:0.##}m");
			Plugin.Log.LogInfo((object)($"Crafting scan: {num2} unlocked normal recipes ({num} Hand); " + $"learned no-station recipes={list.Count}: " + (string.IsNullOrEmpty(text) ? "none" : text) + "; detected station types: " + (string.IsNullOrEmpty(text2) ? "none" : text2) + "; " + $"scene CraftingStation components={sceneFallback.Count}; " + $"Core={((Component)core).transform.position}, Terminal={((Component)terminal).transform.position}; " + "nearest components: " + (string.IsNullOrEmpty(text3) ? "none" : text3) + "."));
		}

		private static bool SameStationType(CraftingStation instance, CraftingStation required)
		{
			if ((Object)(object)instance == (Object)null || (Object)(object)required == (Object)null)
			{
				return false;
			}
			if (!SameStationName(instance.m_name, required.m_name) && !SameStationName(((Object)((Component)instance).gameObject).name, ((Object)((Component)required).gameObject).name) && !SameStationName(instance.m_name, ((Object)((Component)required).gameObject).name))
			{
				return SameStationName(((Object)((Component)instance).gameObject).name, required.m_name);
			}
			return true;
		}

		private static bool SameStationName(string left, string right)
		{
			if (string.IsNullOrEmpty(left) || string.IsNullOrEmpty(right))
			{
				return false;
			}
			string a = NormalizePrefabName(left).TrimStart(new char[1] { '$' });
			string b = NormalizePrefabName(right).TrimStart(new char[1] { '$' });
			return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
		}

		private static string GetStationIdentity(CraftingStation station)
		{
			if ((Object)(object)station == (Object)null)
			{
				return "RuneStorage_HandCrafting";
			}
			if (string.IsNullOrEmpty(station.m_name))
			{
				return NormalizePrefabName(((Object)((Component)station).gameObject).name);
			}
			return station.m_name;
		}

		private static string GetStationDisplayName(CraftingStation station)
		{
			if ((Object)(object)station == (Object)null)
			{
				return "Hand";
			}
			return Localize((!string.IsNullOrEmpty(station.m_name)) ? station.m_name : ((Object)((Component)station).gameObject).name);
		}

		private static string NormalizePrefabName(string name)
		{
			return (name ?? string.Empty).Replace("(Clone)", string.Empty).Trim();
		}

		private static string GetRecipeIdentity(Recipe recipe)
		{
			CraftingStation requiredStation = recipe.GetRequiredStation(1);
			List<RuneStorageCraftingIngredient> ingredients = GetIngredients(recipe, null);
			StringBuilder stringBuilder = new StringBuilder(192);
			Append(stringBuilder, ((Object)recipe).name ?? string.Empty);
			Append(stringBuilder, ((Object)(object)recipe.m_item != (Object)null) ? NormalizePrefabName(((Object)((Component)recipe.m_item).gameObject).name) : string.Empty);
			Append(stringBuilder, GetStationIdentity(requiredStation));
			Append(stringBuilder, (((Object)(object)requiredStation != (Object)null) ? recipe.GetRequiredStationLevel(1) : 0).ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, recipe.m_amount.ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, recipe.m_requireOnlyOneIngredient ? "alternative-ingredients" : "all-ingredients");
			Append(stringBuilder, recipe.m_qualityResultAmountMultiplier.ToString("R", CultureInfo.InvariantCulture));
			foreach (RuneStorageCraftingIngredient item in ingredients.OrderBy<RuneStorageCraftingIngredient, string>((RuneStorageCraftingIngredient value) => value.Identity, StringComparer.Ordinal))
			{
				Append(stringBuilder, item.Identity);
				Append(stringBuilder, item.Required.ToString(CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}

		private static string GetIngredientIdentity(string sharedName, int worldLevel)
		{
			return sharedName.Length.ToString(CultureInfo.InvariantCulture) + ":" + sharedName + "|" + worldLevel.ToString(CultureInfo.InvariantCulture);
		}

		private static ItemData CreateOutput(Recipe recipe, Player player)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || recipe.m_item.m_itemData == null || recipe.m_amount <= 0)
			{
				return null;
			}
			GameObject gameObject = ((Component)recipe.m_item).gameObject;
			if ((Object)(object)gameObject == (Object)null)
			{
				return null;
			}
			ItemData obj = recipe.m_item.m_itemData.Clone();
			obj.m_dropPrefab = gameObject;
			obj.m_stack = recipe.m_amount;
			obj.m_crafterID = player.GetPlayerID();
			obj.m_crafterName = player.GetPlayerName();
			return obj;
		}

		private static bool CanAcceptOutput(Inventory destination, Inventory coreInventory, ItemData output, List<RuneStorageCraftingIngredient> ingredients, bool outputToCore)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			if (destination == null || output == null || output.m_stack <= 0)
			{
				return false;
			}
			if (!outputToCore)
			{
				return destination.CanAddItem(output, output.m_stack);
			}
			if (coreInventory == null || ingredients == null)
			{
				return false;
			}
			Inventory val = new Inventory("RuneStorage craft capacity check", (Sprite)null, coreInventory.GetWidth(), coreInventory.GetHeight());
			Dictionary<string, int> dictionary = ingredients.ToDictionary<RuneStorageCraftingIngredient, string, int>((RuneStorageCraftingIngredient ingredient) => ingredient.Identity, (RuneStorageCraftingIngredient ingredient) => ingredient.Required, StringComparer.Ordinal);
			foreach (ItemData current in coreInventory.GetAllItems())
			{
				if (current != null && current.m_stack > 0)
				{
					ItemData val2 = current.Clone();
					RuneStorageCraftingIngredient runeStorageCraftingIngredient = ingredients.FirstOrDefault((RuneStorageCraftingIngredient ingredient) => MatchesIngredient(current, ingredient));
					if (runeStorageCraftingIngredient != null && dictionary.TryGetValue(runeStorageCraftingIngredient.Identity, out var value) && value > 0)
					{
						int num = Math.Min(value, val2.m_stack);
						val2.m_stack -= num;
						dictionary[runeStorageCraftingIngredient.Identity] = value - num;
					}
					if (val2.m_stack > 0 && !val.AddItem(val2, current.m_gridPos))
					{
						return false;
					}
				}
			}
			if (dictionary.Values.Any((int remaining) => remaining > 0))
			{
				return false;
			}
			return val.CanAddItem(output, output.m_stack);
		}

		private static bool TryConsumeIngredients(Inventory inventory, List<RuneStorageCraftingIngredient> ingredients, out List<ItemData> removed)
		{
			removed = new List<ItemData>();
			try
			{
				foreach (RuneStorageCraftingIngredient ingredient in ingredients)
				{
					int num = ingredient.Required;
					ItemData[] array = (from candidate in inventory.GetAllItems()
						where MatchesIngredient(candidate, ingredient)
						select candidate).ToArray();
					foreach (ItemData val in array)
					{
						if (num <= 0)
						{
							break;
						}
						int num3 = Math.Min(num, val.m_stack);
						if (num3 > 0)
						{
							int num4 = CountIngredient(inventory, ingredient);
							bool num5 = inventory.RemoveItem(val, num3);
							int num6 = CountIngredient(inventory, ingredient);
							int num7 = Math.Max(0, num4 - num6);
							if (num7 > 0)
							{
								ItemData val2 = val.Clone();
								val2.m_stack = num7;
								removed.Add(val2);
								num -= num7;
							}
							if (!num5 || num7 != num3)
							{
								return false;
							}
						}
					}
					if (num > 0)
					{
						return false;
					}
				}
				return true;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage ingredient removal failed: {arg}");
				return false;
			}
		}

		private static bool RestoreIngredients(Inventory inventory, List<ItemData> removed, RuneStorageCoreMarker marker)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (removed == null || removed.Count == 0)
			{
				return true;
			}
			foreach (ItemData item in removed)
			{
				try
				{
					if (inventory.AddItem(item, item.m_gridPos) || inventory.AddItem(item))
					{
						continue;
					}
					goto IL_0057;
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"RuneStorage ingredient restoration failed: {arg}");
					goto IL_0057;
				}
				IL_0057:
				marker.SetReadOnly("RuneStorage could not restore ingredients after an interrupted craft transaction.");
				Plugin.Log.LogError((object)("RuneStorage could not restore ingredient '" + item.m_shared?.m_name + "' to Core '" + ((Object)marker).name + "'."));
				return false;
			}
			return true;
		}

		private static string GetItemDisplayName(ItemData item)
		{
			string value = ((item != null && item.m_shared != null) ? item.m_shared.m_name : null);
			if (string.IsNullOrEmpty(value))
			{
				if (item == null || !((Object)(object)item.m_dropPrefab != (Object)null))
				{
					return "Unknown item";
				}
				return ((Object)item.m_dropPrefab).name;
			}
			return Localize(value);
		}

		private static string Localize(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return "Unknown";
			}
			try
			{
				if (Localization.instance != null)
				{
					string text = Localization.instance.Localize(value);
					if (!string.IsNullOrEmpty(text))
					{
						return text;
					}
				}
			}
			catch (Exception)
			{
				return value;
			}
			return value.TrimStart(new char[1] { '$' });
		}

		private static void Append(StringBuilder builder, string value)
		{
			value = value ?? string.Empty;
			builder.Append(value.Length.ToString(CultureInfo.InvariantCulture));
			builder.Append(':');
			builder.Append(value);
			builder.Append('|');
		}
	}
	internal sealed class RuneStorageItemGroup
	{
		internal string Identity { get; set; }

		internal string ItemId { get; set; }

		internal string DisplayName { get; set; }

		internal Sprite Icon { get; set; }

		internal long Count { get; set; }

		internal List<ItemData> Items { get; } = new List<ItemData>();
	}
	internal static class RuneStorageItemGroups
	{
		internal static List<RuneStorageItemGroup> Build(Inventory inventory, string search, bool excludeEquipped = false)
		{
			Dictionary<string, RuneStorageItemGroup> dictionary = new Dictionary<string, RuneStorageItemGroup>(StringComparer.Ordinal);
			string normalizedSearch = (search ?? string.Empty).Trim();
			if (inventory == null)
			{
				return new List<RuneStorageItemGroup>();
			}
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (excludeEquipped && allItem != null && allItem.m_equipped)
				{
					continue;
				}
				string identity = GetIdentity(allItem);
				if (identity != null)
				{
					if (!dictionary.TryGetValue(identity, out var value))
					{
						value = new RuneStorageItemGroup
						{
							Identity = identity,
							ItemId = (((Object)(object)allItem.m_dropPrefab != (Object)null) ? ((Object)allItem.m_dropPrefab).name : allItem.m_shared.m_name),
							DisplayName = GetDisplayName(allItem),
							Icon = allItem.GetIcon()
						};
						dictionary.Add(identity, value);
					}
					value.Count += Math.Max(0, allItem.m_stack);
					value.Items.Add(allItem);
				}
			}
			return dictionary.Values.Where((RuneStorageItemGroup group) => normalizedSearch.Length == 0 || group.DisplayName.IndexOf(normalizedSearch, StringComparison.OrdinalIgnoreCase) >= 0 || group.ItemId.IndexOf(normalizedSearch, StringComparison.OrdinalIgnoreCase) >= 0).OrderBy<RuneStorageItemGroup, string>((RuneStorageItemGroup group) => group.DisplayName, StringComparer.OrdinalIgnoreCase).ThenBy<RuneStorageItemGroup, string>((RuneStorageItemGroup group) => group.Identity, StringComparer.Ordinal)
				.ToList();
		}

		internal static string GetIdentity(ItemData item)
		{
			if (item == null || item.m_shared == null)
			{
				return null;
			}
			StringBuilder stringBuilder = new StringBuilder(128);
			Append(stringBuilder, ((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : item.m_shared.m_name);
			Append(stringBuilder, item.m_shared.m_name);
			Append(stringBuilder, item.m_quality.ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, item.m_variant.ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, item.m_worldLevel.ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, item.m_durability.ToString("R", CultureInfo.InvariantCulture));
			Append(stringBuilder, item.m_crafterID.ToString(CultureInfo.InvariantCulture));
			Append(stringBuilder, item.m_crafterName ?? string.Empty);
			Append(stringBuilder, item.m_equipped ? "1" : "0");
			Append(stringBuilder, item.m_cheated ? "1" : "0");
			if (item.m_customData != null)
			{
				foreach (KeyValuePair<string, string> item2 in item.m_customData.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> pair) => pair.Key, StringComparer.Ordinal))
				{
					Append(stringBuilder, item2.Key ?? string.Empty);
					Append(stringBuilder, item2.Value ?? string.Empty);
				}
			}
			return stringBuilder.ToString();
		}

		private static string GetDisplayName(ItemData item)
		{
			string text = ((item.m_shared != null) ? item.m_shared.m_name : null);
			if (string.IsNullOrEmpty(text))
			{
				if (!((Object)(object)item.m_dropPrefab != (Object)null))
				{
					return "Unknown item";
				}
				return ((Object)item.m_dropPrefab).name;
			}
			try
			{
				if (Localization.instance != null)
				{
					string text2 = Localization.instance.Localize(text);
					if (!string.IsNullOrEmpty(text2))
					{
						return text2;
					}
				}
			}
			catch (Exception)
			{
			}
			return text;
		}

		private static void Append(StringBuilder builder, string value)
		{
			value = value ?? string.Empty;
			builder.Append(value.Length.ToString(CultureInfo.InvariantCulture));
			builder.Append(':');
			builder.Append(value);
			builder.Append('|');
		}
	}
	internal static class RuneStorageTransactions
	{
		private static readonly HashSet<int> ActiveCoreOperations = new HashSet<int>();

		internal static bool TryBeginCoreOperation(RuneStorageCoreMarker marker, out int operationId)
		{
			operationId = (((Object)(object)marker != (Object)null) ? ((Object)marker).GetInstanceID() : 0);
			if ((Object)(object)marker == (Object)null)
			{
				return false;
			}
			lock (ActiveCoreOperations)
			{
				return ActiveCoreOperations.Add(operationId);
			}
		}

		internal static void EndCoreOperation(int operationId)
		{
			lock (ActiveCoreOperations)
			{
				ActiveCoreOperations.Remove(operationId);
			}
		}
	}
	internal enum RuneStorageTransferKind
	{
		DepositAll,
		DepositIdentity,
		DepositExact,
		Withdraw
	}
	internal static class RuneStorageTransfers
	{
		private sealed class SourceChunk
		{
			internal ItemData Original;

			internal int Amount;
		}

		private sealed class PendingTransfer
		{
			internal RuneStorageCoreMarker Core;

			internal Player Player;

			internal RuneStorageTransferKind Kind;

			internal List<SourceChunk> Sources;
		}

		internal const int MaxPayloadCharacters = 524288;

		internal const int MaxItemsPerPayload = 1024;

		private static readonly MethodInfo InventoryChanged = AccessTools.Method(typeof(Inventory), "Changed", new Type[2]
		{
			typeof(bool),
			typeof(bool)
		}, (Type[])null);

		private static readonly Dictionary<string, PendingTransfer> Pending = new Dictionary<string, PendingTransfer>(StringComparer.Ordinal);

		internal static string WireName(RuneStorageTransferKind kind)
		{
			return kind switch
			{
				RuneStorageTransferKind.DepositAll => "deposit-all", 
				RuneStorageTransferKind.DepositIdentity => "deposit-identity", 
				RuneStorageTransferKind.DepositExact => "deposit-exact", 
				_ => "withdraw", 
			};
		}

		internal static bool TryParseWireName(string value, out RuneStorageTransferKind kind)
		{
			switch (value)
			{
			case "deposit-all":
				kind = RuneStorageTransferKind.DepositAll;
				return true;
			case "deposit-identity":
				kind = RuneStorageTransferKind.DepositIdentity;
				return true;
			case "deposit-exact":
				kind = RuneStorageTransferKind.DepositExact;
				return true;
			case "withdraw":
				kind = RuneStorageTransferKind.Withdraw;
				return true;
			default:
				kind = RuneStorageTransferKind.DepositAll;
				return false;
			}
		}

		internal static bool HasPendingTransfer(RuneStorageCoreMarker core)
		{
			return Pending.Values.Any((PendingTransfer pending) => (Object)(object)pending.Core == (Object)(object)core);
		}

		internal static string Start(Player player, RuneStorageTerminalMarker terminal, RuneStorageTransferKind kind, string identity, int amount, int expectedQuantity, out bool waiting)
		{
			waiting = false;
			if ((kind == RuneStorageTransferKind.Withdraw || kind == RuneStorageTransferKind.DepositExact) && amount <= 0)
			{
				return "Enter an amount greater than zero.";
			}
			if (!RuneStorageCoreAccess.TryResolve(player, terminal, out var marker, out var container, out var reason))
			{
				return reason;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			Inventory inventory2 = container.GetInventory();
			if (inventory == null || inventory2 == null)
			{
				return "A player or Core inventory is unavailable. No items were moved.";
			}
			if (HasPendingTransfer(marker))
			{
				return "A transfer is already waiting for the Core owner. Wait for it to finish.";
			}
			if (container.IsOwner())
			{
				return RunOnOwnedCore(player, marker, container, kind, identity, amount, expectedQuantity);
			}
			return StartRemote(player, marker, container, kind, identity, amount, expectedQuantity, out waiting);
		}

		private static string RunOnOwnedCore(Player player, RuneStorageCoreMarker marker, Container core, RuneStorageTransferKind kind, string identity, int amount, int expectedQuantity)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			Inventory inventory2 = core.GetInventory();
			if (!RuneStorageTransactions.TryBeginCoreOperation(marker, out var operationId))
			{
				return "The Core is already handling a transfer. Try again in a moment.";
			}
			try
			{
				if (kind == RuneStorageTransferKind.Withdraw)
				{
					return LocalWithdraw(player, inventory, inventory2, identity, amount, expectedQuantity);
				}
				string message;
				List<SourceChunk> list = CollectSources(inventory, kind, identity, amount, out message);
				if (list == null)
				{
					return message;
				}
				List<ItemData> copies = list.Select((SourceChunk source) => CopyWithAmount(source.Original, source.Amount)).ToList();
				string shortfall;
				int[] accepted = CommitDepositToCore(inventory2, copies, kind != RuneStorageTransferKind.DepositExact, out shortfall);
				RemoveAcceptedFromSources(inventory, list, accepted);
				return DepositMessage(accepted, message, shortfall);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RuneStorage local transfer failed: {arg}");
				return "The transfer stopped after an inventory error. Check both inventories before retrying.";
			}
			finally
			{
				RuneStorageTransactions.EndCoreOperation(operationId);
			}
		}

		private static string LocalWithdraw(Player player, Inventory playerInventory, Inventory coreInventory, string identity, int amount, int expectedQuantity)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			Vector3 value = ((Component)player).transform.position + ((Component)player).transform.forward + Vector3.up * 0.5f;
			List<ItemData> list = CoreStacks(coreInventory, identity);
			long num = ((IEnumerable<ItemData>)list).Sum((Func<ItemData, long>)((ItemData item) => Math.Max(0, item.m_stack)));
			if (list.Count == 0)
			{
				return "That item changed or is no longer stored. The list has been refreshed.";
			}
			if (expectedQuantity