Decompiled source of ToolStacks v0.1.0

plugins/ToolStacks.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.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 ToolStacks
{
	internal static class Gui
	{
		private static class Panel
		{
			private static readonly FieldRef<GameObject> tooltipRef = AccessTools.StaticFieldRefAccess<GameObject>(AccessTools.Field(typeof(UITooltip), "m_tooltip"));

			private static GameObject owner;

			private static RectTransform panel;

			private static readonly List<InventoryElement> cells = new List<InventoryElement>();

			private const float Scale = 0.72f;

			private const float Pad = 8f;

			private const float Gap = 6f;

			internal const int Max = 40;

			internal static void Show(InventoryGrid grid, List<ItemData> members, int chosen)
			{
				//IL_0211: Unknown result type (might be due to invalid IL or missing references)
				//IL_0230: Unknown result type (might be due to invalid IL or missing references)
				//IL_023f: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_012e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0169: Unknown result type (might be due to invalid IL or missing references)
				//IL_0292: Unknown result type (might be due to invalid IL or missing references)
				//IL_0299: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_02de: Unknown result type (might be due to invalid IL or missing references)
				GameObject val = tooltipRef.Invoke();
				if ((Object)(object)val == (Object)null || !val.activeSelf || val.transform.childCount == 0)
				{
					return;
				}
				Transform child = val.transform.GetChild(0);
				RectTransform val2 = (RectTransform)(object)((child is RectTransform) ? child : null);
				if ((Object)(object)val2 == (Object)null)
				{
					return;
				}
				if ((Object)(object)owner != (Object)(object)val || (Object)(object)panel == (Object)null)
				{
					Build(val, val2);
				}
				int num = Math.Min(members.Count, 40);
				int num2 = Math.Max(1, Math.Min(Plugin.IconColumns.Value, num));
				int num3 = (num + num2 - 1) / num2;
				float num4 = grid.m_elementSpace * 0.72f;
				while (cells.Count < num)
				{
					cells.Add(Cell(grid));
				}
				for (int i = 0; i < cells.Count; i++)
				{
					InventoryElement val3 = cells[i];
					bool flag = i < num;
					if (((Component)val3).gameObject.activeSelf != flag)
					{
						((Component)val3).gameObject.SetActive(flag);
					}
					if (flag)
					{
						((RectTransform)((Component)val3).transform).anchoredPosition = new Vector2(8f + (float)(i % num2) * num4, 0f - (8f + (float)(i / num2) * num4));
						ItemData val4 = members[i];
						((Behaviour)val3.m_icon).enabled = true;
						val3.m_icon.sprite = val4.GetIcon();
						((Graphic)val3.m_icon).color = Color.white;
						Durability(val3, val4);
						((Behaviour)val3.m_quality).enabled = val4.m_shared.m_maxQuality > 1;
						if (val4.m_shared.m_maxQuality > 1)
						{
							val3.m_quality.text = val4.m_quality.ToString();
						}
						if ((Object)(object)val3.m_selected != (Object)null)
						{
							val3.m_selected.SetActive(i == chosen);
						}
					}
				}
				panel.sizeDelta = new Vector2(16f + (float)num2 * num4, 16f + (float)num3 * num4);
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				val2.GetWorldCorners(array);
				float num5 = panel.sizeDelta.x * ((Transform)panel).lossyScale.x;
				bool flag2 = array[2].x + 6f + num5 > (float)Screen.width;
				RectTransform obj = panel;
				RectTransform obj2 = panel;
				Vector2 val5 = default(Vector2);
				((Vector2)(ref val5))..ctor(flag2 ? 0f : 1f, 1f);
				obj2.anchorMax = val5;
				obj.anchorMin = val5;
				panel.pivot = new Vector2(flag2 ? 1f : 0f, 1f);
				panel.anchoredPosition = new Vector2(flag2 ? (-6f) : 6f, 0f);
			}

			private static void Build(GameObject tip, RectTransform bkg)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Expected O, but got Unknown
				//IL_0049: 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_00d1: 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)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				cells.Clear();
				owner = tip;
				GameObject val = new GameObject("ToolStacksIcons", new Type[1] { typeof(RectTransform) });
				panel = (RectTransform)val.transform;
				((Transform)panel).SetParent((Transform)(object)bkg, false);
				val.AddComponent<LayoutElement>().ignoreLayout = true;
				CanvasGroup obj = val.AddComponent<CanvasGroup>();
				obj.blocksRaycasts = false;
				obj.interactable = false;
				Image val2 = val.AddComponent<Image>();
				Image component = ((Component)bkg).GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					val2.sprite = component.sprite;
					val2.type = component.type;
					((Graphic)val2).color = ((Graphic)component).color;
					val2.pixelsPerUnitMultiplier = component.pixelsPerUnitMultiplier;
					((Graphic)val2).material = ((Graphic)component).material;
				}
				else
				{
					((Graphic)val2).color = new Color(0f, 0f, 0f, 0.8f);
				}
				((Graphic)val2).raycastTarget = false;
			}

			private static InventoryElement Cell(InventoryGrid grid)
			{
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
				GameObject val = Object.Instantiate<GameObject>(grid.m_elementPrefab, (Transform)(object)panel);
				UITooltip[] componentsInChildren = val.GetComponentsInChildren<UITooltip>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
				}
				UIInputHandler[] componentsInChildren2 = val.GetComponentsInChildren<UIInputHandler>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
				}
				UIDragHandler[] componentsInChildren3 = val.GetComponentsInChildren<UIDragHandler>(true);
				for (int i = 0; i < componentsInChildren3.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
				}
				Graphic[] componentsInChildren4 = val.GetComponentsInChildren<Graphic>(true);
				for (int i = 0; i < componentsInChildren4.Length; i++)
				{
					componentsInChildren4[i].raycastTarget = false;
				}
				RectTransform val2 = (RectTransform)val.transform;
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(0f, 1f);
				val2.anchorMax = val3;
				val2.anchorMin = val3;
				val2.pivot = new Vector2(0f, 1f);
				((Transform)val2).localScale = Vector3.one * 0.72f;
				InventoryElement component = val.GetComponent<InventoryElement>();
				Transform val4 = val.transform.Find("binding");
				if ((Object)(object)val4 != (Object)null)
				{
					((Component)val4).gameObject.SetActive(false);
				}
				((Behaviour)component.m_amount).enabled = false;
				((Behaviour)component.m_equiped).enabled = false;
				((Behaviour)component.m_queued).enabled = false;
				((Behaviour)component.m_noteleport).enabled = false;
				((Behaviour)component.m_food).enabled = false;
				if ((Object)(object)component.m_selected != (Object)null)
				{
					component.m_selected.SetActive(false);
				}
				return component;
			}
		}

		internal static (Inventory inv, Vector2i pos)? Pending;

		private static Inventory dragInv;

		private static ItemData dragHead;

		private static Inventory choiceInv;

		private static Vector2i choicePos;

		private static int choiceCount;

		private static int choice = -1;

		private static readonly Dictionary<Vector2i, List<ItemData>> stacks = new Dictionary<Vector2i, List<ItemData>>();

		private static readonly Dictionary<InventoryGrid, (ScrollRect rect, float sensitivity)> scrolls = new Dictionary<InventoryGrid, (ScrollRect, float)>();

		internal static void StartDrag(ItemData item, Inventory inventory)
		{
			//IL_004e: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			(Inventory, Vector2i)? pending = Pending;
			Pending = null;
			dragInv = null;
			dragHead = null;
			if (item != null && inventory != null && pending.HasValue && pending.Value.Item1 == inventory && item.m_gridPos.x == pending.Value.Item2.x && item.m_gridPos.y == pending.Value.Item2.y && Piles.CountAt(inventory, item.m_gridPos) >= 2)
			{
				dragInv = inventory;
				dragHead = item;
			}
		}

		internal static bool IsWholeDrag(Inventory inv, ItemData item)
		{
			if (dragHead == null || inv == null || inv != dragInv || item != dragHead)
			{
				return false;
			}
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null)
			{
				return instance.m_dragItem == dragHead;
			}
			return false;
		}

		internal static int ChosenAt(Inventory inv, Vector2i pos, int count)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (choiceInv != inv || choicePos.x != pos.x || choicePos.y != pos.y || choiceCount != count)
			{
				return -1;
			}
			return choice;
		}

		internal static void ClearChoice()
		{
			choiceInv = null;
			choice = -1;
			choiceCount = 0;
		}

		private static void Hover(Inventory inv, Vector2i pos, int count)
		{
			//IL_003b: 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)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (choiceInv != inv || choicePos.x != pos.x || choicePos.y != pos.y || choiceCount != count)
			{
				choiceInv = inv;
				choicePos = pos;
				choiceCount = count;
				choice = -1;
			}
		}

		internal static void Update(InventoryGrid grid)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = grid.m_inventory;
			int width = inventory.GetWidth();
			stacks.Clear();
			foreach (ItemData item in inventory.m_inventory)
			{
				if (!stacks.TryGetValue(item.m_gridPos, out var value))
				{
					value = (stacks[item.m_gridPos] = new List<ItemData>(2));
				}
				value.Add(item);
			}
			InventoryGui instance = InventoryGui.instance;
			bool flag = (Object)(object)instance != (Object)null && (Object)(object)instance.m_dragGo != (Object)null;
			InventoryElement hoveredElement = grid.GetHoveredElement();
			Vector2i val = (Vector2i)(((Object)(object)hoveredElement != (Object)null) ? grid.GetElementPos(hoveredElement) : new Vector2i(-1, -1));
			List<ItemData> list2 = null;
			if (val.x >= 0 && stacks.TryGetValue(val, out var value2) && value2.Count >= 2)
			{
				list2 = value2;
			}
			if (list2 != null)
			{
				Hover(inventory, val, list2.Count);
				float mouseScrollWheel = ZInput.GetMouseScrollWheel();
				if (mouseScrollWheel != 0f && !flag)
				{
					choice = Piles.Step(choice, list2.Count, (mouseScrollWheel < 0f) ? 1 : (-1));
				}
				LockScroll(grid, locked: true);
			}
			else
			{
				if (choiceInv == inventory)
				{
					ClearChoice();
				}
				LockScroll(grid, locked: false);
			}
			foreach (KeyValuePair<Vector2i, List<ItemData>> stack in stacks)
			{
				List<ItemData> value3 = stack.Value;
				if (value3.Count < 2)
				{
					continue;
				}
				InventoryElement element = grid.GetElement(stack.Key.x, stack.Key.y, width);
				if (!((Object)(object)element == (Object)null))
				{
					int num = ChosenAt(inventory, stack.Key, value3.Count);
					ItemData val2 = ((num >= 0) ? value3[num] : value3[0]);
					bool flag2 = IsWholeDrag(inventory, value3[0]);
					if (!flag2 && flag && instance.m_dragItem == val2)
					{
						val2 = ((value3[0] != val2) ? value3[0] : value3[1]);
					}
					Show(element, val2, flag2);
					((Behaviour)element.m_amount).enabled = true;
					element.m_amount.text = value3.Count.ToString();
				}
			}
			if (Plugin.Icons && list2 != null && !flag)
			{
				Panel.Show(grid, list2, choice);
			}
		}

		private static void Show(InventoryElement element, ItemData item, bool grey)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)element.m_icon).enabled = true;
			element.m_icon.sprite = item.GetIcon();
			((Graphic)element.m_icon).color = (grey ? Color.grey : Color.white);
			Durability(element, item);
			((Behaviour)element.m_quality).enabled = item.m_shared.m_maxQuality > 1;
			if (item.m_shared.m_maxQuality > 1)
			{
				element.m_quality.text = item.m_quality.ToString();
			}
		}

		internal static void Durability(InventoryElement element, ItemData item)
		{
			//IL_0089: 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)
			bool flag = item.m_shared.m_useDurability && item.m_durability < item.GetMaxDurability();
			((Component)element.m_durability).gameObject.SetActive(flag);
			if (flag)
			{
				if (item.m_durability <= 0f)
				{
					element.m_durability.SetValue(1f);
					element.m_durability.SetColor((Color)((Mathf.Sin(Time.time * 10f) > 0f) ? Color.red : new Color(0f, 0f, 0f, 0f)));
				}
				else
				{
					element.m_durability.SetValue(item.GetDurabilityPercentage());
					element.m_durability.ResetColor();
				}
			}
		}

		internal static string TooltipText(Inventory inv, Vector2i pos, List<ItemData> members)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Words.Ensure();
			int num = ChosenAt(inv, pos, members.Count);
			string text = "$toolstacks_in_stack: " + members.Count;
			if (Plugin.Icons)
			{
				ItemData val = ((num >= 0) ? members[num] : members[0]);
				return text + "\n" + Piles.Hint(num) + "\n\n" + val.GetTooltip(-1);
			}
			string text2 = text + "\n" + Piles.Lines(members, num) + "\n\n" + Piles.Hint(num);
			if (num >= 0)
			{
				text2 = text2 + "\n\n" + members[num].GetTooltip(-1);
			}
			return text2;
		}

		private static void LockScroll(InventoryGrid grid, bool locked)
		{
			if (!scrolls.TryGetValue(grid, out (ScrollRect, float) value))
			{
				ScrollRect val = (((Object)(object)grid.m_gridRoot != (Object)null) ? ((Component)grid.m_gridRoot).GetComponentInParent<ScrollRect>() : null);
				value = (val, ((Object)(object)val != (Object)null) ? val.scrollSensitivity : 0f);
				scrolls[grid] = value;
			}
			if (!((Object)(object)value.Item1 == (Object)null))
			{
				float num = (locked ? 0f : value.Item2);
				if (value.Item1.scrollSensitivity != num)
				{
					value.Item1.scrollSensitivity = num;
				}
			}
		}
	}
	internal static class Hooks
	{
		[HarmonyPatch(typeof(Localization), "SetupLanguage")]
		private static class Language
		{
			private static void Postfix(Localization __instance, string language)
			{
				Words.Add(__instance, language);
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwake
		{
			[HarmonyPriority(200)]
			private static void Postfix(Container __instance)
			{
				if (__instance.m_inventory != null && Plugin.Wanted(__instance))
				{
					Piles.Mark(__instance.m_inventory, new Box
					{
						Height = __instance.m_height
					});
				}
			}
		}

		[HarmonyPatch(typeof(Container), "Save")]
		private static class ContainerSave
		{
			private static bool Prefix(Container __instance)
			{
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Expected O, but got Unknown
				Inventory inventory = __instance.m_inventory;
				Box box = Piles.Of(inventory);
				if (box == null)
				{
					return true;
				}
				box.Height = __instance.m_height;
				List<(ItemData, Vector2i)> list = Piles.Spread(inventory, box);
				if (list.Count == 0)
				{
					return true;
				}
				ZNetView nview = __instance.m_nview;
				ZDO val = ((nview != null) ? nview.GetZDO() : null);
				if (val == null)
				{
					Piles.Restore(list);
					return true;
				}
				ZPackage val2 = new ZPackage();
				try
				{
					inventory.Save(val2);
				}
				finally
				{
					Piles.Restore(list);
				}
				val.Set(ZDOVars.s_items, val2.GetArray());
				__instance.m_lastRevision = val.DataRevision;
				return false;
			}
		}

		[HarmonyPatch(typeof(Container), "Load")]
		private static class ContainerLoad
		{
			private static void Prefix(Container __instance, out Box __state)
			{
				__state = Piles.Of(__instance.m_inventory);
				if (__state != null)
				{
					__state.Height = __instance.m_height;
					__state.Loading = true;
				}
			}

			private static void Postfix(Container __instance, bool __result, Box __state)
			{
				if (__state != null)
				{
					__state.Loading = false;
					if (__result)
					{
						Piles.Fold(__instance.m_inventory, __state);
						__instance.UpdateRows();
					}
				}
			}

			private static Exception Finalizer(Exception __exception, Box __state)
			{
				if (__state != null)
				{
					__state.Loading = false;
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })]
		private static class AddItem
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null || box.Loading || !Piles.Join(__instance, box, item))
				{
					return true;
				}
				__instance.Changed(true, false);
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
		{
			typeof(ItemData),
			typeof(Vector2i)
		})]
		private static class AddItemAt
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null || box.Loading || !Piles.Join(__instance, box, item))
				{
					return true;
				}
				__instance.Changed(true, false);
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static class AddItemAmount
		{
			private static bool Prefix(Inventory __instance, ItemData item, int amount, int x, int y, ref bool __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null || item == null)
				{
					return true;
				}
				bool? flag = Piles.AddAt(__instance, box, item, amount, x, y);
				if (!flag.HasValue)
				{
					return true;
				}
				__result = flag.Value;
				if (flag.Value && Player.m_localPlayerExists)
				{
					__instance.Changed(true, false);
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[]
		{
			typeof(ItemData),
			typeof(int)
		})]
		private static class CanAddItem
		{
			private static bool Prefix(Inventory __instance, ItemData item, int stack, ref bool __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null || item?.m_shared == null)
				{
					return true;
				}
				__result = Piles.CanAdd(__instance, box, item, stack);
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "HaveEmptySlot")]
		private static class HaveEmptySlot
		{
			private static bool Prefix(Inventory __instance, ref bool __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null)
				{
					return true;
				}
				__result = Piles.EmptyCells(__instance, box) > 0;
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "GetEmptySlots")]
		private static class GetEmptySlots
		{
			private static bool Prefix(Inventory __instance, ref int __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null)
				{
					return true;
				}
				__result = Piles.EmptyCells(__instance, box);
				return false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "SlotsUsedPercentage")]
		private static class SlotsUsed
		{
			private static bool Prefix(Inventory __instance, ref float __result)
			{
				Box box = Piles.Of(__instance);
				if (box == null)
				{
					return true;
				}
				int num = __instance.GetWidth() * __instance.GetHeight();
				__result = ((num <= 0) ? 100f : ((float)(num - Piles.EmptyCells(__instance, box)) * 100f / (float)num));
				return false;
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
		private static class DragItem
		{
			private static void Postfix(ItemData item, Inventory inventory)
			{
				Gui.StartDrag(item, inventory);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "UpdateItemDrag")]
		private static class DragCount
		{
			private static void Postfix(InventoryGui __instance)
			{
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)__instance.m_dragGo == (Object)null) && Gui.IsWholeDrag(__instance.m_dragInventory, __instance.m_dragItem))
				{
					Transform obj = __instance.m_dragGo.transform.Find("amount");
					TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null);
					if ((Object)(object)val != (Object)null)
					{
						val.text = Piles.CountAt(__instance.m_dragInventory, __instance.m_dragItem.m_gridPos).ToString();
					}
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
		private static class SelectedItem
		{
			private static bool Prefix(InventoryGui __instance, InventoryGrid grid, ref ItemData item, Modifier mod)
			{
				//IL_003c: 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_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a6: Invalid comparison between Unknown and I4
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				//IL_0119: Unknown result type (might be due to invalid IL or missing references)
				//IL_0127: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				Gui.Pending = null;
				if ((Object)(object)__instance.m_dragGo != (Object)null || item == null || (Object)(object)grid == (Object)null)
				{
					return true;
				}
				Inventory inventory = grid.GetInventory();
				if (!Piles.Is(inventory))
				{
					return true;
				}
				List<ItemData> list = Piles.Members(inventory, item.m_gridPos);
				if (list.Count < 2)
				{
					return true;
				}
				int num = Gui.ChosenAt(inventory, item.m_gridPos, list.Count);
				Gui.ClearChoice();
				if (num >= 0)
				{
					Piles.BringToFront(inventory, list[num]);
					item = list[num];
					return true;
				}
				Gui.Pending = (inventory, item.m_gridPos);
				Player localPlayer = Player.m_localPlayer;
				if ((int)mod != 2 || (Object)(object)localPlayer == (Object)null || (Object)(object)__instance.m_currentContainer == (Object)null || ((Character)localPlayer).IsTeleporting())
				{
					return true;
				}
				Gui.Pending = null;
				Inventory inventory2 = ((Humanoid)localPlayer).GetInventory();
				if (Piles.Distribute(inventory, item.m_gridPos, inventory2, new Vector2i(-1, -1), out var left) > 0)
				{
					inventory.Changed(false, false);
					inventory2.Changed(false, false);
					__instance.m_moveItemEffects.Create(((Component)__instance).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
				if (left > 0)
				{
					Say("toolstacks_noroom");
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
		private static class GridDrop
		{
			private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, int amount, Vector2i pos, ref bool __result)
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: 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_0106: Unknown result type (might be due to invalid IL or missing references)
				//IL_010d: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_0123: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0152: Unknown result type (might be due to invalid IL or missing references)
				//IL_0154: Unknown result type (might be due to invalid IL or missing references)
				//IL_0226: Unknown result type (might be due to invalid IL or missing references)
				//IL_022b: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
				Inventory inventory = __instance.m_inventory;
				Box box = Piles.Of(inventory);
				bool flag = Piles.Is(fromInventory);
				if ((box == null && !flag) || item == null || fromInventory == null || inventory == null)
				{
					return true;
				}
				if (!fromInventory.ContainsItem(item))
				{
					return true;
				}
				if (inventory == fromInventory)
				{
					if (box == null)
					{
						return true;
					}
					if (item.m_gridPos.x == pos.x && item.m_gridPos.y == pos.y)
					{
						__result = true;
						return false;
					}
					if (!Piles.Inside(inventory, box, pos.x, pos.y))
					{
						return true;
					}
					Piles.MoveCell(inventory, item.m_gridPos, pos);
					inventory.Changed(false, false);
					__result = true;
					return false;
				}
				if (flag && Gui.IsWholeDrag(fromInventory, item))
				{
					int left;
					int num = Piles.Distribute(fromInventory, item.m_gridPos, inventory, pos, out left);
					if (num > 0)
					{
						fromInventory.Changed(false, false);
						inventory.Changed(false, false);
					}
					if (left > 0)
					{
						Say("toolstacks_noroom");
					}
					__result = num > 0;
					return false;
				}
				if (flag && box == null && Piles.CountAt(fromInventory, item.m_gridPos) >= 2 && inventory.GetItemAt(pos.x, pos.y) != null)
				{
					Vector2i val = inventory.FindEmptySlot(inventory.TopFirst(item));
					if (val.x < 0)
					{
						Say("toolstacks_noroom");
						__result = false;
						return false;
					}
					fromInventory.m_inventory.Remove(item);
					item.m_gridPos = val;
					inventory.m_inventory.Add(item);
					fromInventory.Changed(false, false);
					inventory.Changed(false, false);
					__result = true;
					return false;
				}
				if (box == null)
				{
					return true;
				}
				bool flag2 = item.m_stack == amount;
				if (flag2 && Piles.Pileable(item) && Piles.Room(inventory))
				{
					Vector2i? val2 = Piles.CellOf(inventory, box, item.m_shared.m_name, item);
					if (val2.HasValue)
					{
						fromInventory.RemoveItem(item);
						item.m_gridPos = val2.Value;
						inventory.m_inventory.Add(item);
						inventory.Changed(false, false);
						__result = true;
						return false;
					}
				}
				if (flag2 && Piles.CountAt(inventory, pos) >= 2)
				{
					Vector2i? val3 = Piles.FreeCell(inventory, box);
					if (!val3.HasValue)
					{
						Say("toolstacks_noroom");
						__result = false;
						return false;
					}
					fromInventory.RemoveItem(item);
					item.m_gridPos = val3.Value;
					inventory.m_inventory.Add(item);
					inventory.Changed(false, false);
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "DropItem")]
		private static class GroundDrop
		{
			private static bool dropping;

			private static void Prefix(Humanoid __instance, Inventory inventory, ItemData item)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				if (dropping || item == null || !Gui.IsWholeDrag(inventory, item))
				{
					return;
				}
				List<ItemData> list = Piles.Members(inventory, item.m_gridPos);
				dropping = true;
				try
				{
					foreach (ItemData item2 in list)
					{
						if (item2 != item)
						{
							__instance.DropItem(inventory, item2, item2.m_stack);
						}
					}
				}
				finally
				{
					dropping = false;
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
		private static class GridGui
		{
			private static void Postfix(InventoryGrid __instance)
			{
				if (!Piles.Is(__instance.m_inventory))
				{
					return;
				}
				try
				{
					Gui.Update(__instance);
				}
				catch (Exception ex)
				{
					Plugin.Warn("window: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip")]
		private static class GridTooltip
		{
			private static bool Prefix(InventoryGrid __instance, ItemData item, UITooltip tooltip)
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				if (item == null || (Object)(object)tooltip == (Object)null || !Piles.Is(__instance.m_inventory))
				{
					return true;
				}
				List<ItemData> list = Piles.Members(__instance.m_inventory, item.m_gridPos);
				if (list.Count < 2)
				{
					return true;
				}
				tooltip.Set(item.m_shared.m_name, Gui.TooltipText(__instance.m_inventory, item.m_gridPos, list), __instance.m_tooltipAnchor, default(Vector2));
				return false;
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "UpdateContainer")]
		private static class OpenChest
		{
			private static void Prefix(InventoryGui __instance)
			{
				Container currentContainer = __instance.m_currentContainer;
				if ((Object)(object)currentContainer == (Object)null || (Object)(object)__instance.m_dragGo != (Object)null || !currentContainer.IsOwner())
				{
					return;
				}
				Inventory inventory = currentContainer.m_inventory;
				Box box = Piles.Of(inventory);
				if (box != null && !box.Loading && Piles.Signature(inventory) != box.Seen)
				{
					box.Height = currentContainer.m_height;
					if (Piles.Fold(inventory, box))
					{
						currentContainer.UpdateRows();
						inventory.Changed(false, false);
						Plugin.Debug("gathered the stacks of " + ((Object)currentContainer).name);
					}
					box.Seen = Piles.Signature(inventory);
				}
			}
		}

		private static float lastMessage;

		internal static void Say(string key)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !(Time.time - lastMessage < 0.5f))
			{
				lastMessage = Time.time;
				Words.Ensure();
				((Character)localPlayer).Message((MessageType)2, "$" + key, 0, (Sprite)null, false);
			}
		}
	}
	internal sealed class Box
	{
		internal int Height;

		internal bool Loading;

		internal long Seen;
	}
	internal static class Piles
	{
		private static readonly ConditionalWeakTable<Inventory, Box> boxes = new ConditionalWeakTable<Inventory, Box>();

		internal const int LastRow = 250;

		internal const int ListMax = 30;

		internal static void Mark(Inventory inv, Box box)
		{
			if (inv != null)
			{
				boxes.Remove(inv);
				boxes.Add(inv, box);
			}
		}

		internal static Box Of(Inventory inv)
		{
			if (inv == null)
			{
				return null;
			}
			if (!boxes.TryGetValue(inv, out var value))
			{
				return null;
			}
			return value;
		}

		internal static bool Is(Inventory inv)
		{
			return Of(inv) != null;
		}

		internal static bool Pileable(ItemData item)
		{
			if (item?.m_shared != null)
			{
				return item.m_shared.m_maxStackSize <= 1;
			}
			return false;
		}

		private static int Rows(Inventory inv, Box box)
		{
			if (box == null || box.Height <= 0)
			{
				return inv.GetHeight();
			}
			return box.Height;
		}

		internal static bool Inside(Inventory inv, Box box, int x, int y)
		{
			if (x >= 0 && y >= 0 && x < inv.GetWidth())
			{
				return y < Rows(inv, box);
			}
			return false;
		}

		private static bool Same(Vector2i a, Vector2i b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (a.x == b.x)
			{
				return a.y == b.y;
			}
			return false;
		}

		internal static List<ItemData> Members(Inventory inv, Vector2i at)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			List<ItemData> list = new List<ItemData>();
			foreach (ItemData item in inv.m_inventory)
			{
				if (Same(item.m_gridPos, at))
				{
					list.Add(item);
				}
			}
			return list;
		}

		internal static int CountAt(Inventory inv, Vector2i at)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			foreach (ItemData item in inv.m_inventory)
			{
				if (Same(item.m_gridPos, at))
				{
					num++;
				}
			}
			return num;
		}

		private static ItemData ItemAt(Inventory inv, int x, int y, ItemData except = null)
		{
			foreach (ItemData item in inv.m_inventory)
			{
				if (item != except && item.m_gridPos.x == x && item.m_gridPos.y == y)
				{
					return item;
				}
			}
			return null;
		}

		internal static Vector2i? CellOf(Inventory inv, Box box, string name, ItemData except = null)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			foreach (ItemData item in inv.m_inventory)
			{
				if (item != except && Pileable(item) && item.m_shared.m_name == name && Inside(inv, box, item.m_gridPos.x, item.m_gridPos.y))
				{
					return item.m_gridPos;
				}
			}
			return null;
		}

		private static HashSet<Vector2i> Taken(Inventory inv, ItemData except = null)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Vector2i> hashSet = new HashSet<Vector2i>();
			foreach (ItemData item in inv.m_inventory)
			{
				if (item != except)
				{
					hashSet.Add(item.m_gridPos);
				}
			}
			return hashSet;
		}

		internal static Vector2i? FreeCell(Inventory inv, Box box, ItemData except = null)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Vector2i> hashSet = Taken(inv, except);
			int width = inv.GetWidth();
			int num = Rows(inv, box);
			for (int i = 0; i < num; i++)
			{
				for (int j = 0; j < width; j++)
				{
					if (!hashSet.Contains(new Vector2i(j, i)))
					{
						return new Vector2i(j, i);
					}
				}
			}
			return null;
		}

		internal static int EmptyCells(Inventory inv, Box box)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Vector2i> hashSet = Taken(inv);
			int width = inv.GetWidth();
			int num = Rows(inv, box);
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				for (int j = 0; j < width; j++)
				{
					if (!hashSet.Contains(new Vector2i(j, i)))
					{
						num2++;
					}
				}
			}
			return num2;
		}

		private static Vector2i? Beyond(Inventory inv, Box box)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Vector2i> hashSet = Taken(inv);
			int width = inv.GetWidth();
			for (int i = Rows(inv, box); i <= 250; i++)
			{
				for (int j = 0; j < width; j++)
				{
					if (!hashSet.Contains(new Vector2i(j, i)))
					{
						return new Vector2i(j, i);
					}
				}
			}
			return null;
		}

		internal static bool Room(Inventory inv)
		{
			return inv.m_inventory.Count < inv.GetWidth() * 250;
		}

		internal static bool Join(Inventory inv, Box box, ItemData item)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!Pileable(item) || !Room(inv))
			{
				return false;
			}
			Vector2i? val = CellOf(inv, box, item.m_shared.m_name, item);
			if (!val.HasValue)
			{
				return false;
			}
			inv.m_inventory.Remove(item);
			item.m_gridPos = val.Value;
			inv.m_inventory.Add(item);
			return true;
		}

		internal static bool? AddAt(Inventory inv, Box box, ItemData item, int amount, int x, int y)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if (!Pileable(item))
			{
				return null;
			}
			amount = Math.Min(amount, item.m_stack);
			if (amount <= 0)
			{
				return null;
			}
			Vector2i? val = (Room(inv) ? CellOf(inv, box, item.m_shared.m_name, item) : ((Vector2i?)null));
			if (!val.HasValue)
			{
				if (ItemAt(inv, x, y, item) == null)
				{
					return null;
				}
				if (Inside(inv, box, x, y) || !box.Loading)
				{
					val = FreeCell(inv, box, item);
				}
				if (!val.HasValue && box.Loading)
				{
					val = Beyond(inv, box);
				}
				if (!val.HasValue)
				{
					return false;
				}
			}
			ItemData val2 = item.Clone();
			val2.m_stack = amount;
			val2.m_gridPos = val.Value;
			inv.m_inventory.Add(val2);
			item.m_stack -= amount;
			return true;
		}

		internal static bool CanAdd(Inventory inv, Box box, ItemData item, int stack)
		{
			if (item?.m_shared == null)
			{
				return false;
			}
			if (stack <= 0)
			{
				stack = item.m_stack;
			}
			if (Pileable(item) && Room(inv) && CellOf(inv, box, item.m_shared.m_name).HasValue)
			{
				return true;
			}
			return inv.FindFreeStackSpace(item.m_shared.m_name, (float)item.m_worldLevel) + (long)EmptyCells(inv, box) * (long)item.m_shared.m_maxStackSize >= stack;
		}

		internal static int Distribute(Inventory from, Vector2i cell, Inventory to, Vector2i start, out int left)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			List<ItemData> list = Members(from, cell);
			int num = 0;
			Box box = Of(to);
			bool flag = true;
			foreach (ItemData item in list)
			{
				Vector2i val2;
				if (box != null)
				{
					Vector2i? val = CellOf(to, box, item.m_shared.m_name) ?? FreeCell(to, box);
					if (!val.HasValue || !Room(to))
					{
						break;
					}
					val2 = val.Value;
				}
				else
				{
					val2 = ((flag && start.x >= 0 && start.y >= 0 && start.x < to.GetWidth() && start.y < to.GetHeight() && to.GetItemAt(start.x, start.y) == null) ? start : to.FindEmptySlot(to.TopFirst(item)));
					if (val2.x < 0)
					{
						break;
					}
				}
				flag = false;
				from.m_inventory.Remove(item);
				item.m_gridPos = val2;
				to.m_inventory.Add(item);
				num++;
			}
			left = list.Count - num;
			return num;
		}

		internal static void MoveCell(Inventory inv, Vector2i from, Vector2i to)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0057: 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)
			if (Same(from, to))
			{
				return;
			}
			List<ItemData> list = Members(inv, from);
			List<ItemData> list2 = Members(inv, to);
			foreach (ItemData item in list)
			{
				item.m_gridPos = to;
			}
			foreach (ItemData item2 in list2)
			{
				item2.m_gridPos = from;
			}
		}

		internal static void BringToFront(Inventory inv, ItemData item)
		{
			//IL_0014: 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)
			List<ItemData> inventory = inv.m_inventory;
			int num = -1;
			for (int i = 0; i < inventory.Count; i++)
			{
				if (Same(inventory[i].m_gridPos, item.m_gridPos))
				{
					num = i;
					break;
				}
			}
			if (num >= 0 && inventory[num] != item)
			{
				inventory.Remove(item);
				inventory.Insert(num, item);
			}
		}

		internal static bool Fold(Inventory inv, Box box)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			bool result = false;
			List<ItemData> inventory = inv.m_inventory;
			Dictionary<string, Vector2i> dictionary = new Dictionary<string, Vector2i>();
			foreach (ItemData item in inventory)
			{
				if (Pileable(item) && Inside(inv, box, item.m_gridPos.x, item.m_gridPos.y) && !dictionary.ContainsKey(item.m_shared.m_name))
				{
					dictionary[item.m_shared.m_name] = item.m_gridPos;
				}
			}
			foreach (ItemData item2 in inventory)
			{
				if (!Pileable(item2))
				{
					continue;
				}
				if (!dictionary.TryGetValue(item2.m_shared.m_name, out var value))
				{
					if (Inside(inv, box, item2.m_gridPos.x, item2.m_gridPos.y))
					{
						continue;
					}
					Vector2i? val = FreeCell(inv, box, item2);
					if (!val.HasValue)
					{
						continue;
					}
					value = val.Value;
					dictionary[item2.m_shared.m_name] = value;
				}
				if (!Same(item2.m_gridPos, value))
				{
					item2.m_gridPos = value;
					result = true;
				}
			}
			Dictionary<Vector2i, string> dictionary2 = new Dictionary<Vector2i, string>();
			List<ItemData> list = new List<ItemData>();
			for (int i = 0; i < inventory.Count; i++)
			{
				ItemData val2 = inventory[i];
				string text = (Pileable(val2) ? val2.m_shared.m_name : ("\u0001" + i));
				if (!dictionary2.TryGetValue(val2.m_gridPos, out var value2))
				{
					dictionary2[val2.m_gridPos] = text;
				}
				else if (value2 != text)
				{
					list.Add(val2);
				}
			}
			Dictionary<string, Vector2i> dictionary3 = new Dictionary<string, Vector2i>();
			foreach (ItemData item3 in list)
			{
				string text2 = (Pileable(item3) ? item3.m_shared.m_name : null);
				Vector2i? val3 = null;
				val3 = ((text2 == null || !dictionary3.TryGetValue(text2, out var value3)) ? FreeCell(inv, box, item3) : new Vector2i?(value3));
				if (val3.HasValue)
				{
					item3.m_gridPos = val3.Value;
					if (text2 != null)
					{
						dictionary3[text2] = val3.Value;
					}
					result = true;
				}
			}
			return result;
		}

		internal static long Signature(Inventory inv)
		{
			long num = inv.m_inventory.Count;
			foreach (ItemData item in inv.m_inventory)
			{
				num = num * 31 + (item.m_shared?.m_name?.GetHashCode()).GetValueOrDefault() * 7 + item.m_gridPos.x * 1000 + item.m_gridPos.y;
			}
			return num;
		}

		internal static List<(ItemData item, Vector2i pos)> Spread(Inventory inv, Box box)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			List<(ItemData, Vector2i)> list = new List<(ItemData, Vector2i)>();
			HashSet<Vector2i> hashSet = new HashSet<Vector2i>();
			List<ItemData> list2 = new List<ItemData>();
			foreach (ItemData item in inv.m_inventory)
			{
				if (!hashSet.Add(item.m_gridPos))
				{
					list2.Add(item);
				}
			}
			if (list2.Count == 0)
			{
				return list;
			}
			int width = inv.GetWidth();
			Rows(inv, box);
			int num = 0;
			int num2 = 0;
			foreach (ItemData item2 in list2)
			{
				while (num2 <= 250 && hashSet.Contains(new Vector2i(num, num2)))
				{
					if (++num >= width)
					{
						num = 0;
						num2++;
					}
				}
				if (num2 > 250)
				{
					break;
				}
				list.Add((item2, item2.m_gridPos));
				item2.m_gridPos = new Vector2i(num, num2);
				hashSet.Add(item2.m_gridPos);
			}
			return list;
		}

		internal static void Restore(List<(ItemData item, Vector2i pos)> plan)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			foreach (var item3 in plan)
			{
				ItemData item = item3.item;
				Vector2i item2 = item3.pos;
				item.m_gridPos = item2;
			}
		}

		internal static int Step(int index, int count, int delta)
		{
			if (count <= 0)
			{
				return -1;
			}
			int num = count + 1;
			return ((index + 1 + delta) % num + num) % num - 1;
		}

		internal static string Bar(float fraction, int cells = 10)
		{
			if (float.IsNaN(fraction))
			{
				fraction = 0f;
			}
			fraction = Math.Max(0f, Math.Min(1f, fraction));
			int num = (int)Math.Round(fraction * (float)cells);
			if (fraction > 0f && num == 0)
			{
				num = 1;
			}
			string value = ((fraction > 0.5f) ? "#8ccf5c" : ((fraction > 0.25f) ? "#e3c454" : "#e0584c"));
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<color=").Append(value).Append('>')
				.Append('|', num)
				.Append("</color>");
			if (num < cells)
			{
				stringBuilder.Append("<color=#5a5a5a>").Append('|', cells - num).Append("</color>");
			}
			return stringBuilder.ToString();
		}

		internal static string Line(ItemData item, int number, bool chosen)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (chosen)
			{
				stringBuilder.Append("<color=orange>");
			}
			stringBuilder.Append(number).Append('.');
			if (item.m_shared.m_maxQuality > 1)
			{
				stringBuilder.Append("  $toolstacks_level ").Append(item.m_quality);
			}
			if (item.m_shared.m_useDurability)
			{
				float maxDurability = item.GetMaxDurability();
				float fraction = ((maxDurability > 0f) ? (item.m_durability / maxDurability) : 1f);
				stringBuilder.Append("  ").Append(chosen ? "</color>" : "").Append(Bar(fraction))
					.Append(chosen ? "<color=orange>" : "");
				stringBuilder.Append("  ").Append((int)Math.Ceiling(Math.Max(0f, item.m_durability))).Append('/')
					.Append((int)Math.Ceiling(maxDurability));
			}
			if (chosen)
			{
				stringBuilder.Append("</color>");
			}
			return stringBuilder.ToString();
		}

		internal static string Lines(List<ItemData> members, int chosen)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			if (members.Count > 30 && chosen >= 30)
			{
				num = chosen - 30 + 1;
			}
			int num2 = Math.Min(members.Count, num + 30);
			if (num > 0)
			{
				stringBuilder.Append("...\n");
			}
			for (int i = num; i < num2; i++)
			{
				stringBuilder.Append(Line(members[i], i + 1, i == chosen)).Append('\n');
			}
			if (num2 < members.Count)
			{
				stringBuilder.Append("... +").Append(members.Count - num2).Append('\n');
			}
			return stringBuilder.ToString().TrimEnd('\n');
		}

		internal static string Hint(int chosen)
		{
			return "<color=#a0a0a0>$toolstacks_hint_wheel\n" + ((chosen < 0) ? "$toolstacks_hint_all" : "$toolstacks_hint_one") + "</color>";
		}
	}
	[BepInPlugin("chistix.toolstacks", "Tool Stacks", "0.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "chistix.toolstacks";

		public const string Version = "0.1.0";

		private static ManualLogSource log;

		internal static ConfigEntry<string> Style;

		internal static ConfigEntry<string> Excluded;

		internal static ConfigEntry<int> IconColumns;

		internal static ConfigEntry<bool> DebugLog;

		private static HashSet<string> excluded = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static GUIStyle centred;

		internal static bool Icons
		{
			get
			{
				if (Style != null)
				{
					return Style.Value == "Icons";
				}
				return false;
			}
		}

		private void Awake()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			log = ((BaseUnityPlugin)this).Logger;
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				CustomDrawer = Stepper
			};
			Style = ((BaseUnityPlugin)this).Config.Bind<string>("Tooltip", "Style", "List", new ConfigDescription("How the tooltip of a stack shows its items. List: a line per item (number, durability bar and numbers, level). Icons: small cells as in the inventory (icon, level, durability bar) next to the tooltip.\nКак подсказка пачки показывает её предметы. List: строка на предмет (номер, полоска и числа прочности, уровень). Icons: маленькие ячейки как в инвентаре (значок, уровень, полоска прочности) рядом с подсказкой.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "List", "Icons" }), new object[1] { configurationManagerAttributes }));
			IconColumns = ((BaseUnityPlugin)this).Config.Bind<int>("Tooltip", "IconColumns", 5, new ConfigDescription("Icons style: cells in a row.\nВид Icons: ячеек в ряду.", (AcceptableValueBase)(object)new AcceptableValueList<int>(new int[6] { 3, 4, 5, 6, 7, 8 }), new object[1] { configurationManagerAttributes }));
			Excluded = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludedChests", "", new ConfigDescription("Prefab names of chests that keep the game's one item per cell, comma-separated (e.g. piece_chest_wood, Cart). Applies to a chest when it is loaded again. Graves and Deep Slots' chests are never stacked.\nИмена префабов сундуков, где остаётся правило игры «один предмет - одна ячейка», через запятую (например piece_chest_wood, Cart). Применяется к сундуку, когда он загрузится заново. Могилы и сундуки Deep Slots не трогаются никогда.", (AcceptableValueBase)null, Array.Empty<object>()));
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DebugLog", false, "More details in the log.\nПодробности в журнал.");
			ReadExcluded();
			Excluded.SettingChanged += delegate
			{
				ReadExcluded();
			};
			new Harmony("chistix.toolstacks").PatchAll(typeof(Plugin).Assembly);
			Log("Tool Stacks 0.1.0");
		}

		private static void ReadExcluded()
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = (Excluded.Value ?? "").Split(',', ';');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					hashSet.Add(text);
				}
			}
			excluded = hashSet;
		}

		internal static bool Wanted(Container c)
		{
			if ((Object)(object)c == (Object)null)
			{
				return false;
			}
			GameObject val = (Object.op_Implicit((Object)(object)c.m_rootObjectOverride) ? ((Component)c.m_rootObjectOverride).gameObject : ((Component)c).gameObject);
			if ((Object)(object)val.GetComponentInChildren<TombStone>() != (Object)null || (Object)(object)((Component)c).GetComponentInParent<TombStone>() != (Object)null)
			{
				return false;
			}
			if (c.m_name != null && c.m_name.StartsWith("$deep_", StringComparison.Ordinal))
			{
				return false;
			}
			if (excluded.Count > 0 && excluded.Contains(Utils.GetPrefabName(val)))
			{
				return false;
			}
			return true;
		}

		internal static void Stepper(ConfigEntryBase entry)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			AcceptableValueBase acceptableValues = entry.Description.AcceptableValues;
			if (((object)acceptableValues)?.GetType().GetProperty("AcceptableValues")?.GetValue(acceptableValues, null) is Array { Length: not 0 } array)
			{
				int num = Array.IndexOf(array, entry.BoxedValue);
				if (centred == null)
				{
					centred = new GUIStyle(GUI.skin.label)
					{
						alignment = (TextAnchor)4
					};
				}
				if (GUILayout.Button("‹", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(28f) }))
				{
					entry.BoxedValue = array.GetValue((Math.Max(num, 0) - 1 + array.Length) % array.Length);
				}
				GUILayout.Label(entry.BoxedValue?.ToString() ?? "", centred, (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.MinWidth(120f),
					GUILayout.ExpandWidth(true)
				});
				if (GUILayout.Button("›", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(28f) }))
				{
					entry.BoxedValue = array.GetValue((num + 1) % array.Length);
				}
			}
			else
			{
				GUILayout.Label(entry.BoxedValue?.ToString() ?? "", Array.Empty<GUILayoutOption>());
			}
		}

		internal static void Log(string text)
		{
			ManualLogSource obj = log;
			if (obj != null)
			{
				obj.LogInfo((object)text);
			}
		}

		internal static void Warn(string text)
		{
			ManualLogSource obj = log;
			if (obj != null)
			{
				obj.LogWarning((object)text);
			}
		}

		internal static void Debug(string text)
		{
			if (DebugLog != null && DebugLog.Value)
			{
				ManualLogSource obj = log;
				if (obj != null)
				{
					obj.LogInfo((object)text);
				}
			}
		}
	}
	internal sealed class ConfigurationManagerAttributes
	{
		public Action<ConfigEntryBase> CustomDrawer;
	}
	internal static class Words
	{
		private static readonly Action<Localization, string, string> AddWord = AccessTools.MethodDelegate<Action<Localization, string, string>>(AccessTools.Method(typeof(Localization), "AddWord", (Type[])null, (Type[])null), (object)null, true);

		internal static readonly (string key, string en, string ru)[] Texts = new(string, string, string)[6]
		{
			("toolstacks_in_stack", "In the stack", "В пачке"),
			("toolstacks_level", "level", "ур."),
			("toolstacks_hint_wheel", "Mouse wheel: pick an item", "Колёсико мыши: выбрать предмет"),
			("toolstacks_hint_all", "Click: take the whole stack", "Щелчок: взять всю пачку"),
			("toolstacks_hint_one", "Click: take the chosen item", "Щелчок: взять выбранный предмет"),
			("toolstacks_noroom", "Not enough room: the rest stays in the chest", "Не хватает места: остальное осталось в сундуке")
		};

		private static string added;

		internal static void Ensure()
		{
			Localization instance = Localization.instance;
			if (instance != null)
			{
				string selectedLanguage = instance.GetSelectedLanguage();
				if (selectedLanguage != added)
				{
					Add(instance, selectedLanguage);
				}
			}
		}

		internal static void Add(Localization localization, string language)
		{
			if (localization != null && AddWord != null)
			{
				added = language;
				bool flag = string.Equals(language, "Russian", StringComparison.OrdinalIgnoreCase);
				(string, string, string)[] texts = Texts;
				for (int i = 0; i < texts.Length; i++)
				{
					var (arg, text, text2) = texts[i];
					AddWord(localization, arg, flag ? text2 : text);
				}
			}
		}
	}
}