Decompiled source of Carturs Waste Management v1.2.8

plugins/CarturWasteManagement/CarturWasteManagement.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("CarturWasteManagement")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c90fcdcf09cfd7d61bbc928fe1aa6fd3bb8bc05d")]
[assembly: AssemblyProduct("CarturWasteManagement")]
[assembly: AssemblyTitle("CarturWasteManagement")]
[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 CarturWasteManagement
{
	[BepInPlugin("com.jekkle.valheim.carturwastemanagement", "Cartur's Waste Management", "1.2.7")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.jekkle.valheim.carturwastemanagement";

		public const string PluginName = "Cartur's Waste Management";

		public const string PluginVersion = "1.2.7";

		internal static Sprite CanSprite;

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> ShowTrashCan;

		internal static ConfigEntry<bool> ShowBagSort;

		internal static ConfigEntry<bool> ShowChestSort;

		internal static ConfigEntry<bool> ShowChestSortAll;

		internal static ConfigEntry<float> GatherRange;

		internal static ConfigEntry<KeyboardShortcut> QuickDepositKey;

		internal static ConfigEntry<Vector2> TrashCanOffset;

		internal static ConfigEntry<Vector2> BagSortOffset;

		internal static ConfigEntry<Vector2> ChestSortOffset;

		private void Awake()
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: 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_0142: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			CanSprite = LoadSprite("trashcan_128.png");
			ShowTrashCan = ((BaseUnityPlugin)this).Config.Bind<bool>("Buttons", "ShowTrashCan", true, "Show the trash can in the player panel.");
			ShowBagSort = ((BaseUnityPlugin)this).Config.Bind<bool>("Buttons", "ShowBagSort", true, "Show the Sort button under the trash can, for your own bag.");
			ShowChestSort = ((BaseUnityPlugin)this).Config.Bind<bool>("Buttons", "ShowChestSort", true, "Show the Sort button above the chest's weight, for the open chest.");
			ShowChestSortAll = ((BaseUnityPlugin)this).Config.Bind<bool>("Buttons", "ShowChestSortAll", true, "Show the Sort All button above Sort, for every chest in range.");
			GatherRange = ((BaseUnityPlugin)this).Config.Bind<float>("Buttons", "GatherRange", 20f, "How far, in metres, a chest's Sort pulls matching items in from nearby chests, how far Sort All reaches, and how far Quick Deposit looks. 0 disables all three. The bag's Sort never takes from chests.");
			QuickDepositKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "QuickDeposit", new KeyboardShortcut((KeyCode)121, Array.Empty<KeyCode>()), "Press to move every loose item in your bag that a chest within GatherRange already holds into that chest, without opening it. Hotbar row and equipped items are never moved.");
			TrashCanOffset = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Buttons", "TrashCanOffset", Vector2.zero, "Nudge the trash can from where it normally sits, in UI pixels. X is right, Y is up.");
			BagSortOffset = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Buttons", "BagSortOffset", Vector2.zero, "Nudge the bag Sort button, in UI pixels. X is right, Y is up.");
			ChestSortOffset = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Buttons", "ChestSortOffset", Vector2.zero, "Nudge the chest Sort button, in UI pixels. X is right, Y is up. Moves Sort and Sort All together. Use this when another mod already owns the space above the chest's weight.");
			try
			{
				Harmony.CreateAndPatchAll(typeof(Plugin).Assembly, "com.jekkle.valheim.carturwastemanagement");
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Cartur's Waste Management 1.2.7 loaded - trash can refunds half the item's own recipe, sort button added.");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)$"Failed to patch InventoryGui - no can and no sort button this run. {arg}");
			}
		}

		private void Update()
		{
			//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)
			KeyboardShortcut value = QuickDepositKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				WasteBin.QuickDeposit();
			}
		}

		private Sprite LoadSprite(string fileName)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "", "assets"), fileName);
			if (!File.Exists(text))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("asset missing: " + text));
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false)
			{
				wrapMode = (TextureWrapMode)1
			};
			MethodInfo methodInfo = null;
			MethodInfo[] array = AccessTools.TypeByName("UnityEngine.ImageConversion")?.GetMethods(BindingFlags.Static | BindingFlags.Public) ?? new MethodInfo[0];
			foreach (MethodInfo methodInfo2 in array)
			{
				ParameterInfo[] parameters = methodInfo2.GetParameters();
				if (methodInfo2.Name == "LoadImage" && parameters.Length == 3 && parameters[1].ParameterType == typeof(byte[]))
				{
					methodInfo = methodInfo2;
					break;
				}
			}
			if (!(methodInfo == null))
			{
				object obj = methodInfo.Invoke(null, new object[3]
				{
					val,
					File.ReadAllBytes(text),
					false
				});
				if (obj is bool && (bool)obj)
				{
					return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
				}
			}
			((BaseUnityPlugin)this).Logger.LogWarning((object)("could not decode " + text));
			return null;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Show")]
	public static class Patch_InventoryGui_Show
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__SortOpenContainer;

			public static UnityAction <1>__SortAllContainers;

			public static UnityAction <2>__DropCarriedItem;

			public static UnityAction <3>__SortPlayerInventory;
		}

		private const float CanSize = 54f;

		private const float ButtonWidth = 54f;

		private const float ButtonHeight = 30f;

		private const float Gap = 6f;

		private static GameObject s_can;

		private static GameObject s_sort;

		private static GameObject s_containerSort;

		private static GameObject s_containerSortAll;

		private static Vector2 s_canHome;

		private static Vector2 s_sortHome;

		private static Vector2 s_containerSortHome;

		private static Vector2 s_containerSortAllHome;

		private static void Postfix(InventoryGui __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				BuildContainerSort(__instance);
				BuildPlayerButtons(__instance);
				ApplySettings();
			}
		}

		private static void BuildPlayerButtons(InventoryGui gui)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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)
			//IL_0081: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)s_can != (Object)null) && !((Object)(object)gui.m_weight == (Object)null))
			{
				RectTransform rectTransform = gui.m_weight.rectTransform;
				Transform parent = ((Transform)rectTransform).parent;
				RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
				if (!((Object)(object)val == (Object)null))
				{
					float num = rectTransform.anchoredPosition.y + 30f + 6f;
					float num2 = num + 15f + 27f + 6f;
					s_canHome = new Vector2(rectTransform.anchoredPosition.x, num2);
					s_sortHome = new Vector2(rectTransform.anchoredPosition.x, num);
					s_can = BuildCan(val, s_canHome);
					s_sort = BuildSort(gui, val, s_sortHome);
				}
			}
		}

		private static void ApplySettings()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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)
			Place(s_can, s_canHome, Plugin.ShowTrashCan.Value, Plugin.TrashCanOffset.Value);
			Place(s_sort, s_sortHome, Plugin.ShowBagSort.Value, Plugin.BagSortOffset.Value);
			Place(s_containerSort, s_containerSortHome, Plugin.ShowChestSort.Value, Plugin.ChestSortOffset.Value);
			Place(s_containerSortAll, s_containerSortAllHome, Plugin.ShowChestSortAll.Value, Plugin.ChestSortOffset.Value);
		}

		private static void Place(GameObject go, Vector2 home, bool show, Vector2 offset)
		{
			//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_001d: 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)
			if (!((Object)(object)go == (Object)null))
			{
				go.SetActive(show);
				((RectTransform)go.transform).anchoredPosition = home + offset;
			}
		}

		private unsafe static void BuildContainerSort(InventoryGui gui)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: 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_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_containerSort != (Object)null || (Object)(object)gui.m_takeAllButton == (Object)null || (Object)(object)gui.m_container == (Object)null)
			{
				return;
			}
			RectTransform val = (((Object)(object)gui.m_stackAllButton != (Object)null) ? ((Component)gui.m_stackAllButton).GetComponent<RectTransform>() : null);
			RectTransform val2 = (RectTransform)(((Object)(object)gui.m_containerWeight != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && !((Object)(object)((Transform)val2).parent != (Object)(object)((Transform)val).parent))
			{
				Rect rect = val.rect;
				float height = ((Rect)(ref rect)).height;
				rect = val2.rect;
				Vector2 sizeDelta = default(Vector2);
				((Vector2)(ref sizeDelta))..ctor(((Rect)(ref rect)).width, height);
				float y = val2.anchoredPosition.y;
				float num = 1f - val2.pivot.y;
				rect = val2.rect;
				float num2 = y + num * ((Rect)(ref rect)).height + 6f + height * 0.5f;
				s_containerSortHome = new Vector2(val2.anchoredPosition.x, num2);
				s_containerSortAllHome = new Vector2(val2.anchoredPosition.x, num2 + height + 6f);
				object obj = <>O.<0>__SortOpenContainer;
				if (obj == null)
				{
					UnityAction val3 = WasteBin.SortOpenContainer;
					<>O.<0>__SortOpenContainer = val3;
					obj = (object)val3;
				}
				s_containerSort = MakeContainerButton(gui, val2, "CarturSortContainerButton", "Sort", (UnityAction)obj, s_containerSortHome, sizeDelta);
				object obj2 = <>O.<1>__SortAllContainers;
				if (obj2 == null)
				{
					UnityAction val4 = WasteBin.SortAllContainers;
					<>O.<1>__SortAllContainers = val4;
					obj2 = (object)val4;
				}
				s_containerSortAll = MakeContainerButton(gui, val2, "CarturSortAllContainerButton", "Sort All", (UnityAction)obj2, s_containerSortAllHome, sizeDelta);
				RectTransform component = ((Component)gui.m_takeAllButton).GetComponent<RectTransform>();
				RectTransform val5 = (((Object)(object)gui.m_dropButton != (Object)null) ? ((Component)gui.m_dropButton).GetComponent<RectTransform>() : null);
				ManualLogSource log = Plugin.Log;
				string[] array = new string[21];
				array[0] = "container sort buttons at ";
				Vector2 val6 = s_containerSortHome;
				array[1] = ((object)(*(Vector2*)(&val6))/*cast due to .constrained prefix*/).ToString();
				array[2] = " and ";
				val6 = s_containerSortAllHome;
				array[3] = ((object)(*(Vector2*)(&val6))/*cast due to .constrained prefix*/).ToString();
				array[4] = " size ";
				rect = ((RectTransform)s_containerSort.transform).rect;
				array[5] = ((object)((Rect)(ref rect)).size/*cast due to .constrained prefix*/).ToString();
				array[6] = "  (place stacks ";
				array[7] = ((object)val.anchoredPosition/*cast due to .constrained prefix*/).ToString();
				array[8] = " size ";
				rect = val.rect;
				array[9] = ((object)((Rect)(ref rect)).size/*cast due to .constrained prefix*/).ToString();
				array[10] = " anchors ";
				array[11] = ((object)val.anchorMin/*cast due to .constrained prefix*/).ToString();
				array[12] = "-";
				array[13] = ((object)val.anchorMax/*cast due to .constrained prefix*/).ToString();
				array[14] = " pivot ";
				array[15] = ((object)val.pivot/*cast due to .constrained prefix*/).ToString();
				array[16] = ", take all ";
				array[17] = (((Object)(object)component != (Object)null) ? ((object)component.anchoredPosition/*cast due to .constrained prefix*/).ToString() : "?");
				array[18] = ", drop ";
				array[19] = (((Object)(object)val5 != (Object)null) ? ((object)val5.anchoredPosition/*cast due to .constrained prefix*/).ToString() : "none");
				array[20] = ")";
				log.LogInfo((object)string.Concat(array));
			}
		}

		private static GameObject MakeContainerButton(InventoryGui gui, RectTransform stackAll, string name, string caption, UnityAction onClick, Vector2 home, Vector2 sizeDelta)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(((Component)gui.m_takeAllButton).gameObject, ((Transform)stackAll).parent);
			((Object)val).name = name;
			val.SetActive(true);
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = stackAll.anchorMin;
			val2.anchorMax = stackAll.anchorMax;
			val2.pivot = stackAll.pivot;
			val2.sizeDelta = sizeDelta;
			val2.anchoredPosition = home;
			TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].text = caption;
			}
			Button component = val.GetComponent<Button>();
			((UnityEventBase)component.onClick).RemoveAllListeners();
			((UnityEvent)component.onClick).AddListener(onClick);
			return val;
		}

		private static GameObject BuildCan(RectTransform parent, Vector2 pos)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_007e: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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_00e5: Expected O, but got Unknown
			//IL_00d4: 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_00df: Expected O, but got Unknown
			GameObject val = new GameObject("CarturTrashCan", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Button)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)parent, false);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0.5f, 0.5f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.sizeDelta = new Vector2(54f, 54f);
			val2.anchoredPosition = pos;
			Image component = val.GetComponent<Image>();
			component.sprite = Plugin.CanSprite;
			component.preserveAspect = true;
			Button component2 = val.GetComponent<Button>();
			((Selectable)component2).targetGraphic = (Graphic)(object)component;
			ButtonClickedEvent onClick = component2.onClick;
			object obj = <>O.<2>__DropCarriedItem;
			if (obj == null)
			{
				UnityAction val4 = WasteBin.DropCarriedItem;
				<>O.<2>__DropCarriedItem = val4;
				obj = (object)val4;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			return val;
		}

		private static GameObject BuildSort(InventoryGui gui, RectTransform parent, Vector2 pos)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			if ((Object)(object)gui.m_takeAllButton == (Object)null)
			{
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(((Component)gui.m_takeAllButton).gameObject, (Transform)(object)parent);
			((Object)val).name = "CarturSortButton";
			val.SetActive(true);
			RectTransform val2 = (RectTransform)val.transform;
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0.5f, 0.5f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.sizeDelta = new Vector2(54f, 30f);
			val2.anchoredPosition = pos;
			TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].text = "Sort";
			}
			Button component = val.GetComponent<Button>();
			((UnityEventBase)component.onClick).RemoveAllListeners();
			ButtonClickedEvent onClick = component.onClick;
			object obj = <>O.<3>__SortPlayerInventory;
			if (obj == null)
			{
				UnityAction val4 = WasteBin.SortPlayerInventory;
				<>O.<3>__SortPlayerInventory = val4;
				obj = (object)val4;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			return val;
		}
	}
	internal static class WasteBin
	{
		private static readonly FieldInfo DragItem = AccessTools.Field(typeof(InventoryGui), "m_dragItem");

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

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

		private static readonly MethodInfo SetupDragItem = AccessTools.Method(typeof(InventoryGui), "SetupDragItem", (Type[])null, (Type[])null);

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

		private static readonly Type RarityType = FindType("EpicLoot.ItemRarity");

		private static readonly Type EnchantCostsType = FindType("EpicLoot.Crafting.EnchantCostsHelper");

		private static readonly Type EpicLootApi = FindType("EpicLoot.API");

		private static readonly Type ItemAmountType = FindType("EpicLoot.Crafting.ItemAmountConfig");

		private static readonly MethodInfo EnchantCostFor = ((RarityType == null || EnchantCostsType == null) ? null : AccessTools.Method(EnchantCostsType, "GetEnchantCost", new Type[2]
		{
			typeof(ItemData),
			RarityType
		}, (Type[])null));

		private static readonly MethodInfo SacrificeProductsFor = ((EnchantCostsType == null) ? null : AccessTools.Method(EnchantCostsType, "GetSacrificeProducts", new Type[1] { typeof(ItemData) }, (Type[])null));

		private static readonly MethodInfo IsMagicItem = ((EpicLootApi == null) ? null : AccessTools.Method(EpicLootApi, "IsMagicItem", new Type[1] { typeof(ItemData) }, (Type[])null));

		private static readonly MethodInfo IsUnidentifiedItem = ((EpicLootApi == null) ? null : AccessTools.Method(EpicLootApi, "IsUnidentified", new Type[1] { typeof(ItemData) }, (Type[])null));

		private static readonly MethodInfo TryGetRarity = ((EpicLootApi == null) ? null : AccessTools.Method(EpicLootApi, "TryGetRarity", new Type[2]
		{
			typeof(ItemData),
			typeof(int).MakeByRefType()
		}, (Type[])null));

		private static readonly FieldInfo CostItem = ((ItemAmountType == null) ? null : AccessTools.Field(ItemAmountType, "Item"));

		private static readonly FieldInfo CostAmount = ((ItemAmountType == null) ? null : AccessTools.Field(ItemAmountType, "Amount"));

		private static readonly Type SlotsType = FindType("CarturUIHud.Slots") ?? FindType("CarturRuneUI.Slots");

		private static readonly MethodInfo VisibleRowsGetter = ((SlotsType != null) ? AccessTools.PropertyGetter(SlotsType, "VisibleRows") : null);

		private static bool s_boundaryLogged;

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

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

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

		private static readonly FieldInfo ContainerWagon = AccessTools.Field(typeof(Container), "m_wagon");

		private static readonly FieldInfo ContainerNview = AccessTools.Field(typeof(Container), "m_nview");

		private static void NotifyChanged(Inventory inv)
		{
			if (inv != null)
			{
				InventoryChanged?.Invoke(inv, new object[2] { false, false });
			}
		}

		internal static void DropCarriedItem()
		{
			InventoryGui instance = InventoryGui.instance;
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)localPlayer == (Object)null) && !((Character)localPlayer).IsTeleporting())
			{
				object? obj = DragItem?.GetValue(instance);
				ItemData val = (ItemData)((obj is ItemData) ? obj : null);
				object? obj2 = DragInventory?.GetValue(instance);
				Inventory val2 = (Inventory)((obj2 is Inventory) ? obj2 : null);
				if (val != null && val2 != null && val2.ContainsItem(val))
				{
					int amount = Mathf.Clamp((DragAmount?.GetValue(instance) is int num) ? num : val.m_stack, 1, val.m_stack);
					Recycle(localPlayer, val2, val, amount);
					SetupDragItem?.Invoke(instance, new object[3] { null, null, 0 });
					NotifyChanged(val2);
				}
			}
		}

		private static void Recycle(Player player, Inventory from, ItemData item, int amount)
		{
			Recipe val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetRecipe(item) : null);
			int num = (((Object)(object)val != (Object)null) ? Mathf.Max(1, val.m_amount) : 0);
			int num2 = (((Object)(object)val != (Object)null) ? (amount / num) : 0);
			int quality = item.m_quality;
			if (item.m_equipped)
			{
				((Humanoid)player).UnequipItem(item, false);
			}
			if (amount >= item.m_stack)
			{
				from.RemoveItem(item);
			}
			else
			{
				from.RemoveItem(item, amount);
			}
			if (num2 > 0)
			{
				Requirement[] resources = val.m_resources;
				foreach (Requirement val2 in resources)
				{
					if (val2 != null && !((Object)(object)val2.m_resItem == (Object)null) && val2.m_recover)
					{
						int num3 = Half(CostUpTo(val2, quality) * num2);
						if (num3 > 0)
						{
							Give(player, ((Component)val2.m_resItem).gameObject, num3);
							Plugin.Log.LogDebug((object)$"returned {num3} {((Object)((Component)val2.m_resItem).gameObject).name}");
						}
					}
				}
			}
			GiveEpicLootRefund(player, item, amount);
		}

		private static int CostUpTo(Requirement req, int quality)
		{
			int num = 0;
			for (int i = 1; i <= Mathf.Max(1, quality); i++)
			{
				num += req.GetAmount(i);
			}
			return num;
		}

		private static int Half(int n)
		{
			return (n + 1) / 2;
		}

		private static void Give(Player player, GameObject prefab, int amount)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			if (amount <= 0 || (Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
			{
				return;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			string name = component.m_itemData.m_shared.m_name;
			int num = Mathf.Max(1, component.m_itemData.m_shared.m_maxStackSize);
			int num2 = inventory.CountItems(name, -1, false);
			int num3 = amount;
			while (num3 > 0 && inventory.AddItem(prefab, Mathf.Min(num3, num)))
			{
				num3 -= num;
			}
			int num4 = amount - (inventory.CountItems(name, -1, false) - num2);
			if (num4 > 0)
			{
				Vector3 val = ((Component)player).transform.position + ((Component)player).transform.forward;
				while (num4 > 0)
				{
					ItemData obj = component.m_itemData.Clone();
					obj.m_dropPrefab = prefab;
					ItemDrop.DropItem(obj, Mathf.Min(num4, num), val, Quaternion.identity);
					num4 -= num;
				}
			}
		}

		private static Type FindType(string fullName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type type;
				try
				{
					type = assembly.GetType(fullName, throwOnError: false);
				}
				catch (Exception)
				{
					continue;
				}
				if (type != null)
				{
					return type;
				}
			}
			return null;
		}

		private static void GiveEpicLootRefund(Player player, ItemData item, int amount)
		{
			if (EnchantCostFor == null || SacrificeProductsFor == null || IsMagicItem == null || IsUnidentifiedItem == null || TryGetRarity == null || CostItem == null || CostAmount == null)
			{
				return;
			}
			bool flag5;
			IEnumerable enumerable;
			try
			{
				object obj = IsMagicItem.Invoke(null, new object[1] { item });
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				bool flag2 = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				obj = IsUnidentifiedItem.Invoke(null, new object[1] { item });
				bool flag3 = default(bool);
				int num2;
				if (obj is bool)
				{
					flag3 = (bool)obj;
					num2 = 1;
				}
				else
				{
					num2 = 0;
				}
				bool flag4 = (byte)((uint)num2 & (flag3 ? 1u : 0u)) != 0;
				flag5 = flag2 && !flag4;
				if (flag5)
				{
					object[] array = new object[2] { item, 0 };
					obj = TryGetRarity.Invoke(null, array);
					if (!(obj is bool) || !(bool)obj)
					{
						return;
					}
					object obj2 = Enum.ToObject(RarityType, array[1]);
					enumerable = EnchantCostFor.Invoke(null, new object[2] { item, obj2 }) as IEnumerable;
				}
				else
				{
					enumerable = SacrificeProductsFor.Invoke(null, new object[1] { item }) as IEnumerable;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("EpicLoot cost lookup threw, no magic materials given. " + ex.Message));
				return;
			}
			if (enumerable == null)
			{
				return;
			}
			foreach (object item2 in enumerable)
			{
				string text = CostItem.GetValue(item2) as string;
				int num3 = ((CostAmount.GetValue(item2) is int num4) ? num4 : 0) * amount;
				if (flag5)
				{
					num3 = Half(num3);
				}
				if (num3 > 0 && !string.IsNullOrEmpty(text))
				{
					GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(text) : null);
					if ((Object)(object)val == (Object)null)
					{
						Plugin.Log.LogWarning((object)("EpicLoot material is not in the ObjectDB: " + text));
						continue;
					}
					Give(player, val, num3);
					Plugin.Log.LogDebug((object)$"refunded {num3} {text}");
				}
			}
		}

		private static int VisibleRows(Inventory inv)
		{
			if (VisibleRowsGetter != null && VisibleRowsGetter.Invoke(null, null) is int num && num > 0)
			{
				return num;
			}
			return inv.GetHeight();
		}

		private static int PlaceableRows(Inventory inv)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer != (Object)null) || inv != ((Humanoid)localPlayer).GetInventory())
			{
				return inv.GetHeight();
			}
			return VisibleRows(inv);
		}

		internal static void SortPlayerInventory()
		{
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting())
			{
				return;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			int num = VisibleRows(inventory);
			if (!s_boundaryLogged)
			{
				s_boundaryLogged = true;
				Plugin.Log.LogInfo((object)("sort covers rows 1-" + (num - 1) + " of " + num + " visible (" + ((VisibleRowsGetter != null) ? ("row count from " + SlotsType.FullName) : "no slot mod found, using the grid height") + ")"));
			}
			List<ItemData> list = new List<ItemData>();
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem.m_gridPos.y > 0 && allItem.m_gridPos.y < num)
				{
					list.Add(allItem);
				}
			}
			MergeStacks(inventory, list);
			list.Sort(Compare);
			int width = inventory.GetWidth();
			int num2 = width * (num - 1);
			for (int i = 0; i < list.Count && i < num2; i++)
			{
				list[i].m_gridPos = new Vector2i(i % width, 1 + i / width);
			}
			if (list.Count > num2)
			{
				Plugin.Log.LogWarning((object)$"sort placed {num2} of {list.Count} bag stacks; the rest were left where they were.");
			}
			NotifyChanged(inventory);
		}

		internal static void SortOpenContainer()
		{
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsContainerOpen())
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !((Character)localPlayer).IsTeleporting())
			{
				object? obj = CurrentContainer?.GetValue(instance);
				Container val = (Container)((obj is Container) ? obj : null);
				if (!((Object)(object)val == (Object)null))
				{
					SortOne(val, gather: true);
				}
			}
		}

		internal static void QuickDeposit()
		{
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: 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)
			Player localPlayer = Player.m_localPlayer;
			float value = Plugin.GatherRange.Value;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || ((Character)localPlayer).IsTeleporting() || value <= 0f || (Object)(object)Game.instance == (Object)null || Typing())
			{
				return;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			InventoryGui instance = InventoryGui.instance;
			Container val = (Container)(((Object)(object)instance != (Object)null && instance.IsContainerOpen()) ? /*isinst with value type is only supported in some contexts*/: null);
			ItemData val2 = (ItemData)(((Object)(object)instance != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
			Vector3 at = ((Component)localPlayer).transform.position;
			float rangeSq = value * value;
			int num = VisibleRows(inventory);
			List<Container> list = new List<Container>();
			if ((Object)(object)val != (Object)null && !IsVessel(val))
			{
				list.Add(val);
			}
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container val3 in array)
			{
				if ((Object)(object)val3 != (Object)null && (Object)(object)val3 != (Object)(object)val && Reachable(val3, at, rangeSq, playerID))
				{
					list.Add(val3);
				}
			}
			list.Sort((Container a, Container b) => Vector3.SqrMagnitude(((Component)a).transform.position - at).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - at)));
			int num2 = 0;
			foreach (Container item in list)
			{
				Inventory inventory2 = item.GetInventory();
				if (inventory2 == null)
				{
					continue;
				}
				HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
				foreach (ItemData allItem in inventory2.GetAllItems())
				{
					if (allItem?.m_shared != null)
					{
						hashSet.Add(allItem.m_shared.m_name);
					}
				}
				bool flag = false;
				foreach (ItemData item2 in new List<ItemData>(inventory.GetAllItems()))
				{
					if (item2?.m_shared != null && !item2.m_equipped && item2 != val2 && item2.m_gridPos.y >= 1 && item2.m_gridPos.y < num && hashSet.Contains(item2.m_shared.m_name))
					{
						int stack = item2.m_stack;
						MoveOne(inventory2, inventory, item2);
						if (item2.m_stack < stack)
						{
							num2 += stack - item2.m_stack;
							flag = true;
						}
					}
				}
				if (flag)
				{
					object? obj = ContainerNview?.GetValue(item);
					object? obj2 = ((obj is ZNetView) ? obj : null);
					if (obj2 != null)
					{
						((ZNetView)obj2).ClaimOwnership();
					}
					ContainerSave?.Invoke(item, null);
					NotifyChanged(inventory2);
				}
			}
			if (num2 > 0)
			{
				NotifyChanged(inventory);
			}
			((Character)localPlayer).Message((MessageType)1, (num2 > 0) ? $"Deposited {num2} items" : "Nothing to deposit", 0, (Sprite)null, false);
		}

		private static bool Typing()
		{
			if (((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || TextInput.IsVisible() || Menu.IsVisible() || Minimap.InTextInput())
			{
				return true;
			}
			GameObject val = (((Object)(object)EventSystem.current != (Object)null) ? EventSystem.current.currentSelectedGameObject : null);
			if ((Object)(object)val != (Object)null)
			{
				TMP_InputField component = val.GetComponent<TMP_InputField>();
				if (component == null || !component.isFocused)
				{
					InputField component2 = val.GetComponent<InputField>();
					if (component2 == null)
					{
						return false;
					}
					return component2.isFocused;
				}
				return true;
			}
			return false;
		}

		internal static void SortAllContainers()
		{
			//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_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsContainerOpen())
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting())
			{
				return;
			}
			object? obj = CurrentContainer?.GetValue(instance);
			Container val = (Container)((obj is Container) ? obj : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float value = Plugin.GatherRange.Value;
			if (value <= 0f)
			{
				SortOne(val, gather: false);
				return;
			}
			long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
			Vector3 at = ((Component)val).transform.position;
			float num = value * value;
			if (IsVessel(val))
			{
				SortOne(val, gather: false);
				return;
			}
			List<Container> list = new List<Container>(32) { val };
			int num2 = 0;
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2 == (Object)(object)val))
				{
					Vector3 val3 = ((Component)val2).transform.position - at;
					if (((Vector3)(ref val3)).sqrMagnitude <= num && IsVessel(val2))
					{
						num2++;
					}
					else if (Reachable(val2, at, num, playerID))
					{
						list.Add(val2);
					}
				}
			}
			list.Sort((Container a, Container b) => Vector3.SqrMagnitude(((Component)a).transform.position - at).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - at)));
			int num3 = Consolidate(list);
			foreach (Container item in list)
			{
				if ((Object)(object)item != (Object)null)
				{
					SortOne(item, gather: false);
				}
			}
			Plugin.Log.LogInfo((object)($"sort all tidied {list.Count} chest(s) within {value:0.#}m, moving {num3} stack(s)" + ((num2 > 0) ? $"; left {num2} boat/cart hold(s) alone." : ".")));
		}

		private static int Consolidate(List<Container> inRange)
		{
			Dictionary<Container, Dictionary<string, int>> dictionary = new Dictionary<Container, Dictionary<string, int>>();
			Dictionary<string, Container> dictionary2 = new Dictionary<string, Container>(StringComparer.Ordinal);
			Dictionary<string, int> dictionary3 = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (Container item in inRange)
			{
				Inventory inventory = item.GetInventory();
				if (inventory == null)
				{
					continue;
				}
				Dictionary<string, int> dictionary4 = new Dictionary<string, int>(StringComparer.Ordinal);
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem?.m_shared != null)
					{
						string name = allItem.m_shared.m_name;
						dictionary4[name] = allItem.m_stack + (dictionary4.TryGetValue(name, out var value) ? value : 0);
					}
				}
				dictionary[item] = dictionary4;
				foreach (KeyValuePair<string, int> item2 in dictionary4)
				{
					if (!dictionary2.TryGetValue(item2.Key, out var _) || item2.Value > dictionary3[item2.Key])
					{
						dictionary2[item2.Key] = item;
						dictionary3[item2.Key] = item2.Value;
					}
				}
			}
			int num = 0;
			foreach (KeyValuePair<string, Container> item3 in dictionary2)
			{
				Inventory inventory2 = item3.Value.GetInventory();
				if (inventory2 == null)
				{
					continue;
				}
				foreach (Container item4 in inRange)
				{
					if ((Object)(object)item4 == (Object)(object)item3.Value || !dictionary.TryGetValue(item4, out var value3) || !value3.ContainsKey(item3.Key))
					{
						continue;
					}
					Inventory inventory3 = item4.GetInventory();
					if (inventory3 == null)
					{
						continue;
					}
					bool flag = false;
					foreach (ItemData item5 in new List<ItemData>(inventory3.GetAllItems()))
					{
						if (item5?.m_shared != null && !(item5.m_shared.m_name != item3.Key) && MoveOne(inventory2, inventory3, item5))
						{
							flag = true;
							num++;
						}
					}
					if (flag)
					{
						object? obj = ContainerNview?.GetValue(item4);
						object? obj2 = ((obj is ZNetView) ? obj : null);
						if (obj2 != null)
						{
							((ZNetView)obj2).ClaimOwnership();
						}
						ContainerSave?.Invoke(item4, null);
						NotifyChanged(inventory3);
					}
				}
			}
			return num;
		}

		private static void SortOne(Container container, bool gather)
		{
			//IL_0015: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = container.GetInventory();
			if (inventory != null)
			{
				if (gather)
				{
					GatherLikeItems(inventory, ((Component)container).transform.position, container);
				}
				List<ItemData> list = new List<ItemData>(inventory.GetAllItems());
				MergeStacks(inventory, list);
				list.Sort(Compare);
				int width = inventory.GetWidth();
				int num = width * inventory.GetHeight();
				for (int i = 0; i < list.Count && i < num; i++)
				{
					list[i].m_gridPos = new Vector2i(i % width, i / width);
				}
				if (list.Count > num)
				{
					Plugin.Log.LogWarning((object)$"placed {num} of {list.Count} stacks in {Utils.GetPrefabName(((Component)container).gameObject)}; the rest were left where they were.");
				}
				object? obj = ContainerNview?.GetValue(container);
				object? obj2 = ((obj is ZNetView) ? obj : null);
				if (obj2 != null)
				{
					((ZNetView)obj2).ClaimOwnership();
				}
				ContainerSave?.Invoke(container, null);
				NotifyChanged(inventory);
			}
		}

		private static void GatherLikeItems(Inventory inv, Vector3 at, Container skip)
		{
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			int num = PlaceableRows(inv);
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (ItemData allItem in inv.GetAllItems())
			{
				if (allItem?.m_shared != null && !allItem.m_equipped && allItem.m_gridPos.y < num)
				{
					hashSet.Add(allItem.m_shared.m_name);
				}
			}
			float value = Plugin.GatherRange.Value;
			if (hashSet.Count == 0 || value <= 0f || (Object)(object)Game.instance == (Object)null)
			{
				return;
			}
			long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
			float rangeSq = value * value;
			int num2 = 0;
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container val in array)
			{
				if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)skip || !Reachable(val, at, rangeSq, playerID))
				{
					continue;
				}
				Inventory inventory = val.GetInventory();
				if (inventory == null)
				{
					continue;
				}
				bool flag = false;
				foreach (ItemData item in new List<ItemData>(inventory.GetAllItems()))
				{
					if (item?.m_shared != null && hashSet.Contains(item.m_shared.m_name) && MoveOne(inv, inventory, item))
					{
						flag = true;
						num2++;
					}
				}
				if (flag)
				{
					object? obj = ContainerNview?.GetValue(val);
					object? obj2 = ((obj is ZNetView) ? obj : null);
					if (obj2 != null)
					{
						((ZNetView)obj2).ClaimOwnership();
					}
					ContainerSave?.Invoke(val, null);
					NotifyChanged(inventory);
				}
			}
			if (num2 > 0)
			{
				Plugin.Log.LogInfo((object)$"sort gathered {num2} stack(s) from the chests within {value:0.#}m.");
			}
		}

		private static bool MoveOne(Inventory to, Inventory from, ItemData item)
		{
			if (to == null || from == null || item?.m_shared == null)
			{
				return false;
			}
			bool result = false;
			while (item.m_stack > 0)
			{
				int stack = item.m_stack;
				MoveSome(to, from, item);
				if (item.m_stack >= stack)
				{
					break;
				}
				result = true;
			}
			return result;
		}

		private static void MoveSome(Inventory to, Inventory from, ItemData item)
		{
			ItemData val = null;
			int num = 0;
			int num2 = PlaceableRows(to);
			foreach (ItemData allItem in to.GetAllItems())
			{
				if (allItem != null && allItem.m_shared != null && allItem.m_stack < allItem.m_shared.m_maxStackSize && allItem.m_gridPos.y < num2 && SameStack(allItem, item))
				{
					int num3 = allItem.m_shared.m_maxStackSize - allItem.m_stack;
					if (val == null || num3 > num)
					{
						val = allItem;
						num = num3;
					}
				}
			}
			if (val != null)
			{
				to.MoveItemToThis(from, item, Mathf.Min(num, item.m_stack), val.m_gridPos.x, val.m_gridPos.y);
				return;
			}
			int num4 = PlaceableRows(to);
			for (int i = 0; i < num4; i++)
			{
				for (int j = 0; j < to.GetWidth(); j++)
				{
					if (to.GetItemAt(j, i) == null)
					{
						to.MoveItemToThis(from, item, Mathf.Min(item.m_stack, item.m_shared.m_maxStackSize), j, i);
						return;
					}
				}
			}
		}

		private static bool IsVessel(Container other)
		{
			object? obj = ContainerWagon?.GetValue(other);
			if (!((Object)((obj is Vagon) ? obj : null) != (Object)null) && !((Object)(object)((Component)other).GetComponentInParent<Vagon>() != (Object)null))
			{
				return (Object)(object)((Component)other).GetComponentInParent<Ship>() != (Object)null;
			}
			return true;
		}

		private static bool Reachable(Container other, Vector3 at, float rangeSq, long playerId)
		{
			//IL_0006: 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_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_00d9: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)other).transform.position - at;
			if (((Vector3)(ref val)).sqrMagnitude > rangeSq)
			{
				return false;
			}
			object? obj = ContainerNview?.GetValue(other);
			object? obj2 = ((obj is ZNetView) ? obj : null);
			ZDO val2 = ((obj2 != null) ? ((ZNetView)obj2).GetZDO() : null);
			if (val2 != null && val2.GetInt(ZDOVars.s_inUse, 0) == 1)
			{
				return false;
			}
			if (IsVessel(other))
			{
				return false;
			}
			if ((Object)(object)((Component)other).GetComponentInParent<Player>() != (Object)null)
			{
				return false;
			}
			if ((Object)(object)((Component)other).GetComponent<TombStone>() != (Object)null)
			{
				return false;
			}
			Piece component = ((Component)other).GetComponent<Piece>();
			if ((Object)(object)component == (Object)null || !component.IsPlacedByPlayer())
			{
				return false;
			}
			object obj3 = ContainerCheckAccess?.Invoke(other, new object[1] { playerId });
			if (!(obj3 is bool) || !(bool)obj3)
			{
				return false;
			}
			return PrivateArea.CheckAccess(((Component)other).transform.position, 0f, false, true);
		}

		private static void MergeStacks(Inventory inv, List<ItemData> items)
		{
			List<ItemData> list = null;
			for (int i = 0; i < items.Count; i++)
			{
				ItemData val = items[i];
				if (val.m_stack <= 0)
				{
					continue;
				}
				for (int j = i + 1; j < items.Count; j++)
				{
					if (val.m_stack >= val.m_shared.m_maxStackSize)
					{
						break;
					}
					ItemData val2 = items[j];
					if (val2.m_stack > 0 && !val2.m_equipped && SameStack(val, val2))
					{
						int num = Mathf.Min(val2.m_stack, val.m_shared.m_maxStackSize - val.m_stack);
						val.m_stack += num;
						val2.m_stack -= num;
						if (val2.m_stack == 0)
						{
							(list ?? (list = new List<ItemData>())).Add(val2);
						}
					}
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (ItemData item in list)
			{
				inv.RemoveItem(item);
				items.Remove(item);
			}
		}

		private static bool SameStack(ItemData a, ItemData b)
		{
			if (a.m_shared.m_maxStackSize > 1 && 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;
		}

		private static int Compare(ItemData a, ItemData b)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			ref ItemType itemType = ref a.m_shared.m_itemType;
			object target = b.m_shared.m_itemType;
			int num = ((Enum)Unsafe.As<ItemType, ItemType>(ref itemType)/*cast due to .constrained prefix*/).CompareTo(target);
			if (num != 0)
			{
				return num;
			}
			int num2 = string.Compare(a.m_shared.m_name, b.m_shared.m_name, StringComparison.Ordinal);
			if (num2 == 0)
			{
				return b.m_quality.CompareTo(a.m_quality);
			}
			return num2;
		}
	}
}