Decompiled source of CollectAll v1.1.1

CollectAll.dll

Decompiled 8 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ChestShared;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("CollectAll")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+fb6bd2cf164162aba018070f047fdf2d8de12792")]
[assembly: AssemblyProduct("CollectAll")]
[assembly: AssemblyTitle("CollectAll")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChestShared
{
	internal static class InventoryOps
	{
		public static bool IsSameStack(ItemData a, ItemData b)
		{
			if (a.m_shared.m_name == b.m_shared.m_name && a.m_quality == b.m_quality)
			{
				return a.m_worldLevel == b.m_worldLevel;
			}
			return false;
		}

		public static int Units(Inventory inv, ItemData kind)
		{
			int num = 0;
			foreach (ItemData allItem in inv.GetAllItems())
			{
				if (IsSameStack(allItem, kind))
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		public static int FreeSpaceFor(Inventory inv, ItemData item)
		{
			int num = Math.Max(1, item.m_shared.m_maxStackSize);
			long num2 = (long)Math.Max(0, inv.GetEmptySlots()) * (long)num;
			if (num > 1)
			{
				foreach (ItemData allItem in inv.GetAllItems())
				{
					if (IsSameStack(allItem, item) && allItem.m_stack < num)
					{
						num2 += num - allItem.m_stack;
					}
				}
			}
			return (int)Math.Min(2147483647L, num2);
		}

		public static int Transfer(Inventory from, Inventory to, ItemData item, int amount, Action<string, Exception> fail)
		{
			if (from == null || to == null || item == null)
			{
				return 0;
			}
			if (amount <= 0 || item.m_stack <= 0 || !from.ContainsItem(item))
			{
				return 0;
			}
			amount = Math.Min(amount, item.m_stack);
			if (from == to)
			{
				return 0;
			}
			ItemData kind = item.Clone();
			int expected = Units(from, kind) + Units(to, kind);
			int num = Units(to, kind);
			try
			{
				ItemData val = item.Clone();
				val.m_stack = amount;
				int num2 = (to.AddItem(val) ? amount : (amount - val.m_stack));
				if (num2 > 0 && !from.RemoveItem(item, num2))
				{
					Fail(fail, "Transfer", new InvalidOperationException($"could not remove {num2}x {item.m_shared.m_name} from source"));
				}
			}
			catch (Exception e)
			{
				Fail(fail, "Transfer", e);
			}
			Reconcile(from, to, kind, expected, from, fail);
			return Math.Max(0, Units(to, kind) - num);
		}

		public static bool Reconcile(Inventory a, Inventory b, ItemData kind, int expected, Inventory preferred, Action<string, Exception> fail)
		{
			bool result = false;
			for (int i = 0; i < 3; i++)
			{
				int num = Units(a, kind) + Units(b, kind);
				if (num == expected)
				{
					return result;
				}
				result = true;
				try
				{
					Inventory[] array;
					if (num < expected)
					{
						int num2 = expected - num;
						array = (Inventory[])(object)new Inventory[2]
						{
							preferred,
							(preferred == a) ? b : a
						};
						foreach (Inventory val in array)
						{
							int num3 = Math.Min(num2, FreeSpaceFor(val, kind));
							if (num3 > 0)
							{
								ItemData val2 = kind.Clone();
								val2.m_stack = num3;
								try
								{
									val.AddItem(val2);
								}
								catch (Exception e)
								{
									Fail(fail, "Repair", e);
								}
								num2 = expected - (Units(a, kind) + Units(b, kind));
								if (num2 <= 0)
								{
									break;
								}
							}
						}
						continue;
					}
					int num4 = num - expected;
					array = (Inventory[])(object)new Inventory[2]
					{
						(preferred == a) ? b : a,
						preferred
					};
					foreach (Inventory inv in array)
					{
						int num5 = Math.Min(num4, Units(inv, kind));
						if (num5 > 0)
						{
							RemoveUnits(inv, kind, num5);
							num4 -= num5;
							if (num4 <= 0)
							{
								break;
							}
						}
					}
				}
				catch (Exception e2)
				{
					Fail(fail, "Repair", e2);
				}
			}
			int num6 = Units(a, kind) + Units(b, kind);
			if (num6 != expected)
			{
				Fail(fail, "Repair", new InvalidOperationException($"{kind.m_shared.m_name}: expected {expected}, have {num6}"));
			}
			return true;
		}

		private static void RemoveUnits(Inventory inv, ItemData kind, int count)
		{
			foreach (ItemData item in (from i in inv.GetAllItems()
				where IsSameStack(i, kind)
				select i).ToList())
			{
				if (count <= 0)
				{
					break;
				}
				int num = Math.Min(count, item.m_stack);
				inv.RemoveItem(item, num);
				count -= num;
			}
		}

		private static void Fail(Action<string, Exception> fail, string what, Exception e)
		{
			try
			{
				fail?.Invoke(what, e);
			}
			catch
			{
			}
		}

		public static bool ContainsItem(this Inventory inv, ItemData item)
		{
			if (inv == null || item == null)
			{
				return false;
			}
			foreach (ItemData allItem in inv.GetAllItems())
			{
				if (allItem == item)
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace CollectAll
{
	internal static class ChestFinder
	{
		public sealed class Found
		{
			public List<CollectSource> Sources = new List<CollectSource>();

			public int NotOwned;
		}

		private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly MethodInfo CheckForChanges = typeof(Container).GetMethod("CheckForChanges", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

		private static readonly MethodInfo CheckAccess = typeof(Container).GetMethod("CheckAccess", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(long) }, null);

		private static readonly List<Piece> PieceBuffer = new List<Piece>();

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

		public static Found ChestsAround(Container target, Player player, float radius, string itemName)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			Found found = new Found();
			Vector3 position = ((Component)target).transform.position;
			long playerID = player.GetPlayerID();
			PieceBuffer.Clear();
			Piece.GetAllPiecesInRadius(position, radius, PieceBuffer);
			foreach (Piece item in PieceBuffer)
			{
				try
				{
					if ((Object)(object)item == (Object)null)
					{
						continue;
					}
					Container container = ((Component)item).GetComponent<Container>();
					if ((Object)(object)container == (Object)null || (Object)(object)container == (Object)(object)target || !IsStorageChest(item, container))
					{
						continue;
					}
					ZNetView nview = ((Component)container).GetComponent<ZNetView>();
					if ((Object)(object)nview == (Object)null || !nview.IsValid() || container.GetInventory() == null || (CheckAccess != null && !(bool)CheckAccess.Invoke(container, new object[1] { playerID })) || !PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false) || Collector.CountOf(container.GetInventory(), itemName) == 0)
					{
						continue;
					}
					if (!nview.IsOwner())
					{
						found.NotOwned++;
						continue;
					}
					Refresh(container);
					if (nview.IsValid() && nview.IsOwner())
					{
						found.Sources.Add(new CollectSource
						{
							Inventory = container.GetInventory(),
							IsBusy = () => IsOpenByAnyone(container, nview),
							Distance = Vector3.Distance(position, ((Component)container).transform.position)
						});
					}
				}
				catch (Exception ex)
				{
					WarnOnce("piece", "Skipping a chest that couldn't be read (" + ex.GetType().Name + ": " + ex.Message + "). Further errors like this are not logged.");
				}
			}
			return found;
		}

		private static bool IsStorageChest(Piece piece, Container container)
		{
			if (container.m_autoDestroyEmpty)
			{
				return false;
			}
			if (IsObliterator(container))
			{
				return false;
			}
			if ((Object)(object)((Component)piece).GetComponent<Ship>() != (Object)null || (Object)(object)((Component)piece).GetComponent<Vagon>() != (Object)null || (Object)(object)container.m_wagon != (Object)null)
			{
				return false;
			}
			return true;
		}

		internal static bool IsObliterator(Container container)
		{
			if (!((Object)(object)((Component)container).GetComponent<Incinerator>() != (Object)null))
			{
				return (Object)(object)((Component)container).GetComponentInParent<Incinerator>() != (Object)null;
			}
			return true;
		}

		private static bool IsOpenByAnyone(Container container, ZNetView nview)
		{
			if ((Object)(object)container == (Object)null || (Object)(object)nview == (Object)null || !nview.IsValid())
			{
				return true;
			}
			if (container.IsInUse())
			{
				return true;
			}
			ZDO zDO = nview.GetZDO();
			if (zDO != null)
			{
				return zDO.GetInt(ZDOVars.s_inUse, 0) == 1;
			}
			return false;
		}

		private static void Refresh(Container container)
		{
			if (CheckForChanges == null)
			{
				WarnOnce("refresh-missing", "Container.CheckForChanges not found (game update?). Chest contents may be up to a second stale.");
				return;
			}
			try
			{
				CheckForChanges.Invoke(container, null);
			}
			catch (Exception ex)
			{
				WarnOnce("refresh", "Refreshing a chest failed: " + (ex.InnerException?.Message ?? ex.Message));
			}
		}

		internal static void WarnOnce(string key, string message)
		{
			if (LoggedOnce.Add(key))
			{
				Plugin.Log.LogWarning((object)message);
			}
		}
	}
	internal sealed class CollectSource
	{
		public Inventory Inventory;

		public Func<bool> IsBusy;

		public float Distance;

		public bool Busy
		{
			get
			{
				try
				{
					return IsBusy?.Invoke() ?? false;
				}
				catch
				{
					return true;
				}
			}
		}
	}
	internal sealed class CollectResult
	{
		public string ItemName;

		public int Moved;

		public int ChestsTakenFrom;

		public int LeftBehind;

		public int BusySkipped;

		public int BiggerSkipped;

		public int FullSkipped;

		public int Errors;

		public bool TargetFull => LeftBehind > 0;
	}
	internal static class Collector
	{
		public static CollectResult Collect(Inventory target, ItemData example, IEnumerable<CollectSource> sources, Action<string, Exception> warn, bool skipBiggerPiles, bool skipFullChests)
		{
			CollectResult result = new CollectResult
			{
				ItemName = example?.m_shared?.m_name
			};
			if (target == null || result.ItemName == null)
			{
				return result;
			}
			Action<string, Exception> action = delegate(string what, Exception e)
			{
				result.Errors++;
				try
				{
					warn?.Invoke(what, e);
				}
				catch
				{
				}
			};
			List<KeyValuePair<CollectSource, List<ItemData>>> list = new List<KeyValuePair<CollectSource, List<ItemData>>>();
			foreach (CollectSource item in sources.Where((CollectSource s) => s?.Inventory != null && s.Inventory != target))
			{
				try
				{
					List<ItemData> list2 = (from i in item.Inventory.GetAllItems()
						where i.m_shared.m_name == result.ItemName
						select i).ToList();
					if (list2.Count > 0)
					{
						list.Add(new KeyValuePair<CollectSource, List<ItemData>>(item, list2));
					}
				}
				catch (Exception arg)
				{
					action("Reading a chest", arg);
				}
			}
			foreach (KeyValuePair<CollectSource, List<ItemData>> item2 in from p in list
				orderby p.Value.Sum((ItemData i) => i.m_stack), p.Key.Distance
				select p)
			{
				CollectSource key = item2.Key;
				List<ItemData> value = item2.Value;
				if (key.Busy)
				{
					result.BusySkipped++;
					continue;
				}
				if (skipFullChests && IsFullOfOnly(key.Inventory, result.ItemName))
				{
					result.FullSkipped++;
					continue;
				}
				if (skipBiggerPiles && CountOf(key.Inventory, result.ItemName) > CountOf(target, result.ItemName))
				{
					result.BiggerSkipped++;
					continue;
				}
				bool flag = false;
				foreach (ItemData item3 in value.OrderByDescending((ItemData i) => i.m_stack))
				{
					try
					{
						if (!key.Inventory.ContainsItem(item3) || item3.m_stack <= 0)
						{
							continue;
						}
						int num = InventoryOps.FreeSpaceFor(target, item3);
						if (num <= 0)
						{
							result.LeftBehind += item3.m_stack;
							continue;
						}
						int num2 = InventoryOps.Transfer(key.Inventory, target, item3, Math.Min(num, item3.m_stack), action);
						if (num2 > 0)
						{
							result.Moved += num2;
							flag = true;
						}
						if (key.Inventory.ContainsItem(item3) && item3.m_stack > 0)
						{
							result.LeftBehind += item3.m_stack;
						}
					}
					catch (Exception arg2)
					{
						action("Collecting " + result.ItemName, arg2);
					}
				}
				if (flag)
				{
					result.ChestsTakenFrom++;
				}
			}
			return result;
		}

		internal static bool IsFullOfOnly(Inventory inv, string itemName)
		{
			if (inv == null || inv.GetEmptySlots() > 0)
			{
				return false;
			}
			List<ItemData> allItems = inv.GetAllItems();
			if (allItems.Count == 0)
			{
				return false;
			}
			foreach (ItemData item in allItems)
			{
				if (item.m_shared.m_name != itemName)
				{
					return false;
				}
				if (item.m_stack < Math.Max(1, item.m_shared.m_maxStackSize))
				{
					return false;
				}
			}
			return true;
		}

		internal static int CountOf(Inventory inv, string itemName)
		{
			return (from i in inv.GetAllItems()
				where i.m_shared.m_name == itemName
				select i).Sum((ItemData i) => i.m_stack);
		}
	}
	[HarmonyPatch]
	internal static class CollectUi
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__OnButtonClicked;
		}

		private static readonly FieldInfo CurrentContainerField = AccessTools.Field(typeof(InventoryGui), "m_currentContainer");

		private static readonly FieldInfo ContainerGridField = AccessTools.Field(typeof(InventoryGui), "m_containerGrid");

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

		private static Button _button;

		private static TMP_Text _label;

		private static Color _labelColor = Color.white;

		private static bool _pickMode;

		private static readonly string[] StripComponents = new string[5] { "Localize", "UIGamePad", "UIInputHint", "UITooltip", "ButtonTextColor" };

		private static Vector2 _buttonSize = new Vector2(110f, 34f);

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InventoryGui), "Awake")]
		private static void AddButton(InventoryGui __instance)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Button val = (((Object)(object)__instance.m_stackAllButton != (Object)null) ? __instance.m_stackAllButton : __instance.m_takeAllButton);
				if ((Object)(object)val == (Object)null || (Object)(object)__instance.m_container == (Object)null)
				{
					Plugin.Log.LogError((object)"Chest window not found (game update?); the Collect button is not available. Alt+click still works.");
					return;
				}
				Rect rect = ((RectTransform)((Component)val).transform).rect;
				if (((Rect)(ref rect)).width > 20f && ((Rect)(ref rect)).height > 10f)
				{
					_buttonSize = new Vector2(Mathf.Min(((Rect)(ref rect)).width, 140f), ((Rect)(ref rect)).height);
				}
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, (Transform)(object)__instance.m_container);
				((Object)val2).name = "CollectAllButton";
				val2.SetActive(true);
				Component[] componentsInChildren = val2.GetComponentsInChildren<Component>(true);
				foreach (Component val3 in componentsInChildren)
				{
					if ((Object)(object)val3 != (Object)null && Array.IndexOf(StripComponents, ((object)val3).GetType().Name) >= 0)
					{
						Object.DestroyImmediate((Object)(object)val3);
					}
				}
				Transform[] componentsInChildren2 = val2.GetComponentsInChildren<Transform>(true);
				foreach (Transform val4 in componentsInChildren2)
				{
					if ((Object)(object)val4 != (Object)(object)val2.transform && IsHint(val4, val2.transform))
					{
						((Component)val4).gameObject.SetActive(false);
					}
				}
				_button = val2.GetComponent<Button>();
				_button.onClick = new ButtonClickedEvent();
				ButtonClickedEvent onClick = _button.onClick;
				object obj = <>O.<0>__OnButtonClicked;
				if (obj == null)
				{
					UnityAction val5 = OnButtonClicked;
					<>O.<0>__OnButtonClicked = val5;
					obj = (object)val5;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				_label = null;
				TMP_Text[] componentsInChildren3 = val2.GetComponentsInChildren<TMP_Text>(true);
				foreach (TMP_Text val6 in componentsInChildren3)
				{
					if (!IsHint(val6.transform, val2.transform))
					{
						_label = val6;
						break;
					}
				}
				if ((Object)(object)_label != (Object)null)
				{
					_labelColor = ((Graphic)_label).color;
				}
				UpdateLabel();
				Pin(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not add the Collect button: {arg}");
			}
		}

		private static bool IsHint(Transform t, Transform root)
		{
			Transform val = t;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
			{
				if (((Object)val).name.IndexOf("hint", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		internal static void OnSettingsChanged()
		{
			UpdateLabel();
			if ((Object)(object)InventoryGui.instance != (Object)null)
			{
				Pin(InventoryGui.instance);
			}
		}

		private static void Pin(InventoryGui gui)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_button == (Object)null) && !((Object)(object)gui == (Object)null) && !((Object)(object)gui.m_container == (Object)null))
			{
				RectTransform val = (RectTransform)((Component)_button).transform;
				if ((Object)(object)((Transform)val).parent != (Object)(object)gui.m_container)
				{
					((Transform)val).SetParent((Transform)(object)gui.m_container, false);
				}
				LayoutElement val2 = ((Component)val).GetComponent<LayoutElement>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)val).gameObject.AddComponent<LayoutElement>();
				}
				val2.ignoreLayout = true;
				val.anchorMin = new Vector2(1f, 1f);
				val.anchorMax = new Vector2(1f, 1f);
				val.pivot = new Vector2(1f, 1f);
				((Transform)val).localScale = Vector3.one;
				((Transform)val).localRotation = Quaternion.identity;
				val.sizeDelta = _buttonSize;
				val.anchoredPosition = new Vector2(-16f + Plugin.ButtonOffsetX.Value, -12f + Plugin.ButtonOffsetY.Value);
				((Transform)val).SetAsLastSibling();
			}
		}

		private static void OnButtonClicked()
		{
			InventoryGui instance = InventoryGui.instance;
			if (!((Object)(object)instance == (Object)null) && InventoryGui.IsVisible() && instance.IsContainerOpen() && DragItemField?.GetValue(instance) == null)
			{
				_pickMode = !_pickMode;
				UpdateLabel();
				if (_pickMode)
				{
					Message("Click an item to collect all of it into this chest");
				}
			}
		}

		private static void UpdateLabel()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_label == (Object)null))
			{
				_label.text = (_pickMode ? "Pick item..." : Plugin.ButtonText.Value);
				((Graphic)_label).color = (Color)(_pickMode ? new Color(1f, 0.82f, 0.35f) : _labelColor);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InventoryGui), "Update")]
		private static void EveryFrame(InventoryGui __instance)
		{
			if (_pickMode && (!InventoryGui.IsVisible() || !__instance.IsContainerOpen() || Input.GetKeyDown((KeyCode)27)))
			{
				_pickMode = false;
				UpdateLabel();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")]
		private static bool OnRightClickItem()
		{
			if (!_pickMode)
			{
				return true;
			}
			_pickMode = false;
			UpdateLabel();
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
		private static bool OnSelectedItem(InventoryGui __instance, InventoryGrid grid, ItemData item)
		{
			try
			{
				bool flag = Plugin.AltClickShortcut.Value && ShortcutHeld() && (Object)(object)grid != (Object)null && grid == ContainerGridField?.GetValue(__instance);
				if (!_pickMode && !flag)
				{
					return true;
				}
				if (DragItemField?.GetValue(__instance) != null)
				{
					_pickMode = false;
					UpdateLabel();
					return true;
				}
				if (item == null)
				{
					return !_pickMode;
				}
				object? obj = CurrentContainerField?.GetValue(__instance);
				Container val = (Container)((obj is Container) ? obj : null);
				_pickMode = false;
				UpdateLabel();
				if ((Object)(object)val == (Object)null)
				{
					return true;
				}
				CollectInto(val, item);
				return false;
			}
			catch (Exception arg)
			{
				_pickMode = false;
				UpdateLabel();
				Plugin.Log.LogError((object)$"Collect failed: {arg}");
				return true;
			}
		}

		private static bool ShortcutHeld()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected I4, but got Unknown
			KeyCode value = Plugin.ShortcutKey.Value;
			if ((int)value == 0)
			{
				return false;
			}
			if (Input.GetKey(value))
			{
				return true;
			}
			switch (value - 303)
			{
			case 4:
			case 5:
				if (!Input.GetKey((KeyCode)308))
				{
					return Input.GetKey((KeyCode)307);
				}
				return true;
			case 2:
			case 3:
				if (!Input.GetKey((KeyCode)306))
				{
					return Input.GetKey((KeyCode)305);
				}
				return true;
			case 0:
			case 1:
				if (!Input.GetKey((KeyCode)304))
				{
					return Input.GetKey((KeyCode)303);
				}
				return true;
			default:
				return false;
			}
		}

		private static void CollectInto(Container target, ItemData example)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)target).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
			{
				Message("Can't collect into this chest right now");
				return;
			}
			if (ChestFinder.IsObliterator(target))
			{
				Message("Not into the Obliterator!");
				return;
			}
			ChestFinder.Found found = ChestFinder.ChestsAround(target, localPlayer, Plugin.Radius.Value, example.m_shared.m_name);
			CollectResult collectResult = Collector.Collect(target.GetInventory(), example, found.Sources, delegate(string what, Exception e)
			{
				Plugin.Log.LogWarning((object)(what + ": " + e.GetType().Name + ": " + e.Message));
			}, Plugin.SkipBiggerPiles.Value, Plugin.SkipFullChests.Value);
			Message(Describe(collectResult, found.NotOwned, Plugin.Radius.Value, Localize(collectResult.ItemName)));
			if (collectResult.Moved > 0)
			{
				Plugin.Log.LogInfo((object)$"Collected {collectResult.Moved}x {collectResult.ItemName} from {collectResult.ChestsTakenFrom} chests");
			}
		}

		internal static string Describe(CollectResult r, int notOwned, float radius, string name)
		{
			string text;
			if (r.Moved <= 0)
			{
				text = (r.TargetFull ? ("No room in this chest for more " + name) : ((r.BiggerSkipped > 0) ? ("Other chests have more " + name + " than this one\nCollect into the biggest pile instead") : ((r.FullSkipped <= 0) ? $"No other {name} in chests within {radius:0} m" : ("The only other " + name + " is in full " + name + " chests - left alone"))));
			}
			else
			{
				text = string.Format("Collected {0} {1} from {2} chest{3}", r.Moved, name, r.ChestsTakenFrom, (r.ChestsTakenFrom == 1) ? "" : "s");
				if (r.TargetFull)
				{
					text += $"\nChest is full - {r.LeftBehind} more still elsewhere";
				}
			}
			if (r.Moved > 0 && r.BiggerSkipped > 0)
			{
				text += string.Format("\n{0} chest{1} with more {2} left alone", r.BiggerSkipped, (r.BiggerSkipped == 1) ? "" : "s", name);
			}
			if (r.Moved > 0 && r.FullSkipped > 0)
			{
				text += string.Format("\n{0} full {1} chest{2} left alone", r.FullSkipped, name, (r.FullSkipped == 1) ? "" : "s");
			}
			int num = r.BusySkipped + notOwned;
			if (num > 0)
			{
				text += string.Format("\n{0} chest{1} skipped (open, or another player's)", num, (num == 1) ? "" : "s");
			}
			if (r.Errors > 0)
			{
				text += "\nSomething went wrong - see BepInEx log (item counts were checked)";
			}
			return text;
		}

		private static string Localize(string token)
		{
			try
			{
				return (Localization.instance != null) ? Localization.instance.Localize(token) : token;
			}
			catch
			{
				return token;
			}
		}

		private static void Message(string text)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
			}
		}
	}
	[BepInPlugin("dcarrigg.collectall", "CollectAll", "1.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "dcarrigg.collectall";

		public const string Name = "CollectAll";

		public const string Version = "1.1.1";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> Radius;

		internal static ConfigEntry<bool> AltClickShortcut;

		internal static ConfigEntry<KeyCode> ShortcutKey;

		internal static ConfigEntry<bool> SkipBiggerPiles;

		internal static ConfigEntry<bool> SkipFullChests;

		internal static ConfigEntry<string> ButtonText;

		internal static ConfigEntry<float> ButtonOffsetX;

		internal static ConfigEntry<float> ButtonOffsetY;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Radius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Radius", 60f, new ConfigDescription("How far (meters) from the open chest to look for more of the item.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 100f), Array.Empty<object>()));
			AltClickShortcut = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AltClickShortcut", true, "Hold ShortcutKey and click an item in the chest to collect it straight away, without pressing the button first.");
			ShortcutKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "ShortcutKey", (KeyCode)308, "Key to hold while clicking an item for the shortcut. Left and right Alt/Ctrl/Shift both count. Shift and Ctrl already do something on click in vanilla; the shortcut replaces that in the chest.");
			SkipBiggerPiles = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SkipBiggerPiles", false, "Bigger pile wins: never take from a chest that holds more of the item than the chest you're collecting into. Items only flow toward your biggest pile, so collecting in two chests can't shuffle them back and forth. Turn off to pull from every chest regardless (e.g. to move a whole stash into a new chest).");
			SkipFullChests = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SkipFullChests", true, "Never take from a chest that is completely full and holds nothing but that item (a finished stash). A chest with any other item, a partial stack or an empty slot is still collected from. Works on its own or together with SkipBiggerPiles.");
			ButtonText = ((BaseUnityPlugin)this).Config.Bind<string>("Button", "Text", "Collect", "Label on the button in the chest window.");
			ButtonOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetX", 0f, "Nudge the button sideways (pixels) if it overlaps something, e.g. another mod's button.");
			ButtonOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetY", 0f, "Nudge the button up/down (pixels).");
			ButtonText.SettingChanged += delegate
			{
				CollectUi.OnSettingsChanged();
			};
			ButtonOffsetX.SettingChanged += delegate
			{
				CollectUi.OnSettingsChanged();
			};
			ButtonOffsetY.SettingChanged += delegate
			{
				CollectUi.OnSettingsChanged();
			};
			try
			{
				_harmony = new Harmony("dcarrigg.collectall");
				_harmony.PatchAll(typeof(Plugin).Assembly);
				Log.LogInfo((object)"CollectAll 1.1.1 loaded");
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("{0} could not hook into the chest window (game update?) and is disabled: {1}", "CollectAll", arg));
				try
				{
					Harmony harmony = _harmony;
					if (harmony != null)
					{
						harmony.UnpatchSelf();
					}
				}
				catch
				{
				}
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}