Decompiled source of NearbyStorage v1.0.7

Landoria.NearbyStorage.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GUIFramework;
using HarmonyLib;
using Landoria.Shared;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Landoria.NearbyStorage")]
[assembly: AssemblyDescription("Stacks nearby items and crafts from nearby chests.")]
[assembly: AssemblyCompany("Landoria")]
[assembly: AssemblyProduct("Landoria.NearbyStorage")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0.7")]
[assembly: AssemblyInformationalVersion("1.0.7")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.7.32348")]
[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 Landoria.Shared
{
	internal static class ConfigWatcher
	{
		private const int ReloadDelayMilliseconds = 250;

		private const int MaximumReloadAttempts = 5;

		private static ConfigFile config;

		private static string configPath;

		private static ManualLogSource logger;

		private static FileSystemWatcher watcher;

		private static long lastChangeTicks;

		private static int reloadPending;

		private static int reloadAttempts;

		private static long ignoredWriteTicks;

		private static string displayName;

		private static Action restoreDefaults;

		private static Action applyConfiguration;

		internal static void Initialize(ConfigFile configFile, ManualLogSource logSource, string configurationDisplayName, Action restoreDefaultsAction, Action applyConfigurationAction = null)
		{
			Dispose();
			config = configFile;
			logger = logSource;
			displayName = configurationDisplayName;
			restoreDefaults = restoreDefaultsAction;
			applyConfiguration = applyConfigurationAction;
			configPath = Path.GetFullPath(config.ConfigFilePath);
			watcher = new FileSystemWatcher(Path.GetDirectoryName(configPath), Path.GetFileName(configPath));
			watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
			watcher.Changed += OnChanged;
			watcher.Created += OnChanged;
			watcher.Deleted += OnChanged;
			watcher.Renamed += OnRenamed;
			watcher.EnableRaisingEvents = true;
		}

		internal static void IgnoreCurrentFileVersion()
		{
			if (string.IsNullOrEmpty(configPath) || !File.Exists(configPath))
			{
				return;
			}
			try
			{
				Interlocked.Exchange(ref ignoredWriteTicks, File.GetLastWriteTimeUtc(configPath).Ticks);
				Interlocked.Exchange(ref reloadPending, 0);
			}
			catch (IOException)
			{
				ManualLogSource obj = logger;
				if (obj != null)
				{
					obj.LogDebug((object)"Could not mark the internal configuration write.");
				}
			}
		}

		internal static void Update()
		{
			if (Volatile.Read(in reloadPending) == 0 || !ReloadDelayElapsed())
			{
				return;
			}
			Interlocked.Exchange(ref reloadPending, 0);
			try
			{
				bool flag = !File.Exists(configPath);
				if (flag)
				{
					restoreDefaults?.Invoke();
				}
				else
				{
					config.Reload();
				}
				applyConfiguration?.Invoke();
				reloadAttempts = 0;
				logger.LogInfo((object)(flag ? "Recreated the deleted configuration with default values." : "Reloaded configuration after a file change."));
				ShowReloadMessage(flag);
			}
			catch (Exception exception)
			{
				RetryReload(exception);
			}
		}

		internal static void Dispose()
		{
			if (watcher != null)
			{
				watcher.EnableRaisingEvents = false;
				watcher.Dispose();
				watcher = null;
			}
			Interlocked.Exchange(ref reloadPending, 0);
			Interlocked.Exchange(ref ignoredWriteTicks, 0L);
			reloadAttempts = 0;
			displayName = null;
			restoreDefaults = null;
			applyConfiguration = null;
		}

		private static void OnChanged(object sender, FileSystemEventArgs eventArgs)
		{
			QueueReload();
		}

		private static void OnRenamed(object sender, RenamedEventArgs eventArgs)
		{
			QueueReload();
		}

		private static void QueueReload()
		{
			if (!IsIgnoredWrite())
			{
				Interlocked.Exchange(ref lastChangeTicks, DateTime.UtcNow.Ticks);
				Interlocked.Exchange(ref reloadPending, 1);
				reloadAttempts = 0;
			}
		}

		private static bool IsIgnoredWrite()
		{
			try
			{
				long num = (File.Exists(configPath) ? File.GetLastWriteTimeUtc(configPath).Ticks : 0);
				return num != 0L && num == Interlocked.Read(in ignoredWriteTicks);
			}
			catch (IOException)
			{
				return false;
			}
		}

		private static bool ReloadDelayElapsed()
		{
			return DateTime.UtcNow.Ticks - Interlocked.Read(in lastChangeTicks) >= 2500000;
		}

		private static void RetryReload(Exception exception)
		{
			reloadAttempts++;
			logger.LogWarning((object)("Configuration reload failed: " + exception.Message));
			if (reloadAttempts < 5)
			{
				Interlocked.Exchange(ref lastChangeTicks, DateTime.UtcNow.Ticks);
				Interlocked.Exchange(ref reloadPending, 1);
			}
		}

		private static void ShowReloadMessage(bool recreated)
		{
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)1, recreated ? (displayName + " configuration restored to defaults.") : (displayName + " configuration reloaded."), 0, (Sprite)null, false);
			}
		}
	}
}
namespace Landoria.NearbyStorage
{
	[HarmonyPatch(typeof(Player), "ConsumeResources", new Type[]
	{
		typeof(Requirement[]),
		typeof(int),
		typeof(int),
		typeof(int)
	})]
	internal static class BuildingDebitPatch
	{
		private static bool Prefix(Player __instance, Requirement[] requirements, int qualityLevel)
		{
			if (!BuildingState.Matches(__instance, requirements, qualityLevel))
			{
				return true;
			}
			BuildingState.Consume(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "TryPlacePiece")]
	internal static class BuildingPlacementPatch
	{
		private static bool Prefix(Player __instance, Piece piece, ref bool __result)
		{
			if (BuildingState.Prepare(__instance, piece))
			{
				return true;
			}
			__result = false;
			return false;
		}

		private static void Postfix(bool __result)
		{
			if (!__result)
			{
				BuildingState.Reset();
			}
		}

		private static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				BuildingState.Reset();
			}
			return __exception;
		}
	}
	internal static class BuildingPlan
	{
		internal static bool IsBuildPiece(Player player, Piece piece)
		{
			if ((Object)(object)player != (Object)null && ((Character)player).InPlaceMode())
			{
				return (Object)(object)piece != (Object)null;
			}
			return false;
		}

		internal static CraftPlan Build(Player player, Piece piece)
		{
			if (!CanBuild(player, piece))
			{
				return null;
			}
			CraftPlan craftPlan = new CraftPlan();
			StorageSupply storageSupply = new StorageSupply(player);
			Requirement[] resources = piece.m_resources;
			foreach (Requirement val in resources)
			{
				if (!((Object)(object)val.m_resItem == (Object)null) && val.m_amount > 0)
				{
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					int amount = val.GetAmount(0);
					amount = storageSupply.AllocateAnyQuality(craftPlan, name, amount);
					if (amount > 0)
					{
						return null;
					}
				}
			}
			return craftPlan;
		}

		private static bool CanBuild(Player player, Piece piece)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (IsBuildPiece(player, piece) && (piece.m_dlc.Length == 0 || DLCMan.instance.IsDLCInstalled(piece.m_dlc)))
			{
				if (!((Object)(object)piece.m_craftingStation == (Object)null) && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)player).transform.position)))
				{
					return ZoneSystem.instance.GetGlobalKey((GlobalKeys)27);
				}
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Piece),
		typeof(RequirementMode)
	})]
	internal static class BuildingRequirementsPatch
	{
		private static void Postfix(Player __instance, Piece piece, RequirementMode mode, ref bool __result)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if (!__result && ((int)mode == 0 || (int)mode == 2) && (Object)(object)__instance == (Object)(object)Player.m_localPlayer && NearbyStorageActionInput.IsHeld() && BuildingPlan.IsBuildPiece(__instance, piece))
			{
				__result = BuildingPlan.Build(__instance, piece) != null;
			}
		}
	}
	internal static class BuildingState
	{
		private static CraftPlan _plan;

		private static Player _player;

		private static Piece _piece;

		internal static bool Matches(Player player, Requirement[] requirements, int qualityLevel)
		{
			if (_plan != null && (Object)(object)player == (Object)(object)_player && qualityLevel == 0)
			{
				return requirements == _piece.m_resources;
			}
			return false;
		}

		internal static bool Prepare(Player player, Piece piece)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Reset();
			if ((Object)(object)player != (Object)(object)Player.m_localPlayer || !NearbyStorageActionInput.IsHeld() || !BuildingPlan.IsBuildPiece(player, piece) || player.NoCostCheat() || ZoneSystem.instance.GetGlobalKey(piece.FreeBuildKey()))
			{
				return true;
			}
			CraftPlan craftPlan = BuildingPlan.Build(player, piece);
			if (craftPlan == null || !craftPlan.ClaimSources(player) || !craftPlan.StillAvailable(player))
			{
				return false;
			}
			_player = player;
			_piece = piece;
			_plan = craftPlan;
			return true;
		}

		internal static void Consume(Player player)
		{
			if ((Object)(object)player != (Object)(object)_player || _plan == null)
			{
				return;
			}
			try
			{
				_plan.Consume();
			}
			finally
			{
				Reset();
			}
		}

		internal static void Reset()
		{
			_plan = null;
			_player = null;
			_piece = null;
		}
	}
	internal static class BuildingUiRefresh
	{
		private static readonly MethodInfo RefreshHudIcons = AccessTools.Method(typeof(Hud), "UpdatePieceBuildStatusAll", (Type[])null, (Type[])null);

		private static bool _lastHeld;

		internal static void Update()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).InPlaceMode())
			{
				_lastHeld = false;
				return;
			}
			bool flag = NearbyStorageActionInput.IsHeld();
			if (flag == _lastHeld)
			{
				return;
			}
			_lastHeld = flag;
			try
			{
				if ((Object)(object)Hud.instance != (Object)null && RefreshHudIcons != null)
				{
					RefreshHudIcons.Invoke(Hud.instance, new object[2]
					{
						localPlayer.GetBuildPieces(),
						localPlayer
					});
				}
				BuildUiPieceButton[] array = Object.FindObjectsByType<BuildUiPieceButton>((FindObjectsSortMode)0);
				foreach (BuildUiPieceButton val in array)
				{
					if (((Behaviour)val).isActiveAndEnabled && (Object)(object)val.Piece != (Object)null)
					{
						val.UpdateRequirements();
					}
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Nearby Storage build icon refresh failed: " + ex));
			}
		}

		internal static void Reset()
		{
			_lastHeld = false;
		}
	}
	internal sealed class ModConfigFile
	{
		private const float DefaultRadius = 60f;

		internal ConfigEntry<float> Radius { get; }

		internal ConfigEntry<bool> IncludeChestsByDefault { get; }

		internal ConfigEntry<bool> SeparateStacksByContainer { get; }

		internal ConfigEntry<bool> AutomaticItemDistribution { get; }

		internal ConfigEntry<KeyboardShortcut> NearbyStorageShortcut { get; }

		internal ModConfigFile(ConfigFile config)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			Radius = config.Bind<float>("General", "SearchRadius", 60f, new ConfigDescription("Radius around the player for nearby storage, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), Array.Empty<object>()));
			IncludeChestsByDefault = config.Bind<bool>("General", "IncludeChestsByDefault", true, "Whether chests without an individual inclusion choice are included in Nearby Storage.");
			SeparateStacksByContainer = config.Bind<bool>("General", "SeparateStacksByContainer", true, "Show matching items in different containers as separate stacks.");
			AutomaticItemDistribution = config.Bind<bool>("General", "AutomaticItemDistribution", true, "Distribute Ctrl-clicked items among nearby containers.");
			NearbyStorageShortcut = config.Bind<KeyboardShortcut>("Controls", "NearbyStorageShortcut", new KeyboardShortcut((KeyCode)308, Array.Empty<KeyCode>()), "Hold this shortcut to use nearby storage while crafting, building, refueling, or feeding.");
		}

		internal void RestoreDefaults(ConfigFile config)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				Radius.Value = 60f;
				IncludeChestsByDefault.Value = true;
				SeparateStacksByContainer.Value = true;
				AutomaticItemDistribution.Value = true;
				NearbyStorageShortcut.Value = new KeyboardShortcut((KeyCode)308, Array.Empty<KeyCode>());
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			config.Save();
			ConfigWatcher.IgnoreCurrentFileVersion();
		}
	}
	internal static class NearbyStorageActionInput
	{
		internal static bool IsHeld()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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)
			if (Plugin.Instance?.Settings == null)
			{
				return false;
			}
			KeyboardShortcut value = Plugin.Instance.Settings.NearbyStorageShortcut.Value;
			if ((int)((KeyboardShortcut)(ref value)).MainKey == 0 || !ZInput.GetKey(((KeyboardShortcut)(ref value)).MainKey, true))
			{
				return false;
			}
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers)
			{
				if (!ZInput.GetKey(modifier, true))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class ButtonHalo
	{
		private static Image _craft;

		private static Sprite _glowSprite;

		internal static void Update()
		{
			bool flag = InventoryGui.IsVisible() && (Object)(object)Player.m_localPlayer != (Object)null && NearbyStorageActionInput.IsHeld();
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance == (Object)null)
			{
				Clear();
			}
			else
			{
				Set(ref _craft, instance.m_craftButton, flag && ((Selectable)instance.m_craftButton).interactable);
			}
		}

		internal static void Clear()
		{
			if ((Object)(object)_craft != (Object)null)
			{
				((Behaviour)_craft).enabled = false;
			}
		}

		internal static void Dispose()
		{
			if ((Object)(object)_craft != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_craft).gameObject);
			}
			_craft = null;
			_glowSprite = null;
		}

		private static void Set(ref Image glow, Button button, bool active)
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)button == (Object)null || (Object)(object)((Selectable)button).targetGraphic == (Object)null)
			{
				if ((Object)(object)glow != (Object)null)
				{
					((Behaviour)glow).enabled = false;
				}
				return;
			}
			if (!active || !((Component)button).gameObject.activeInHierarchy)
			{
				if ((Object)(object)glow != (Object)null)
				{
					((Behaviour)glow).enabled = false;
				}
				return;
			}
			if ((Object)(object)_glowSprite == (Object)null)
			{
				_glowSprite = FindGlowSprite();
				if ((Object)(object)_glowSprite == (Object)null)
				{
					return;
				}
			}
			if ((Object)(object)glow == (Object)null || (Object)(object)((Component)glow).transform.parent != (Object)(object)((Component)((Selectable)button).targetGraphic).transform)
			{
				glow = CreateGlow(glow, button);
			}
			((Behaviour)glow).enabled = true;
			float num = 0.5f + 0.15f * Mathf.Sin(Time.unscaledTime * 3f);
			((Graphic)glow).color = new Color(1f, 61f / 85f, 0.35686275f, num);
		}

		private static Sprite FindGlowSprite()
		{
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if (((Object)val).name == "button_glow")
				{
					return val;
				}
			}
			return null;
		}

		private static Image CreateGlow(Image existingGlow, Button button)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)existingGlow != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)existingGlow).gameObject);
			}
			GameObject val = new GameObject("NearbyStorageGlow", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(((Component)((Selectable)button).targetGraphic).transform, false);
			val.transform.SetAsFirstSibling();
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.offsetMin = Vector2.zero;
			val2.offsetMax = Vector2.zero;
			Image component = val.GetComponent<Image>();
			component.sprite = _glowSprite;
			component.type = (Type)1;
			((Graphic)component).raycastTarget = false;
			return component;
		}
	}
	[HarmonyPatch(typeof(Inventory), "ItemCheated", new Type[]
	{
		typeof(Requirement[]),
		typeof(int),
		typeof(bool)
	})]
	internal static class CheatedIngredientPatch
	{
		private static void Postfix(Inventory __instance, ref bool __result)
		{
			if (!__result && CraftState.Armed && CraftState.Plan != null && (Object)(object)Player.m_localPlayer != (Object)null && __instance == ((Humanoid)Player.m_localPlayer).GetInventory())
			{
				__result = CraftState.Plan.HasCheatedIngredient();
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnCraftCancelPressed")]
	internal static class CraftCancelPatch
	{
		private static void Postfix()
		{
			CraftState.Reset();
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
	internal static class CraftClickPatch
	{
		private static bool Prefix(InventoryGui __instance)
		{
			return CraftState.Arm(__instance);
		}

		private static void Postfix(InventoryGui __instance)
		{
			CraftState.ResetIfNoTimer(__instance);
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	internal static class CraftCompletionPatch
	{
		private static bool Prefix(InventoryGui __instance, Player player)
		{
			return CraftState.Prepare(__instance, player);
		}

		private static void Postfix()
		{
			CraftState.Reset();
		}
	}
	internal sealed class CraftPlan
	{
		internal readonly List<Withdrawal> Withdrawals = new List<Withdrawal>();

		internal ItemData SingleItem;

		internal int SingleNeed;

		internal int SingleExtra;

		internal static CraftPlan Build(Player player, Recipe recipe, int quality, int multiplier)
		{
			if (!CanPlan(player, recipe, multiplier))
			{
				return null;
			}
			CraftPlan craftPlan = new CraftPlan();
			StorageSupply supply = new StorageSupply(player);
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			bool flag = false;
			Requirement[] resources = recipe.m_resources;
			foreach (Requirement val in resources)
			{
				if (!Relevant(val, currentCraftingStation))
				{
					continue;
				}
				int num = val.GetAmount(quality) * multiplier;
				if (num <= 0)
				{
					continue;
				}
				if (TryRequirement(craftPlan, supply, val, num, recipe.m_requireOnlyOneIngredient))
				{
					flag = true;
					if (recipe.m_requireOnlyOneIngredient)
					{
						craftPlan.SingleNeed = num;
						craftPlan.SingleExtra = val.m_extraAmountOnlyOneIngredient;
						break;
					}
				}
				else if (!recipe.m_requireOnlyOneIngredient)
				{
					return null;
				}
			}
			if (!(!recipe.m_requireOnlyOneIngredient || flag))
			{
				return null;
			}
			return craftPlan;
		}

		private static bool CanPlan(Player player, Recipe recipe, int multiplier)
		{
			if ((Object)(object)player != (Object)null && (Object)(object)recipe != (Object)null)
			{
				return multiplier >= 1;
			}
			return false;
		}

		private static bool TryRequirement(CraftPlan plan, StorageSupply supply, Requirement requirement, int need, bool single)
		{
			string name = requirement.m_resItem.m_itemData.m_shared.m_name;
			int maxQuality = requirement.m_resItem.m_itemData.m_shared.m_maxQuality;
			for (int i = 1; i <= maxQuality; i++)
			{
				if (supply.Available(plan, name, i) >= need)
				{
					int num = supply.Allocate(plan, name, i, need);
					if (single)
					{
						plan.SingleItem = FindItem(plan, name, i);
					}
					return num == 0;
				}
			}
			return false;
		}

		private static ItemData FindItem(CraftPlan plan, string name, int quality)
		{
			foreach (Withdrawal withdrawal in plan.Withdrawals)
			{
				if (withdrawal.Name != name || withdrawal.Quality != quality)
				{
					continue;
				}
				foreach (ItemData allItem in withdrawal.Inventory.GetAllItems())
				{
					if (allItem.m_shared.m_name == name && allItem.m_quality == quality)
					{
						return allItem;
					}
				}
			}
			return null;
		}

		private static bool Relevant(Requirement requirement, CraftingStation station)
		{
			if ((Object)(object)requirement.m_resItem != (Object)null)
			{
				if (!((Object)(object)station == (Object)null) || requirement.m_upgraderResource)
				{
					if ((Object)(object)station != (Object)null)
					{
						return station.m_upgrader == requirement.m_upgraderResource;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal bool ClaimSources(Player player)
		{
			foreach (Withdrawal withdrawal in Withdrawals)
			{
				if ((Object)(object)withdrawal.Chest != (Object)null && !StorageLocator.TryClaimAndLoad(withdrawal.Chest, player))
				{
					return false;
				}
			}
			return true;
		}

		internal bool StillAvailable(Player player)
		{
			foreach (Withdrawal withdrawal in Withdrawals)
			{
				if ((Object)(object)withdrawal.Chest != (Object)null && !StorageLocator.Eligible(withdrawal.Chest, player, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value))
				{
					return false;
				}
				int num = 0;
				foreach (Withdrawal withdrawal2 in Withdrawals)
				{
					if (withdrawal2.Inventory == withdrawal.Inventory && withdrawal2.Name == withdrawal.Name && withdrawal2.Quality == withdrawal.Quality)
					{
						num += withdrawal2.Amount;
					}
				}
				if (withdrawal.Inventory.CountItems(withdrawal.Name, withdrawal.Quality, true) < num)
				{
					return false;
				}
			}
			return true;
		}

		internal void Consume()
		{
			foreach (Withdrawal withdrawal in Withdrawals)
			{
				withdrawal.Inventory.RemoveItem(withdrawal.Name, withdrawal.Amount, withdrawal.Quality, true);
			}
		}

		internal bool HasCheatedIngredient()
		{
			foreach (Withdrawal withdrawal in Withdrawals)
			{
				if (withdrawal.Inventory.ItemCheated(withdrawal.Name, withdrawal.Quality, true))
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class CraftState
	{
		private static readonly FieldInfo SelectedField = AccessTools.Field(typeof(InventoryGui), "m_selectedRecipe");

		private static readonly FieldInfo RecipeField = AccessTools.Field(typeof(InventoryGui), "m_craftRecipe");

		private static readonly FieldInfo UpgradeField = AccessTools.Field(typeof(InventoryGui), "m_craftUpgradeItem");

		private static readonly FieldInfo MultiField = AccessTools.Field(typeof(InventoryGui), "m_multiCrafting");

		private static readonly FieldInfo TouchField = AccessTools.Field(typeof(InventoryGui), "m_touchMultiCrafting");

		private static readonly FieldInfo TimerField = AccessTools.Field(typeof(InventoryGui), "m_craftTimer");

		private static readonly PropertyInfo SelectedRecipe = AccessTools.Property(SelectedField.FieldType, "Recipe");

		private static readonly PropertyInfo SelectedItem = AccessTools.Property(SelectedField.FieldType, "ItemData");

		internal static bool Armed { get; private set; }

		internal static bool Consuming { get; private set; }

		internal static CraftPlan Plan { get; private set; }

		internal static bool Checking
		{
			get
			{
				if ((Object)(object)Plugin.Instance != (Object)null && InventoryGui.IsVisible())
				{
					if (!NearbyStorageActionInput.IsHeld())
					{
						return Armed;
					}
					return true;
				}
				return false;
			}
		}

		internal static bool Arm(InventoryGui gui)
		{
			Reset();
			if (!NearbyStorageActionInput.IsHeld())
			{
				return true;
			}
			object value = SelectedField.GetValue(gui);
			object? value2 = SelectedRecipe.GetValue(value);
			Recipe val = (Recipe)((value2 is Recipe) ? value2 : null);
			object? value3 = SelectedItem.GetValue(value);
			ItemData val2 = (ItemData)((value3 is ItemData) ? value3 : null);
			if ((Object)(object)val == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			int multiplier = ((val2 != null || (!ZInput.GetButton("AltPlace") && !ZInput.GetButton("JoyLStick") && !(bool)TouchField.GetValue(gui))) ? 1 : gui.m_multiCraftAmount);
			int quality = ((val2 == null) ? 1 : (val2.m_quality + 1));
			if ((val.m_requireOnlyOneIngredient || !FreeCraft(Player.m_localPlayer)) && CraftPlan.Build(Player.m_localPlayer, val, quality, multiplier) == null)
			{
				return false;
			}
			Armed = true;
			return true;
		}

		internal static bool Prepare(InventoryGui gui, Player player)
		{
			if (!Armed)
			{
				return true;
			}
			object? value = RecipeField.GetValue(gui);
			Recipe val = (Recipe)((value is Recipe) ? value : null);
			object? value2 = UpgradeField.GetValue(gui);
			ItemData val2 = (ItemData)((value2 is ItemData) ? value2 : null);
			int quality = ((val2 == null) ? 1 : (val2.m_quality + 1));
			int multiplier = ((!(bool)MultiField.GetValue(gui)) ? 1 : gui.m_multiCraftAmount);
			if (FreeCraft(player))
			{
				if ((Object)(object)val != (Object)null)
				{
					if (val.m_requireOnlyOneIngredient)
					{
						return CraftPlan.Build(player, val, quality, multiplier) != null;
					}
					return true;
				}
				return false;
			}
			Plan = CraftPlan.Build(player, val, quality, multiplier);
			if (Plan == null || !Plan.ClaimSources(player))
			{
				return false;
			}
			Plan = CraftPlan.Build(player, val, quality, multiplier);
			if (Plan != null)
			{
				return Plan.StillAvailable(player);
			}
			return false;
		}

		internal static void Consume()
		{
			if (Plan == null || Consuming)
			{
				return;
			}
			Consuming = true;
			try
			{
				Plan.Consume();
			}
			finally
			{
				Consuming = false;
				Plan = null;
			}
		}

		internal static void ResetIfNoTimer(InventoryGui gui)
		{
			if ((float)TimerField.GetValue(gui) < 0f)
			{
				Reset();
			}
		}

		internal static void Reset()
		{
			Armed = false;
			Consuming = false;
			Plan = null;
		}

		internal static bool FreeCraft(Player player)
		{
			if (!player.NoCostCheat())
			{
				return ZoneSystem.instance.GetGlobalKey((GlobalKeys)25);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	internal static class CraftTooltipPatch
	{
		private static void Prefix(InventoryGui __instance, out string __state)
		{
			UITooltip component = ((Component)__instance.m_craftButton).GetComponent<UITooltip>();
			__state = (((Object)(object)component == (Object)null) ? null : component.m_text);
		}

		private static void Postfix(InventoryGui __instance, string __state)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			UITooltip component = ((Component)__instance.m_craftButton).GetComponent<UITooltip>();
			if (!((Object)(object)component == (Object)null) && !(component.m_text == __state))
			{
				string text = component.m_text;
				component.m_text = __state;
				component.Set(component.m_topic, text, (RectTransform)null, default(Vector2));
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Hide")]
	internal static class InventoryClosePatch
	{
		private static void Postfix()
		{
			CraftState.Reset();
			ButtonHalo.Clear();
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Update")]
	internal static class RecipeListRefreshPatch
	{
		private static readonly MethodInfo UpdatePanel = AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", (Type[])null, (Type[])null);

		private static InventoryGui _lastGui;

		private static bool _lastChecking;

		private static void Postfix(InventoryGui __instance)
		{
			if ((Object)(object)_lastGui != (Object)(object)__instance)
			{
				_lastGui = __instance;
				_lastChecking = false;
			}
			bool checking = CraftState.Checking;
			if (checking == _lastChecking)
			{
				return;
			}
			_lastChecking = checking;
			if (!InventoryGui.IsVisible() || UpdatePanel == null)
			{
				return;
			}
			try
			{
				UpdatePanel.Invoke(__instance, new object[1] { false });
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Nearby Storage recipe refresh failed: " + ex));
			}
		}

		internal static void Reset()
		{
			_lastGui = null;
			_lastChecking = false;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	internal static class RequirementDisplayPatch
	{
		private static void Postfix(Transform elementRoot, Requirement req, Player player, bool craft, int quality, int craftMultiplier, bool __result)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || (Object)(object)player != (Object)(object)Player.m_localPlayer || (Object)(object)req?.m_resItem == (Object)null)
			{
				return;
			}
			bool num = craft && CraftState.Checking;
			bool flag = ((Character)player).InPlaceMode() && NearbyStorageActionInput.IsHeld();
			if (!num && !flag)
			{
				return;
			}
			string name = req.m_resItem.m_itemData.m_shared.m_name;
			if (new StorageSupply(player).Available(null, name, -1) >= req.GetAmount(quality) * craftMultiplier)
			{
				Transform val = elementRoot.Find("res_amount");
				if ((Object)(object)val != (Object)null)
				{
					((Graphic)((Component)val).GetComponent<TMP_Text>()).color = Color.white;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class RequirementPatch
	{
		private static void Postfix(Player __instance, Recipe recipe, bool discover, int qualityLevel, int amount, ref bool __result)
		{
			if (!(__result || discover) && CraftState.Checking && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && __instance.RequiredCraftingStation(recipe, qualityLevel, true))
			{
				string dlc = recipe.m_item.m_itemData.m_shared.m_dlc;
				if (dlc.Length <= 0 || DLCMan.instance.IsDLCInstalled(dlc))
				{
					__result = CraftPlan.Build(__instance, recipe, qualityLevel, amount) != null;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "ConsumeResources", new Type[]
	{
		typeof(Requirement[]),
		typeof(int),
		typeof(int),
		typeof(int)
	})]
	internal static class ResourceDebitPatch
	{
		private static bool Prefix(Player __instance)
		{
			if (!CraftState.Armed || CraftState.Plan == null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			CraftState.Consume();
			return false;
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	internal static class SingleDebitPatch
	{
		private static bool Prefix(Inventory __instance)
		{
			if (!CraftState.Armed || CraftState.Plan == null || CraftState.Consuming || (Object)(object)Player.m_localPlayer == (Object)null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
			{
				return true;
			}
			CraftState.Consume();
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "GetFirstRequiredItem")]
	internal static class SingleIngredientPatch
	{
		private static void Postfix(Player __instance, Recipe recipe, int qualityLevel, int craftMultiplier, ref ItemData __result, ref int amount, ref int extraAmount)
		{
			if (__result == null && CraftState.Checking && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
			{
				CraftPlan craftPlan = CraftPlan.Build(__instance, recipe, qualityLevel, craftMultiplier);
				if (craftPlan != null)
				{
					__result = craftPlan.SingleItem;
					amount = craftPlan.SingleNeed;
					extraAmount = craftPlan.SingleExtra;
				}
			}
		}
	}
	internal sealed class Withdrawal
	{
		internal Inventory Inventory;

		internal Container Chest;

		internal ItemData SelectedItem;

		internal string Name;

		internal int Quality;

		internal int Amount;
	}
	[HarmonyPatch(typeof(CookingStation), "OnInteract")]
	internal static class CookingFeedPatch
	{
		private static void Prefix(Humanoid user)
		{
			FeedContext.Begin(user);
		}

		private static void Finalizer()
		{
			FeedContext.Reset();
		}
	}
	[HarmonyPatch(typeof(CookingStation), "FindCookableItem")]
	internal static class CookingInputPatch
	{
		private static void Postfix(CookingStation __instance, Inventory inventory, ref ItemData __result)
		{
			if (__result == null)
			{
				__result = FeedContext.FindConversion(inventory, __instance.m_conversion, (ItemConversion conversion) => conversion.m_from);
			}
		}
	}
	internal static class FeedContext
	{
		private static Player _player;

		private static Container _chest;

		private static ItemData _item;

		internal static void Begin(Humanoid user)
		{
			Reset();
			if ((Object)(object)user == (Object)(object)Player.m_localPlayer && NearbyStorageActionInput.IsHeld())
			{
				_player = Player.m_localPlayer;
			}
		}

		internal static ItemData Find(Inventory inventory, IEnumerable<string> names)
		{
			if (names == null)
			{
				return null;
			}
			List<string> candidates = new List<string>(names);
			return FindStored(inventory, delegate(Inventory source)
			{
				foreach (string item2 in candidates)
				{
					if (!string.IsNullOrEmpty(item2))
					{
						ItemData item = source.GetItem(item2, -1, false);
						if (item != null)
						{
							return item;
						}
					}
				}
				return (ItemData)null;
			});
		}

		internal static ItemData FindConversion<T>(Inventory inventory, IEnumerable<T> conversions, Func<T, ItemDrop> sourceItem)
		{
			List<string> list = new List<string>();
			foreach (T conversion in conversions)
			{
				ItemDrop val = sourceItem(conversion);
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val.m_itemData.m_shared.m_name);
				}
			}
			return Find(inventory, list);
		}

		internal static ItemData FindAmmo(Inventory inventory, string ammoType, string prefab)
		{
			Func<ItemData, bool> matches = (ItemData candidate) => ((int)candidate.m_shared.m_itemType == 9 || (int)candidate.m_shared.m_itemType == 23 || (int)candidate.m_shared.m_itemType == 2) && candidate.m_shared.m_ammoType == ammoType && (prefab == null || ((Object)candidate.m_dropPrefab).name == prefab);
			return FindStored(inventory, delegate(Inventory source)
			{
				ItemData ammoItem = source.GetAmmoItem(ammoType, prefab);
				if (ammoItem != null)
				{
					return ammoItem;
				}
				foreach (ItemData allItem in source.GetAllItems())
				{
					if (matches(allItem))
					{
						return allItem;
					}
				}
				return (ItemData)null;
			});
		}

		internal static ItemData FindByPriority(Inventory inventory, IEnumerable<string> names)
		{
			if ((Object)(object)_player == (Object)null || inventory != ((Humanoid)_player).GetInventory() || names == null)
			{
				return null;
			}
			foreach (string name in names)
			{
				if (!string.IsNullOrEmpty(name))
				{
					ItemData item = inventory.GetItem(name, -1, false);
					if (item != null)
					{
						return item;
					}
					ItemData val = FindStored(inventory, (Inventory source) => source.GetItem(name, -1, false));
					if (val != null)
					{
						return val;
					}
				}
			}
			return null;
		}

		internal static bool IsBorrowed(Inventory inventory, ItemData item)
		{
			if ((Object)(object)_player != (Object)null && inventory == ((Humanoid)_player).GetInventory())
			{
				return item == _item;
			}
			return false;
		}

		internal static bool RemoveBorrowed(Inventory inventory, ItemData item, int amount, ref bool result)
		{
			if (!IsBorrowed(inventory, item))
			{
				return true;
			}
			result = Withdraw(amount);
			return false;
		}

		internal static bool Withdraw(int amount)
		{
			if ((Object)(object)_chest == (Object)null || _item == null || amount != 1 || !StorageLocator.Eligible(_chest, _player, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value))
			{
				return false;
			}
			ZNetView val = StorageLocator.View(_chest);
			if ((Object)(object)val == (Object)null || !val.IsOwner() || !_chest.GetInventory().ContainsItem(_item) || _item.m_stack <= 0)
			{
				return false;
			}
			return _chest.GetInventory().RemoveOneItem(_item);
		}

		internal static void Reset()
		{
			_player = null;
			_chest = null;
			_item = null;
		}

		private static ItemData FindStored(Inventory inventory, Func<Inventory, ItemData> selectChest)
		{
			if ((Object)(object)_player == (Object)null || inventory != ((Humanoid)_player).GetInventory())
			{
				return null;
			}
			Withdrawal withdrawal = new StorageSupply(_player).FindStored(selectChest);
			if (withdrawal == null)
			{
				return null;
			}
			_chest = withdrawal.Chest;
			_item = withdrawal.SelectedItem;
			return _item;
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(ItemData),
		typeof(int)
	})]
	internal static class FeedRemoveAmountPatch
	{
		private static bool Prefix(Inventory __instance, ItemData item, int amount, ref bool __result)
		{
			return FeedContext.RemoveBorrowed(__instance, item, amount, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveOneItem")]
	internal static class FeedRemoveOnePatch
	{
		private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
		{
			return FeedContext.RemoveBorrowed(__instance, item, 1, ref __result);
		}
	}
	[HarmonyPatch(typeof(Fermenter), "Interact")]
	internal static class FermenterFeedPatch
	{
		private static void Prefix(Humanoid user)
		{
			FeedContext.Begin(user);
		}

		private static void Finalizer()
		{
			FeedContext.Reset();
		}
	}
	[HarmonyPatch(typeof(Fermenter), "FindCookableItem")]
	internal static class FermenterInputPatch
	{
		private static void Postfix(Fermenter __instance, Inventory inventory, ref ItemData __result)
		{
			if (__result == null)
			{
				__result = FeedContext.FindConversion(inventory, __instance.m_conversion, (ItemConversion conversion) => conversion.m_from);
			}
		}
	}
	[HarmonyPatch(typeof(Smelter), "OnAddOre")]
	internal static class SmelterFeedPatch
	{
		private static void Prefix(Humanoid user, ItemData item)
		{
			if (item == null)
			{
				FeedContext.Begin(user);
			}
		}

		private static void Finalizer()
		{
			FeedContext.Reset();
		}
	}
	[HarmonyPatch(typeof(Smelter), "FindCookableItem")]
	internal static class SmelterInputPatch
	{
		private static readonly string[] KilnWoodPriority = new string[3] { "$item_wood", "$item_roundlog", "$item_finewood" };

		private static void Postfix(Smelter __instance, Inventory inventory, ref ItemData __result)
		{
			List<string> list = new List<string>();
			foreach (ItemConversion item2 in __instance.m_conversion)
			{
				if ((Object)(object)item2.m_from != (Object)null)
				{
					list.Add(item2.m_from.m_itemData.m_shared.m_name);
				}
			}
			if (((Object)((Component)__instance).gameObject).name.StartsWith("charcoal_kiln", StringComparison.OrdinalIgnoreCase))
			{
				List<string> list2 = new List<string>();
				string[] kilnWoodPriority = KilnWoodPriority;
				foreach (string item in kilnWoodPriority)
				{
					if (list.Contains(item))
					{
						list2.Add(item);
					}
				}
				ItemData val = FeedContext.FindByPriority(inventory, list2);
				if (val != null)
				{
					__result = val;
				}
			}
			else if (__result == null)
			{
				__result = FeedContext.Find(inventory, list);
			}
		}
	}
	[HarmonyPatch(typeof(Turret), "UseItem")]
	internal static class TurretFeedPatch
	{
		private static void Prefix(Humanoid user, ItemData item)
		{
			if (item == null)
			{
				FeedContext.Begin(user);
			}
		}

		private static void Finalizer()
		{
			FeedContext.Reset();
		}
	}
	[HarmonyPatch(typeof(Turret), "FindAmmoItem")]
	internal static class TurretInputPatch
	{
		private static void Postfix(Turret __instance, Inventory inventory, bool onlyCurrentlyLoadableType, ref ItemData __result)
		{
			if (__result == null)
			{
				string prefab = ((onlyCurrentlyLoadableType && __instance.HasAmmo()) ? __instance.GetAmmoType() : null);
				__result = FeedContext.FindAmmo(inventory, __instance.m_ammoType, prefab);
			}
		}
	}
	internal static class ChestInclusion
	{
		internal static bool IsIncluded(Container chest)
		{
			ZNetView val = StorageLocator.View(chest);
			Player localPlayer = Player.m_localPlayer;
			bool result = Plugin.Instance?.Settings?.IncludeChestsByDefault.Value ?? true;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)val == (Object)null || !val.IsValid() || val.GetZDO() == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return result;
			}
			if (localPlayer.m_customData.ContainsKey(ChestKey(val)))
			{
				return false;
			}
			if (localPlayer.m_customData.ContainsKey(IncludedKey(val)))
			{
				return true;
			}
			return result;
		}

		private static string ChestKey(ZNetView view)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = view.GetZDO();
			Vector3 position = zDO.GetPosition();
			return "Landoria.NearbyStorage.Excluded.v2:" + ZNet.instance.GetWorldUID() + ":" + zDO.GetPrefab() + ":" + FloatBits(position.x) + ":" + FloatBits(position.y) + ":" + FloatBits(position.z);
		}

		private static string IncludedKey(ZNetView view)
		{
			return ChestKey(view).Replace(".Excluded.v2:", ".Included.v1:");
		}

		private static string FloatBits(float value)
		{
			return BitConverter.ToInt32(BitConverter.GetBytes(value), 0).ToString("X8");
		}

		internal static string HoverText(Container chest)
		{
			bool num = IsIncluded(chest);
			string text = string.Format(ModText.Get(num ? "ChestIncluded" : "ChestExcluded"), ModText.ModName);
			if (!num)
			{
				text = "<color=#FFFFFF80>" + text + "</color>";
			}
			return Localization.instance.Localize("\n[<color=yellow><b>Alt + $KEY_Use</b></color>] ") + text;
		}

		internal static bool HandleInteract(Container chest, bool hold, bool alt, ref bool result)
		{
			if (hold || alt || !ZInput.GetKey((KeyCode)308, true) || !ZInput.GetButtonDown("Use"))
			{
				return false;
			}
			if (ChestRename.CanAccess(chest, flash: true))
			{
				Toggle(chest);
			}
			result = true;
			return true;
		}

		private static void Toggle(Container chest)
		{
			ZNetView val = StorageLocator.View(chest);
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !((Object)(object)val == (Object)null) && val.IsValid() && val.GetZDO() != null && !((Object)(object)ZNet.instance == (Object)null))
			{
				bool flag = !IsIncluded(chest);
				localPlayer.m_customData.Remove(ChestKey(val));
				localPlayer.m_customData.Remove(IncludedKey(val));
				localPlayer.m_customData[flag ? IncludedKey(val) : ChestKey(val)] = "1";
				string text = string.Format(ModText.Get(flag ? "ChestIncluded" : "ChestExcluded"), ModText.ModName);
				MessageHud instance = MessageHud.instance;
				if (instance != null)
				{
					instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
				}
				NearbyStorageDialog.RefreshSoon();
			}
		}
	}
	[HarmonyPatch]
	internal sealed class ChestRename : TextReceiver
	{
		private const int NameLimit = 60;

		private static readonly int NameKey = StringExtensionMethods.GetStableHashCode("Landoria.NearbyStorage.ChestName");

		private static readonly int AuthorKey = StringExtensionMethods.GetStableHashCode("Landoria.NearbyStorage.ChestNameAuthor");

		private static readonly MethodInfo CheckOpenAccess = AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null);

		private readonly Container _chest;

		private ChestRename(Container chest)
		{
			_chest = chest;
		}

		[HarmonyPatch(typeof(Container), "GetHoverText")]
		[HarmonyPostfix]
		private static void GetHoverText(Container __instance, ref string __result)
		{
			if (IsTarget(__instance))
			{
				string text = DisplayName(__instance);
				string text2 = Localization.instance.Localize(__instance.m_name);
				if (text.Length > 0 && __result.StartsWith(text2))
				{
					__result = text + __result.Substring(text2.Length);
				}
				if (CanAccess(__instance, flash: false))
				{
					__result += Localization.instance.Localize("\n[<color=yellow><b>$KEY_AltPlace + $KEY_Use</b></color>] $hud_rename");
					__result += ChestInclusion.HoverText(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Container), "GetHoverName")]
		[HarmonyPostfix]
		private static void GetHoverName(Container __instance, ref string __result)
		{
			if (IsTarget(__instance))
			{
				string text = DisplayName(__instance);
				if (text.Length > 0)
				{
					__result = text;
				}
			}
		}

		[HarmonyPatch(typeof(Container), "Interact")]
		[HarmonyPrefix]
		private static bool Interact(Container __instance, bool hold, bool alt, ref bool __result)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!IsTarget(__instance))
			{
				return true;
			}
			if (ChestInclusion.HandleInteract(__instance, hold, alt, ref __result))
			{
				return false;
			}
			if (hold || !alt)
			{
				return true;
			}
			if (!CanAccess(__instance, flash: true))
			{
				return true;
			}
			__result = true;
			if (!PrivilegeResultExtentions.IsGranted(PlatformManager.DistributionPlatform.PrivilegeProvider.CheckPrivilege((Privilege)2)))
			{
				ResolvePrivilegeUI resolvePrivilege = PlatformManager.DistributionPlatform.UIProvider.ResolvePrivilege;
				if (resolvePrivilege != null)
				{
					resolvePrivilege.Open((Privilege)2, (PrivilegeResult)64);
				}
				return false;
			}
			TextInput instance = TextInput.instance;
			if (instance != null)
			{
				instance.RequestText((TextReceiver)(object)new ChestRename(__instance), "$hud_rename", 60);
			}
			return false;
		}

		internal static bool IsTarget(Container chest)
		{
			string prefabName = Utils.GetPrefabName(((Component)chest).gameObject);
			switch (prefabName)
			{
			default:
				return prefabName == "piece_chest_barrel";
			case "piece_chest_wood":
			case "piece_chest":
			case "piece_chest_private":
				return true;
			}
		}

		internal static bool CanAccess(Container chest, bool flash)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (chest.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)chest).transform.position, 0f, flash, false))
			{
				return false;
			}
			Game instance = Game.instance;
			PlayerProfile val = ((instance != null) ? instance.GetPlayerProfile() : null);
			ZNetView val2 = StorageLocator.View(chest);
			if (val != null && (Object)(object)val2 != (Object)null && val2.IsValid() && CheckOpenAccess != null)
			{
				return (bool)CheckOpenAccess.Invoke(chest, new object[1] { val.GetPlayerID() });
			}
			return false;
		}

		private static string DisplayName(Container chest)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = (((Object)(object)chest.m_rootObjectOverride != (Object)null) ? ((Component)chest.m_rootObjectOverride).GetComponent<ZNetView>() : ((Component)chest).GetComponent<ZNetView>());
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return "";
			}
			ZDO zDO = val.GetZDO();
			string text = zDO.GetString(NameKey, "");
			if (text.Length == 0)
			{
				return "";
			}
			string text2 = zDO.GetString(AuthorKey, "host");
			PlatformUserID val2 = ((text2 == "host") ? default(PlatformUserID) : new PlatformUserID(text2));
			return CensorShittyWords.FilterUGC(text, (UGCType)4, val2, 0L, (GetUserProfileCompletedHandler)null);
		}

		internal static string ExplicitName(Container chest)
		{
			if (!IsTarget(chest))
			{
				return null;
			}
			string text = DisplayName(chest);
			string b = Localization.instance.Localize(chest.m_name);
			if (text.Length <= 0 || string.Equals(text, b, StringComparison.CurrentCultureIgnoreCase))
			{
				return null;
			}
			return text;
		}

		public string GetText()
		{
			ZNetView val = (((Object)(object)_chest == (Object)null) ? null : ((Component)_chest).GetComponent<ZNetView>());
			if (!((Object)(object)val != (Object)null) || !val.IsValid())
			{
				return "";
			}
			return val.GetZDO().GetString(NameKey, "");
		}

		public unsafe void SetText(string text)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_chest == (Object)null) && CanAccess(_chest, flash: true))
			{
				ZNetView component = ((Component)_chest).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid())
				{
					string text2 = StringExtensionMethods.RemoveRichTextTags(text).Replace('\r', ' ').Replace('\n', ' ')
						.Trim();
					PlatformUserID platformUserID = ((IUser)PlatformManager.DistributionPlatform.LocalUser).PlatformUserID;
					component.ClaimOwnership();
					component.GetZDO().Set(NameKey, text2);
					component.GetZDO().Set(AuthorKey, PlatformManager.DistributionPlatform.LocalUser.IsSignedIn ? ((object)(*(PlatformUserID*)(&platformUserID))/*cast due to .constrained prefix*/).ToString() : "host");
				}
			}
		}
	}
	internal static class NearbyStorageCatalog
	{
		internal static List<NearbyStorageItem> Read(Player player)
		{
			Dictionary<string, NearbyStorageItem> dictionary = new Dictionary<string, NearbyStorageItem>();
			foreach (Container item in StorageLocator.Nearby(player))
			{
				foreach (ItemData allItem in item.GetInventory().GetAllItems())
				{
					if (allItem != null && !((Object)(object)allItem.m_dropPrefab == (Object)null) && allItem.m_stack > 0)
					{
						string key = NearbyStorageItemKey.For(allItem, item);
						if (!dictionary.TryGetValue(key, out var value))
						{
							value = new NearbyStorageItem
							{
								Key = key,
								Sample = allItem,
								Name = Localization.instance.Localize(allItem.m_shared.m_name)
							};
							dictionary.Add(key, value);
						}
						else if (value.Sample.m_stack < value.Sample.m_shared.m_maxStackSize && allItem.m_stack >= allItem.m_shared.m_maxStackSize)
						{
							value.Sample = allItem;
						}
						value.Count += allItem.m_stack;
						AddSource(value, item, allItem);
					}
				}
			}
			return new List<NearbyStorageItem>(dictionary.Values);
		}

		private static void AddSource(NearbyStorageItem entry, Container chest, ItemData item)
		{
			foreach (NearbyStorageSource source in entry.Sources)
			{
				if (!((Object)(object)source.Chest != (Object)(object)chest))
				{
					source.Count += item.m_stack;
					return;
				}
			}
			entry.Sources.Add(new NearbyStorageSource
			{
				Chest = chest,
				Item = item,
				Count = item.m_stack
			});
		}
	}
	internal static class NearbyStorageCategory
	{
		private static readonly HashSet<string> PreparedFoods = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> FeastItems = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> FireCookingInputs = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> FireCookingOutputs = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> WoodItems = new HashSet<string>(StringComparer.Ordinal) { "Wood", "RoundLog", "FineWood", "ElderBark", "HardAntler", "Root", "WrithanRoots" };

		private static readonly HashSet<string> StoneItems = new HashSet<string>(StringComparer.Ordinal) { "Stone", "Flint", "StoneRock" };

		private static readonly HashSet<string> SeedItems = new HashSet<string>(StringComparer.Ordinal)
		{
			"CarrotSeeds", "TurnipSeeds", "OnionSeeds", "OatSeeds", "KaleSeeds", "PoteitrSeeds", "BeechSeeds", "BirchSeeds", "FirCone", "FirConeFrost",
			"PineCone", "Acorn", "AncientSeed", "Barley", "Flax", "VineGreenSeeds", "VineberrySeeds"
		};

		private static readonly HashSet<string> OreAndMetalItems = new HashSet<string>(StringComparer.Ordinal)
		{
			"CopperOre", "CopperScrap", "Copper", "TinOre", "Tin", "BronzeScrap", "Bronze", "IronOre", "IronScrap", "Iron",
			"SilverOre", "Silver", "BlackMetalScrap", "BlackMetal", "FlametalOre", "FlametalOreNew", "Flametal", "FlametalNew", "GoldOre", "Gold",
			"Chain", "BronzeNails", "IronNails", "Coal"
		};

		private static readonly HashSet<string> HidesAndFurs = new HashSet<string>(StringComparer.Ordinal) { "DeerHide", "WolfPelt", "LoxPelt", "SerpentScale", "TrollHide", "ScaleHide", "WolfHairBundle", "LeatherScraps", "BjornHide" };

		private static readonly HashSet<string> RawFoodMaterials = new HashSet<string>(StringComparer.Ordinal) { "Turnip", "BreadDough", "BarleyFlour", "OatFlour" };

		private static ObjectDB _cachedDb;

		private static ZNetScene _cachedScene;

		private static int _recipeCount;

		private static int _prefabCount;

		internal static int[] DisplayOrder()
		{
			int[] array = new int[ModText.CategoryCount + 1];
			array[0] = -1;
			int num = 1;
			for (int i = 0; i < ModText.CategoryCount; i++)
			{
				if (i != 12)
				{
					array[num++] = i;
				}
			}
			array[num] = 12;
			CompareInfo comparison = ModText.Comparison();
			Array.Sort(array, 1, ModText.CategoryCount - 1, Comparer<int>.Create((int left, int right) => comparison.Compare(Label(left), Label(right), CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace)));
			return array;
		}

		internal static string Label(int index)
		{
			if (index == -1)
			{
				return ModText.CategoryText("CategoryAll", ModText.SelectedLanguage);
			}
			return ModText.Category(index, ModText.SelectedLanguage);
		}

		internal static int For(ItemData item)
		{
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Invalid comparison between Unknown and I4
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Invalid comparison between Unknown and I4
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Expected I4, but got Unknown
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Invalid comparison between Unknown and I4
			if ((Object)(object)item.m_dropPrefab != (Object)null && RawFoodMaterials.Contains(((Object)item.m_dropPrefab).name))
			{
				return 14;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "Feaster")
			{
				return 2;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "HelmetDverger")
			{
				return 7;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name == "LinenThread" || ((Object)item.m_dropPrefab).name == "JuteBlue" || ((Object)item.m_dropPrefab).name == "JuteRed"))
			{
				return 24;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "SurtlingCore")
			{
				return 1;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name.StartsWith("MeadBase", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name == "BarleyWineBase"))
			{
				return 3;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && WoodItems.Contains(((Object)item.m_dropPrefab).name))
			{
				return 17;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && StoneItems.Contains(((Object)item.m_dropPrefab).name))
			{
				return 19;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && SeedItems.Contains(((Object)item.m_dropPrefab).name))
			{
				return 21;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && OreAndMetalItems.Contains(((Object)item.m_dropPrefab).name))
			{
				return 22;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && HidesAndFurs.Contains(((Object)item.m_dropPrefab).name))
			{
				return 18;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name.StartsWith("FishingBait", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name == "FishingRod"))
			{
				return 10;
			}
			if ((int)item.m_shared.m_itemType == 21)
			{
				return 10;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name.StartsWith("FireworksRocket_", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name == "Sparkler"))
			{
				return 20;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name.StartsWith("Bomb", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name == "BlobVial"))
			{
				return 23;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && (((Object)item.m_dropPrefab).name.StartsWith("Arrow", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name.StartsWith("Bolt", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name.StartsWith("TurretBolt", StringComparison.Ordinal) || ((Object)item.m_dropPrefab).name.StartsWith("Snowball", StringComparison.Ordinal)))
			{
				return 9;
			}
			if (item.m_shared.m_value > 0)
			{
				return 1;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null)
			{
				RefreshCategorySources();
				if (FeastItems.Contains(((Object)item.m_dropPrefab).name))
				{
					return 15;
				}
				if (FireCookingInputs.Contains(((Object)item.m_dropPrefab).name))
				{
					return 13;
				}
				if (FireCookingOutputs.Contains(((Object)item.m_dropPrefab).name))
				{
					return 16;
				}
				if (((Object)item.m_dropPrefab).name == "ScytheHandle" || ((Object)item.m_dropPrefab).name == "SharpeningStone")
				{
					return 8;
				}
			}
			if ((int)item.m_shared.m_skillType == 12)
			{
				return 8;
			}
			ItemType itemType = item.m_shared.m_itemType;
			switch (itemType - 1)
			{
			case 0:
				return 0;
			case 1:
				if (item.m_shared.m_isDrink)
				{
					return 3;
				}
				RefreshCategorySources();
				if (!((Object)(object)item.m_dropPrefab != (Object)null) || !PreparedFoods.Contains(((Object)item.m_dropPrefab).name))
				{
					return 14;
				}
				return 2;
			case 2:
				if ((int)item.m_shared.m_skillType != 7)
				{
					return 4;
				}
				return 8;
			case 3:
			case 13:
			case 21:
				return 4;
			case 4:
				return 5;
			case 5:
			case 6:
			case 10:
			case 11:
			case 16:
				if (!Mathf.Approximately(item.GetArmor(), 1f))
				{
					return 6;
				}
				return 24;
			case 17:
			case 23:
				return 7;
			case 14:
			case 18:
				return 8;
			case 8:
			case 22:
				return 9;
			case 12:
				return 11;
			default:
				return 12;
			}
		}

		private static void RefreshCategorySources()
		{
			ObjectDB instance = ObjectDB.instance;
			ZNetScene instance2 = ZNetScene.instance;
			int valueOrDefault = (instance?.m_recipes?.Count).GetValueOrDefault();
			int valueOrDefault2 = (instance2?.m_prefabs?.Count).GetValueOrDefault();
			if (!((Object)(object)instance == (Object)(object)_cachedDb) || !((Object)(object)instance2 == (Object)(object)_cachedScene) || valueOrDefault != _recipeCount || valueOrDefault2 != _prefabCount)
			{
				_cachedDb = instance;
				_cachedScene = instance2;
				_recipeCount = valueOrDefault;
				_prefabCount = valueOrDefault2;
				PreparedFoods.Clear();
				FeastItems.Clear();
				FireCookingInputs.Clear();
				FireCookingOutputs.Clear();
				AddRecipeOutputs(instance);
				AddCookingStationItems(instance2);
				AddFeastItems(instance2);
			}
		}

		private static void AddRecipeOutputs(ObjectDB db)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			if ((Object)(object)db == (Object)null)
			{
				return;
			}
			foreach (Recipe recipe in db.m_recipes)
			{
				ItemDrop val = recipe?.m_item;
				if (!((Object)(object)val == (Object)null) && (int)val.m_itemData.m_shared.m_itemType == 2)
				{
					PreparedFoods.Add(((Object)((Component)val).gameObject).name);
				}
			}
		}

		private static void AddCookingStationItems(ZNetScene scene)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Invalid comparison between Unknown and I4
			if ((Object)(object)scene == (Object)null)
			{
				return;
			}
			foreach (GameObject prefab in scene.m_prefabs)
			{
				CookingStation val = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<CookingStation>());
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				foreach (ItemConversion item in val.m_conversion)
				{
					ItemDrop val2 = item?.m_from;
					ItemDrop val3 = item?.m_to;
					if (val.m_requireFire && (Object)(object)val2 != (Object)null)
					{
						FireCookingInputs.Add(((Object)((Component)val2).gameObject).name);
						if ((Object)(object)val3 != (Object)null)
						{
							FireCookingOutputs.Add(((Object)((Component)val3).gameObject).name);
						}
					}
					if ((Object)(object)val3 != (Object)null && (int)val3.m_itemData.m_shared.m_itemType == 2)
					{
						PreparedFoods.Add(((Object)((Component)val3).gameObject).name);
					}
				}
			}
		}

		private static void AddFeastItems(ZNetScene scene)
		{
			if ((Object)(object)scene == (Object)null)
			{
				return;
			}
			foreach (GameObject prefab in scene.m_prefabs)
			{
				Feast val = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<Feast>());
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				ItemDrop val2 = val.m_foodItem ?? prefab.GetComponent<ItemDrop>();
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				FeastItems.Add(((Object)((Component)val2).gameObject).name);
				Piece component = prefab.GetComponent<Piece>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				Requirement[] resources = component.m_resources;
				for (int i = 0; i < resources.Length; i++)
				{
					ItemDrop val3 = resources[i]?.m_resItem;
					if ((Object)(object)val3 != (Object)null && val3.m_itemData.m_shared.m_name == val2.m_itemData.m_shared.m_name)
					{
						FeastItems.Add(((Object)((Component)val3).gameObject).name);
					}
				}
			}
		}
	}
	internal static class NearbyStorageCategoryFamily
	{
		private static readonly int[] ByCategory = new int[25]
		{
			1, 4, 2, 2, 0, 0, 0, 0, 0, 3,
			3, 4, 4, 2, 2, 2, 2, 1, 1, 1,
			3, 1, 1, 3, 0
		};

		private static readonly string[] FamilyKeys = new string[5] { "FamilyEquipment", "FamilyResources", "FamilyFoodAndDrinks", "FamilyCombatAndActivities", "FamilySpecialItems" };

		internal static int Count => FamilyKeys.Length;

		internal static string Label(int family)
		{
			return ModText.CategoryText(FamilyKeys[family], ModText.SelectedLanguage);
		}

		internal static string Label(int family, string language)
		{
			return ModText.CategoryText(FamilyKeys[family], language);
		}

		internal static string Aliases(int family, string language)
		{
			return ModText.Aliases(FamilyKeys[family], language);
		}

		internal static int For(int category)
		{
			return ByCategory[category];
		}

		internal static IEnumerable<string> Names(int category)
		{
			int num = For(category);
			string key = FamilyKeys[num];
			yield return ModText.CategoryText(key, ModText.SelectedLanguage);
			yield return ModText.CategoryText(key, "English");
			yield return ModText.CategoryText(key, "French");
		}
	}
	internal static class NearbyStorageDeposit
	{
		private static readonly HashSet<Container> Expired = new HashSet<Container>();

		private static Container _pending;

		private static ItemData _item;

		private static Player _player;

		private static Container _sourceChest;

		private static Vector2i _sourcePosition;

		private static string _sourceKey;

		private static int _remaining;

		private static int _moved;

		private static bool _autoDeposit;

		private static bool _distributeDeposit;

		private static bool _targetedDeposit;

		internal static bool Running { get; private set; }

		internal static bool TryStartAuto(ItemData item)
		{
			Player localPlayer = Player.m_localPlayer;
			if (Running || (Object)(object)localPlayer == (Object)null || (Object)(object)item?.m_dropPrefab == (Object)null || !((Humanoid)localPlayer).GetInventory().ContainsItem(item))
			{
				return false;
			}
			if (Plugin.Instance.Settings.AutomaticItemDistribution.Value)
			{
				return TryStartDistributed(item, item.m_stack, null, clearDrag: false);
			}
			List<Container> list = MatchingChests(item, localPlayer);
			bool flag = list.Count > 0;
			list.RemoveAll((Container chest) => Capacity(chest.GetInventory(), item) < item.m_stack);
			if (list.Count != 1)
			{
				ShowAutoError((list.Count == 0 && flag) ? 1 : list.Count);
				return false;
			}
			NearbyStorageDialog.FocusInventoryItem(item);
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Run(item, localPlayer, item.m_stack, list, null, autoDeposit: true, targetedDeposit: false));
			return true;
		}

		internal static bool TryStartDistributed(ItemData item, int amount, Container source, bool clearDrag)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!Running && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)item?.m_dropPrefab == (Object)null) && amount > 0)
			{
				Plugin instance = Plugin.Instance;
				if (instance != null && instance.Settings?.AutomaticItemDistribution.Value == true && (((Object)(object)source == (Object)null) ? ((Humanoid)localPlayer).GetInventory() : source.GetInventory()).ContainsItem(item))
				{
					List<Container> list = NearbyStorageDistribution.Candidates(item, localPlayer, source);
					if (list.Count == 0)
					{
						ShowAutoError(1);
						return false;
					}
					if (clearDrag && (Object)(object)source != (Object)null && !NearbyStorageTransfer.CancelNearbyDrag())
					{
						return false;
					}
					if (clearDrag && (Object)(object)source == (Object)null)
					{
						NearbyStorageTransfer.ClearPlayerDrag();
					}
					if ((Object)(object)source == (Object)null)
					{
						NearbyStorageDialog.FocusInventoryItem(item);
					}
					((MonoBehaviour)Plugin.Instance).StartCoroutine(Run(item, localPlayer, amount, list, source, autoDeposit: true, targetedDeposit: false, distributeDeposit: true));
					return true;
				}
			}
			return false;
		}

		internal static bool TryStart(ItemData item, int amount, bool clearDrag, NearbyStorageItem target)
		{
			Player localPlayer = Player.m_localPlayer;
			if (Running || (Object)(object)localPlayer == (Object)null || (Object)(object)item?.m_dropPrefab == (Object)null || amount <= 0 || !((Humanoid)localPlayer).GetInventory().ContainsItem(item))
			{
				return false;
			}
			if (!TargetHasRoom(target, item, amount, localPlayer, null))
			{
				return false;
			}
			NearbyStorageDialog.FocusInventoryItem(item);
			List<Container> list = Candidates(item, amount, localPlayer, target, null);
			if (list.Count == 0)
			{
				return false;
			}
			if (clearDrag)
			{
				NearbyStorageTransfer.ClearPlayerDrag();
			}
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Run(item, localPlayer, amount, list, null, autoDeposit: false, targetedDeposit: true));
			return true;
		}

		internal static bool TryMove(Container source, ItemData item, int amount, NearbyStorageItem target)
		{
			Player localPlayer = Player.m_localPlayer;
			if (Running || (Object)(object)localPlayer == (Object)null || (Object)(object)source == (Object)null || (Object)(object)item?.m_dropPrefab == (Object)null || amount <= 0 || !source.GetInventory().ContainsItem(item) || !StorageLocator.Eligible(source, localPlayer, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value))
			{
				return false;
			}
			if (!TargetHasRoom(target, item, amount, localPlayer, source))
			{
				return false;
			}
			List<Container> list = Candidates(item, amount, localPlayer, target, source);
			if (list.Count == 0 || !NearbyStorageTransfer.CancelNearbyDrag())
			{
				return false;
			}
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Run(item, localPlayer, amount, list, source, autoDeposit: false, targetedDeposit: true));
			return true;
		}

		private static bool TargetHasRoom(NearbyStorageItem target, ItemData item, int amount, Player player, Container source)
		{
			if (target == null)
			{
				return false;
			}
			if ((Object)(object)TargetChest(target, item, amount, player, source) != (Object)null)
			{
				return true;
			}
			ShowAutoError(1);
			return false;
		}

		private static Container TargetChest(NearbyStorageItem target, ItemData item, int amount, Player player, Container source)
		{
			foreach (NearbyStorageSource source2 in target.Sources)
			{
				Container chest = source2.Chest;
				if (!((Object)(object)chest == (Object)null) && !((Object)(object)chest == (Object)(object)source) && StorageLocator.Eligible(chest, player, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value) && Capacity(chest.GetInventory(), item) >= Mathf.Min(amount, item.m_stack))
				{
					return chest;
				}
			}
			return null;
		}

		private static List<Container> MatchingChests(ItemData item, Player player)
		{
			List<Container> list = new List<Container>();
			string text = NearbyStorageItemKey.For(item);
			foreach (Container item2 in StorageLocator.Nearby(player))
			{
				foreach (ItemData allItem in item2.GetInventory().GetAllItems())
				{
					if (allItem != null && allItem.m_stack > 0 && !(NearbyStorageItemKey.For(allItem) != text))
					{
						list.Add(item2);
						break;
					}
				}
			}
			return list;
		}

		private static void ShowAutoError(int matches)
		{
			string text = ModText.Error((matches < 0) ? "DepositUnavailable" : ((matches == 0) ? "DepositNoContainer" : ((matches > 1) ? "DepositMultipleContainers" : "DepositFull")));
			MessageHud instance = MessageHud.instance;
			if (instance != null)
			{
				instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
			}
		}

		private static List<Container> Candidates(ItemData item, int amount, Player player, NearbyStorageItem target, Container source)
		{
			List<Container> list = new List<Container>();
			if (target == null || target.Sources.Count == 0)
			{
				return list;
			}
			Container val = TargetChest(target, item, amount, player, source);
			foreach (Container item2 in StorageLocator.Nearby(player))
			{
				if ((Object)(object)item2 == (Object)(object)val && (Object)(object)item2 != (Object)(object)source && Capacity(item2.GetInventory(), item) > 0)
				{
					list.Add(item2);
					break;
				}
			}
			return list;
		}

		private static IEnumerator Run(ItemData item, Player player, int amount, List<Container> chests, Container source, bool autoDeposit, bool targetedDeposit, bool distributeDeposit = false)
		{
			Running = true;
			_autoDeposit = autoDeposit;
			_distributeDeposit = distributeDeposit;
			_targetedDeposit = targetedDeposit;
			_item = item;
			_player = player;
			_sourceChest = source;
			_sourcePosition = item.m_gridPos;
			_sourceKey = (((Object)(object)source == (Object)null) ? null : NearbyStorageItemKey.ForStored(item, source));
			_remaining = Mathf.Min(amount, item.m_stack);
			_moved = 0;
			try
			{
				foreach (Container chest in chests)
				{
					if (_remaining <= 0 || SourceItem() == null)
					{
						break;
					}
					if (StorageLocator.Eligible(chest, player, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value))
					{
						yield return RequestChest(chest);
					}
				}
			}
			finally
			{
				if (_distributeDeposit && _remaining > 0)
				{
					ShowAutoError(1);
				}
				else if (_autoDeposit && _moved == 0)
				{
					ShowAutoError(-1);
				}
				if (_moved > 0 && (Object)(object)source == (Object)null)
				{
					NearbyStorageDialog.FocusInventoryItem(item);
				}
				_pending = null;
				_item = null;
				_player = null;
				_sourceChest = null;
				_sourceKey = null;
				_remaining = 0;
				_autoDeposit = false;
				_distributeDeposit = false;
				_targetedDeposit = false;
				Running = false;
			}
		}

		private static IEnumerator RequestChest(Container chest)
		{
			_pending = chest;
			chest.StackAll();
			float deadline = Time.realtimeSinceStartup + 10f;
			while ((Object)(object)_pending == (Object)(object)chest && Time.realtimeSinceStartup < deadline)
			{
				yield return (object)new WaitForSecondsRealtime(0.1f);
			}
			if ((Object)(object)_pending == (Object)(object)chest)
			{
				Expired.Add(chest);
				_pending = null;
			}
		}

		internal static bool AllowResponse(Container chest, bool granted)
		{
			if (Expired.Remove(chest))
			{
				return false;
			}
			if (!Running || (Object)(object)chest != (Object)(object)_pending)
			{
				return true;
			}
			_pending = null;
			if (granted)
			{
				try
				{
					Store(chest);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Nearby Storage deposit failed: " + ex));
				}
			}
			return false;
		}

		private static ItemData SourceItem()
		{
			if ((Object)(object)_sourceChest == (Object)null)
			{
				if (!((Humanoid)_player).GetInventory().ContainsItem(_item))
				{
					return null;
				}
				return _item;
			}
			ItemData itemAt = _sourceChest.GetInventory().GetItemAt(_sourcePosition.x, _sourcePosition.y);
			if (itemAt == null || !(NearbyStorageItemKey.ForStored(itemAt, _sourceChest) == _sourceKey))
			{
				return null;
			}
			return itemAt;
		}

		private static void Store(Container chest)
		{
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sourceChest != (Object)null && !StorageLocator.TryClaimAndLoad(_sourceChest, _player))
			{
				return;
			}
			Inventory val = (((Object)(object)_sourceChest == (Object)null) ? ((Humanoid)_player).GetInventory() : _sourceChest.GetInventory());
			ItemData val2 = SourceItem();
			if (val2 == null || _remaining <= 0)
			{
				return;
			}
			Inventory inventory = chest.GetInventory();
			if (_autoDeposit && !_distributeDeposit && !CanAutoDeposit(val2, chest, inventory))
			{
				return;
			}
			if (_targetedDeposit && Capacity(inventory, val2) < _remaining)
			{
				ShowAutoError(1);
				return;
			}
			int num = Mathf.Min(new int[3]
			{
				_remaining,
				val2.m_stack,
				Capacity(inventory, val2)
			});
			if (num <= 0)
			{
				return;
			}
			ItemData val3 = val2.Clone();
			val3.m_stack = num;
			val3.m_equipped = false;
			int num2 = inventory.NrOfItemsIncludingStacks();
			inventory.AddItem(val3);
			int num3 = inventory.NrOfItemsIncludingStacks() - num2;
			if (num3 > 0)
			{
				if ((Object)(object)_sourceChest == (Object)null && num3 == val2.m_stack && ((Humanoid)_player).IsItemEquiped(val2))
				{
					((Humanoid)_player).RemoveEquipAction(val2);
					((Humanoid)_player).UnequipItem(val2, true);
				}
				val.RemoveItem(val2, num3);
				_remaining -= num3;
				_moved += num3;
				if ((Object)(object)_sourceChest == (Object)null)
				{
					NearbyStorageDialog.ShowDeposit(val2, num3, chest);
				}
				InventoryGui instance = InventoryGui.instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.m_moveItemEffects.Create(((Component)instance).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
				NearbyStorageDialog.RefreshSoon();
			}
		}

		private static bool CanAutoDeposit(ItemData item, Container chest, Inventory destination)
		{
			List<Container> list = MatchingChests(item, _player);
			list.RemoveAll((Container candidate) => Capacity(candidate.GetInventory(), item) < _remaining);
			if (list.Count == 1 && (Object)(object)list[0] == (Object)(object)chest)
			{
				return Capacity(destination, item) >= _remaining;
			}
			return false;
		}

		internal static int Capacity(Inventory inventory, ItemData item)
		{
			int num = inventory.GetEmptySlots() * item.m_shared.m_maxStackSize;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem.m_shared.m_name == item.m_shared.m_name && allItem.m_quality == item.m_quality && allItem.m_worldLevel == item.m_worldLevel)
				{
					num += Mathf.Max(0, allItem.m_shared.m_maxStackSize - allItem.m_stack);
				}
			}
			return num;
		}

		internal static void Reset()
		{
			_pending = null;
			_item = null;
			_player = null;
			_sourceChest = null;
			_sourceKey = null;
			_remaining = 0;
			_moved = 0;
			_autoDeposit = false;
			_distributeDeposit = false;
			_targetedDeposit = false;
			Expired.Clear();
			Running = false;
		}
	}
	internal static class NearbyStorageDistribution
	{
		internal static List<Container> Candidates(ItemData item, Player player, Container source = null)
		{
			List<Container> list = StorageLocator.Nearby(player);
			string name = ((Object)item.m_dropPrefab).name;
			int category = NearbyStorageCategory.For(item);
			int family = NearbyStorageCategoryFamily.For(category);
			HashSet<string> categoryWords = CategoryWords(category);
			HashSet<string> categoryWords2 = FamilyWords(family);
			Dictionary<Container, int> scores = new Dictionary<Container, int>();
			Dictionary<Container, int> familyScores = new Dictionary<Container, int>();
			Dictionary<Container, int> tiers = new Dictionary<Container, int>();
			foreach (Container item2 in list)
			{
				if (!((Object)(object)item2 == (Object)(object)source) && NearbyStorageDeposit.Capacity(item2.GetInventory(), item) > 0)
				{
					int num = CategoryCount(item2, category);
					int num2 = FamilyCount(item2, family);
					bool flag = ContainsItem(item2, name);
					bool flag2 = NameMatches(item2, categoryWords);
					bool flag3 = NameMatches(item2, categoryWords2);
					bool flag4 = item2.GetInventory().NrOfItems() == 0;
					tiers[item2] = ((!flag) ? (flag2 ? 1 : (flag3 ? 2 : ((num > 0) ? 3 : ((num2 > 0) ? 4 : (flag4 ? 5 : 6))))) : 0);
					scores[item2] = num;
					familyScores[item2] = num2;
				}
			}
			list.RemoveAll((Container chest) => !tiers.ContainsKey(chest));
			list.Sort((Container left, Container right) => Compare(left, right, tiers, scores, familyScores, player));
			return list;
		}

		private static HashSet<string> CategoryWords(int category)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] array = new string[2]
			{
				ModText.SelectedLanguage,
				"English"
			};
			foreach (string language in array)
			{
				hashSet.UnionWith(Words(ModText.Category(category, language)));
				AddAliases(hashSet, ModText.CategoryAliases(category, language));
			}
			return hashSet;
		}

		private static HashSet<string> FamilyWords(int family)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] array = new string[2]
			{
				ModText.SelectedLanguage,
				"English"
			};
			foreach (string language in array)
			{
				hashSet.UnionWith(Words(NearbyStorageCategoryFamily.Label(family, language)));
				AddAliases(hashSet, NearbyStorageCategoryFamily.Aliases(family, language));
			}
			return hashSet;
		}

		private static void AddAliases(HashSet<string> words, string aliases)
		{
			string[] array = aliases.Split(new char[1] { '|' });
			foreach (string value in array)
			{
				words.UnionWith(Words(value));
			}
		}

		private static int Compare(Container left, Container right, Dictionary<Container, int> tiers, Dictionary<Container, int> scores, Dictionary<Container, int> familyScores, Player player)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			int num = tiers[left].CompareTo(tiers[right]);
			if (num != 0)
			{
				return num;
			}
			if (num == 3 || num == 4)
			{
				Dictionary<Container, int> dictionary = ((num == 3) ? scores : familyScores);
				int num2 = dictionary[right].CompareTo(dictionary[left]);
				if (num2 != 0)
				{
					return num2;
				}
			}
			Vector3 val = ((Component)left).transform.position - ((Component)player).transform.position;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			val = ((Component)right).transform.position - ((Component)player).transform.position;
			float sqrMagnitude2 = ((Vector3)(ref val)).sqrMagnitude;
			return sqrMagnitude.CompareTo(sqrMagnitude2);
		}

		private static int CategoryCount(Container chest, int category)
		{
			int num = 0;
			foreach (ItemData allItem in chest.GetInventory().GetAllItems())
			{
				if (allItem != null && allItem.m_stack > 0 && NearbyStorageCategory.For(allItem) == category)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static int FamilyCount(Container chest, int family)
		{
			int num = 0;
			foreach (ItemData allItem in chest.GetInventory().GetAllItems())
			{
				if (allItem != null && allItem.m_stack > 0 && NearbyStorageCategoryFamily.For(NearbyStorageCategory.For(allItem)) == family)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static bool ContainsItem(Container chest, string itemName)
		{
			foreach (ItemData allItem in chest.GetInventory().GetAllItems())
			{
				if (allItem != null && allItem.m_stack > 0 && (Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == itemName)
				{
					return true;
				}
			}
			return false;
		}

		private static bool NameMatches(Container chest, HashSet<string> categoryWords)
		{
			string text = ChestRename.ExplicitName(chest);
			if (text == null)
			{
				return false;
			}
			foreach (string item in Words(text))
			{
				if (categoryWords.Contains(item))
				{
					return true;
				}
			}
			return false;
		}

		private static IEnumerable<string> Words(string value)
		{
			StringBuilder word = new StringBuilder();
			string text = value.Normalize(NormalizationForm.FormD);
			foreach (char c in text)
			{
				if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
				{
					continue;
				}
				if (char.IsLetter(c))
				{
					word.Append(char.ToUpperInvariant(c));
					continue;
				}
				if (IsMeaningfulWord(word))
				{
					yield return word.ToString();
				}
				word.Clear();
			}
			if (IsMeaningfulWord(word))
			{
				yield return word.ToString();
			}
		}

		private static bool IsMeaningfulWord(StringBuilder word)
		{
			if (word.Length <= 3)
			{
				if (word.Length >= 2)
				{
					return CharUnicodeInfo.GetUnicodeCategory(word[0]) == UnicodeCategory.OtherLetter;
				}
				return false;
			}
			return true;
		}
	}
	internal sealed class NearbyStorageItem
	{
		internal string Key;

		internal string Name;

		internal ItemData Sample;

		internal int Count;

		internal readonly List<NearbyStorageSource> Sources = new List<NearbyStorageSource>();
	}
	internal static class NearbyStorageItemKey
	{
		internal static string For(ItemData item)
		{
			if (!((Object)(object)item?.m_dropPrefab == (Object)null))
			{
				return ((Object)item.m_dropPrefab).name + "|" + item.m_quality;
			}
			return null;
		}

		internal static string For(ItemData item, Container chest)
		{
			string text = For(item);
			if (text == null)
			{
				return null;
			}
			bool flag = Plugin.Instance?.Settings?.SeparateStacksByContainer.Value ?? true;
			if (item.m_shared.m_maxStackSize > 1 && !flag)
			{
				return text;
			}
			return ForStored(item, chest);
		}

		internal static string ForStored(ItemData item, Container chest)
		{
			string text = For(item);
			if (text == null)
			{
				return null;
			}
			text = text + "|" + ((Object)chest).GetInstanceID();
			if (item.m_shared.m_maxStackSize <= 1)
			{
				return text + "|" + item.m_gridPos.x + "," + item.m_gridPos.y;
			}
			return text;
		}
	}
	internal static class NearbyStorageSort
	{
		internal static int ClosestIndex(List<NearbyStorageItem> items, string name)
		{
			if (items.Count == 0)
			{
				return -1;
			}
			HashSet<string> hashSet = new HashSet<string>(Words(name));
			int result = 0;
			int num = -1;
			for (int i = 0; i < items.Count; i++)
			{
				int num2 = 0;
				foreach (string item in Words(items[i].Name))
				{
					if (hashSet.Contains(item))
					{
						num2 += 100;
					}
				}
				int j;
				for (j = 0; j < name.Length && j < items[i].Name.Length && char.ToLowerInvariant(name[j]) == char.ToLowerInvariant(items[i].Name[j]); j++)
				{
				}
				num2 += j;
				if (num2 > num)
				{
					num = num2;
					result = i;
				}
			}
			if (num <= 0)
			{
				return -1;
			}
			return result;
		}

		internal static void Sort(List<NearbyStorageItem> items)
		{
			CompareInfo comparison = ModText.Comparison();
			items.Sort((NearbyStorageItem a, NearbyStorageItem b) => Compare(a, b, comparison));
		}

		private static int Compare(NearbyStorageItem a, NearbyStorageItem b, CompareInfo comparison)
		{
			if (a.Key == b.Key)
			{
				return 0;
			}
			int num = comparison.Compare(a.Name, b.Name, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace);
			if (num == 0)
			{
				return string.CompareOrdinal(a.Key, b.Key);
			}
			return num;
		}

		private static IEnumerable<string> Words(string name)
		{
			StringBuilder word = new StringBuilder();
			HashSet<string> seen = new HashSet<string>();
			foreach (char c in name)
			{
				if (char.IsLetterOrDigit(c))
				{
					word.Append(char.ToLowerInvariant(c));
					continue;
				}
				string text = Normalize(word.ToString());
				if (text.Length >= 4 && seen.Add(text))
				{
					yield return text;
				}
				word.Clear();
			}
			string text2 = Normalize(word.ToString());
			if (text2.Length >= 4 && seen.Add(text2))
			{
				yield return text2;
			}
		}

		private static string Normalize(string word)
		{
			if (word.Length <= 4 || !word.EndsWith("s", StringComparison.Ordinal))
			{
				return word;
			}
			return word.Substring(0, word.Length - 1);
		}
	}
	internal sealed class NearbyStorageSource
	{
		internal Container Chest;

		internal ItemData Item;

		internal int Count;
	}
	internal static class NearbyStorageTransfer
	{
		private static readonly MethodInfo SetupDrag = AccessTools.Method(typeof(InventoryGui), "SetupDragItem", new Type[3]
		{
			typeof(ItemData),
			typeof(Inventory),
			typeof(int)
		}, (Type[])null);

		private static readonly MethodInfo ShowSplit = AccessTools.Method(typeof(InventoryGui), "ShowSplitDialog", new Type[2]
		{
			typeof(ItemData),
			typeof(Inventory)
		}, (Type[])null);

		private static readonly FieldInfo DragItem = AccessTools.Field(typeof(InventoryGui), "m_dragItem");

		private static readonly FieldInfo DragAmount = AccessTools.Field(typeof(InventoryGui), "m_dragAmount");

		private static readonly FieldInfo DragInventory = AccessTools.Field(typeof(InventoryGui), "m_dragInventory");

		private static Inventory _trackedInventory;

		private static ItemData _trackedItem;

		private static Container _trackedChest;

		internal static string DraggedPlayerItemKey()
		{
			return NearbyStorageItemKey.For(DraggedPlayerItem());
		}

		internal static ItemData DraggedPlayerItem()
		{
			InventoryGui instance = InventoryGui.instance;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)instance == (Object)null || (Object)(object)localPlayer == (Object)null || (object)/*isinst with value type is only supported in some contexts*/ != ((Humanoid)localPlayer).GetInventory())
			{
				return null;
			}
			object? obj = DragItem?.GetValue(instance);
			return (ItemData)((obj is ItemData) ? obj : null);
		}

		internal static string DraggedNearbyItemKey()
		{
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance == (Object)null || _trackedItem == null || (Object)(object)_trackedChest == (Object)null || DragItem?.GetValue(instance) != _trackedItem || DragInventory?.GetValue(instance) != _trackedInventory)
			{
				return null;
			}
			return NearbyStorageItemKey.For(_trackedItem, _trackedChest);
		}

		internal static bool CancelNearbyDrag()
		{
			if (DraggedNearbyItemKey() == null || SetupDrag == null)
			{
				return false;
			}
			SetupDrag.Invoke(InventoryGui.instance, new object[3] { null, null, 1 });
			_trackedInventory = null;
			_trackedItem = null;
			_trackedChest = null;
			NearbyStorageDialog.RefreshSoon();
			return true;
		}

		internal static bool TryDropInPanel(NearbyStorageItem target)
		{
			Player localPlayer = Player.m_localPlayer;
			InventoryGui instance = InventoryGui.instance;
			if ((target != null && target.Sources.Count == 0) || (Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null || ((Character)localPlayer).IsTeleporting() || NearbyStorageDeposit.Running || (Object)(object)Plugin.Instance == (Object)null || SetupDrag == null)
			{
				return false;
			}
			object? obj = DragItem?.GetValue(instance);
			ItemData val = (ItemData)((obj is ItemData) ? obj : null);
			object? obj2 = DragInventory?.GetValue(instance);
			Inventory val2 = (Inventory)((obj2 is Inventory) ? obj2 : null);
			if ((Object)(object)val?.m_dropPrefab == (Object)null || val2 == null || !val2.ContainsItem(val))
			{
				return false;
			}
			int amount = (int)(DragAmount?.GetValue(instance) ?? ((object)val.m_stack));
			if (target == null)
			{
				if (val2 != ((Humanoid)localPlayer).GetInventory() && !IsTracked(val2, val))
				{
					return false;
				}
				return NearbyStorageDeposit.TryStartDistributed(val, amount, (val2 == ((Humanoid)localPlayer).GetInventory()) ? null : _trackedChest, clearDrag: true);
			}
			if (val2 == ((Humanoid)localPlayer).GetInventory())
			{
				return NearbyStorageDeposit.TryStart(val, amount, clearDrag: true, target);
			}
			if (!IsTracked(val2, val))
			{
				return false;
			}
			return NearbyStorageDeposit.TryMove(_trackedChest, val, amount, target);
		}

		internal static void ClearPlayerDrag()
		{
			SetupDrag?.Invoke(InventoryGui.instance, new object[3] { null, null, 1 });
		}

		internal static bool IsTracked(Inventory inventory, ItemData item)
		{
			if (inventory != null && inventory == _trackedInventory && item != null && item == _trackedItem && (Object)(object)_trackedChest != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)Plugin.Instance != (Object)null)
			{
				return StorageLocator.Eligible(_trackedChest, Player.m_localPlayer, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value);
			}
			return false;
		}

		internal static bool UseConsumable(NearbyStorageItem entry)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			Player localPlayer = Player.m_localPlayer;
			if (entry == null || (int)(entry.Sample?.m_shared?.m_itemType).GetValueOrDefault() != 2 || (Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting() || NearbyStorageDeposit.Running)
			{
				return false;
			}
			foreach (NearbyStorageSource source in entry.Sources)
			{
				if (!((Object)(object)source.Chest == (Object)null) && StorageLocator.TryClaimAndLoad(source.Chest, localPlayer))
				{
					Inventory inventory = source.Chest.GetInventory();
					ItemData val = FindStack(inventory, source.Chest, entry.Key, fullOnly: false);
					if (val != null)
					{
						((Humanoid)localPlayer).UseItem(inventory, val, true);
						NearbyStorageDialog.RefreshSoon();
						return true;
					}
				}
			}
			return false;
		}

		internal static void Select(NearbyStorageItem entry)
		{
			Player localPlayer = Player.m_localPlayer;
			InventoryGui instance = InventoryGui.instance;
			if (entry != null && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)instance == (Object)null) && !((Character)localPlayer).IsTeleporting() && DragItem?.GetValue(instance) == null && !SelectStack(entry, localPlayer, instance, fullOnly: true))
			{
				SelectStack(entry, localPlayer, instance, fullOnly: false);
			}
		}

		private static bool SelectStack(NearbyStorageItem entry, Player player, InventoryGui gui, bool fullOnly)
		{
			foreach (NearbyStorageSource source in entry.Sources)
			{
				if (!((Object)(object)source.Chest == (Object)null) && FindStack(source.Chest.GetInventory(), source.Chest, entry.Key, fullOnly) != null && StorageLocator.TryClaimAndLoad(source.Chest, player))
				{
					Inventory inventory = source.Chest.GetInventory();
					ItemData val = FindStack(inventory, source.Chest, entry.Key, fullOnly);
					if (val != null)
					{
						Act(gui, player, source.Chest, inventory, val);
						NearbyStorageDialog.RefreshSoon();
						return true;
					}
				}
			}
			return false;
		}

		private static ItemData FindStack(Inventory inventory, Container chest, string key, bool fullOnly)
		{
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (NearbyStorageItemKey.For(allItem, chest) == key && allItem.m_stack > 0 && (!fullOnly || allItem.m_stack >= allItem.m_shared.m_maxStackSize))
				{
					return allItem;
				}
			}
			return null;
		}

		private static void Act(InventoryGui gui, Player player, Container chest, Inventory inventory, ItemData item)
		{
			bool num = ZInput.GetKey((KeyCode)304, true) || ZInput.GetKey((KeyCode)303, true);
			bool flag = ZInput.GetKey((KeyCode)306, true) || ZInput.GetKey((KeyCode)305, true);
			if (num)
			{
				if (item.m_stack > 1)
				{
					_trackedInventory = inventory;
					_trackedItem = item;
					_trackedChest = chest;
					ShowSplit?.Invoke(gui, new object[2] { item, inventory });
				}
			}
			else if (flag)
			{
				if (!item.m_shared.m_questItem)
				{
					((Humanoid)player).GetInventory().MoveItemToThis(inventory, item);
				}
			}
			else
			{
				_trackedInventory = inventory;
				_trackedItem = item;
				_trackedChest = chest;
				SetupDrag?.Invoke(gui, new object[3] { item, inventory, item.m_stack });
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
	internal static class StackItemPatch
	{
		private static readonly FieldInfo DragField = AccessTools.Field(typeof(InventoryGui), "m_dragGo");

		private static bool Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item, Modifier mod)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Invalid comparison between Unknown and I4
			Player localPlayer = Player.m_localPlayer;
			Plugin instance = Plugin.Instance;
			bool flag = instance != null && instance.Settings?.AutomaticItemDistribution.Value == true;
			bool flag2 = (NearbyStorageDialog.IsOpen || (flag && (Object)(object)localPlayer != (Object)null && (Object)(object)StorageLocator.CurrentContainer() == (Object)null && StorageLocator.Nearby(localPlayer).Count > 0)) && (int)mod == 2 && (ZInput.GetKey((KeyCode)306, true) || ZInput.GetKey((KeyCode)305, true));
			if (item?.m_shared == null || (Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting() || !InventoryGui.IsVisible() || !flag2 || grid.GetInventory() != ((Humanoid)localPlayer).GetInventory() || DragField.GetValue(__instance) != null)
			{
				return true;
			}
			NearbyStorageDeposit.TryStartAuto(item);
			return false;
		}
	}
	[HarmonyPatch(typeof(Container), "RPC_StackResponse")]
	internal static class StackResponsePatch
	{
		private static bool Prefix(Container __instance, bool granted)
		{
			return NearbyStorageDeposit.AllowResponse(__instance, granted);
		}
	}
	internal static class StorageLabel
	{
		internal static string ShortLabel(Container chest)
		{
			return ChestRename.ExplicitName(chest) ?? Localization.instance.Localize(chest.GetHoverName());
		}
	}
	internal sealed class CategoryButtonHover : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public void OnPointerEnter(PointerEventData eventData)
		{
			RenameDialog.ShowCategoryHelp();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			RenameDialog.HideCategoryHelp();
		}
	}
	internal sealed class NearbyStorageCard : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerEnterHandler, IPointerExitHandler, IDropHandler
	{
		internal Color IdleColor;

		private static readonly Color HoverColor = new Color(0.42f, 0.36f, 0.32f, 0.96f);

		internal NearbyStorageItem Item;

		internal Image Background;

		public void OnPointerDown(PointerEventData eventData)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			if ((int)eventData.button == 1)
			{
				if (NearbyStorageTransfer.UseConsumable(Item))
				{
					((AbstractEventData)eventData).Use();
				}
			}
			else if ((int)eventData.button == 0 && ZInput.GetKey((KeyCode)308, true))
			{
				NearbyStorageItem item = Item;
				Container val = ((item != null && item.Sources.Count > 0) ? Item.Sources[0].Chest : null);
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)val != (Object)null && (Object)(object)localPlayer != (Object)null && (Object)(object)Chat.instance != (Object)null && (Object)(object)Plugin.Instance != (Object)null && StorageLocator.Eligible(val, localPlayer, StorageLocator.CurrentContainer(), Plugin.Instance.Settings.Radius.Value))
				{
					Chat.instance.SendPing(((Component)val).transform.position);
					((AbstractEventData)eventData).Use();
					((MonoBehaviour)Plugin.Instance).StartCoroutine(CloseAfte