Decompiled source of HearthSort v0.1.17

BepInEx/plugins/HearthSort/HearthSort.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using HearthSort.Core;
using Jotunn.Managers;
using Jotunn.Utils;
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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HearthSort")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.17.0")]
[assembly: AssemblyInformationalVersion("0.1.17")]
[assembly: AssemblyProduct("HearthSort")]
[assembly: AssemblyTitle("HearthSort")]
[assembly: AssemblyVersion("0.1.17.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 HearthSort
{
	internal sealed class ChestWindow
	{
		private sealed class Row
		{
			internal GameObject Object;

			internal Image Icon;

			internal Image Background;

			internal Image Accent;

			internal Text Name;

			internal Text State;

			internal Toggle Accept;

			internal Button Delete;

			internal int Index;

			internal string Id;
		}

		private const float Width = 720f;

		private const float Height = 680f;

		private const float RowHeight = 76f;

		private const float ViewHeight = 326f;

		private const float RowWidth = 638f;

		private static readonly Vector2 TopLeft = new Vector2(0f, 1f);

		private static readonly Color Ink = new Color(0.95f, 0.92f, 0.83f);

		private static readonly Color Muted = new Color(0.77f, 0.75f, 0.69f);

		private static readonly Color Gold = new Color(0.94f, 0.73f, 0.36f);

		private Container observed;

		private Container target;

		private GameObject panel;

		private GameObject openButton;

		private GameObject backdrop;

		private GameObject tooltipPrefab;

		private Text count;

		private Text status;

		private Text empty;

		private Text modeHint;

		private Image modeAccent;

		private Toggle distributor;

		private ScrollRect scroll;

		private RectTransform content;

		private Rules rules;

		private string encoded;

		private readonly List<Row> pool = new List<Row>();

		private readonly List<string> ordered = new List<string>();

		private bool binding;

		private bool blocked;

		private float nextRefresh;

		internal int EscapeFrame = -1;

		internal bool IsOpen => Object.op_Implicit((Object)(object)panel);

		internal void Observe(Container chest)
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Expected O, but got Unknown
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: 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)
			Close();
			observed = chest;
			if (Object.op_Implicit((Object)(object)openButton))
			{
				Object.Destroy((Object)(object)openButton);
			}
			openButton = null;
			if (!GameState.Supported(chest) || !Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront) || !Object.op_Implicit((Object)(object)InventoryGui.instance))
			{
				return;
			}
			Plugin.Instance.Registry.Register(chest);
			object? value = AccessTools.Field(typeof(InventoryGui), "m_takeAllButton").GetValue(InventoryGui.instance);
			Button val = (Button)((value is Button) ? value : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				Button craftButton = InventoryGui.instance.m_craftButton;
				tooltipPrefab = ((!Object.op_Implicit((Object)(object)craftButton)) ? null : ((Component)craftButton).GetComponent<UITooltip>()?.m_tooltipPrefab);
				if (!Object.op_Implicit((Object)(object)tooltipPrefab))
				{
					tooltipPrefab = ((Component)val).GetComponent<UITooltip>()?.m_tooltipPrefab;
				}
				openButton = Object.Instantiate<GameObject>(((Component)val).gameObject, (Transform)(object)InventoryGui.instance.m_container, false);
				((Object)openButton).name = "HearthSort Chest Rules";
				Button component = openButton.GetComponent<Button>();
				component.onClick = new ButtonClickedEvent();
				((UnityEvent)component.onClick).AddListener(new UnityAction(Open));
				((Selectable)component).interactable = true;
				RectTransform component2 = openButton.GetComponent<RectTransform>();
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(1f, 1f);
				component2.anchorMax = val2;
				component2.anchorMin = val2;
				component2.pivot = new Vector2(0f, 1f);
				component2.anchoredPosition = new Vector2(10f, -10f);
				component2.sizeDelta = new Vector2(140f, 36f);
				Text componentInChildren = openButton.GetComponentInChildren<Text>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren))
				{
					componentInChildren.text = "Chest rules";
					componentInChildren.supportRichText = false;
				}
				TMP_Text componentInChildren2 = openButton.GetComponentInChildren<TMP_Text>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren2))
				{
					componentInChildren2.text = "Chest rules";
				}
				Tooltip(openButton, "Manage this chest's learned items.");
				openButton.SetActive(true);
			}
		}

		private void Open()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_00a9: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: 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_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0512: Unknown result type (might be due to invalid IL or missing references)
			//IL_054b: Unknown result type (might be due to invalid IL or missing references)
			//IL_057e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0604: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)observed) || (Object)(object)Patches.Current(InventoryGui.instance) != (Object)(object)observed || !Editable(observed) || !Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront))
			{
				return;
			}
			Close();
			target = observed;
			target.SetInUse(true);
			backdrop = new GameObject("Hearth Sort modal backdrop", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform component = backdrop.GetComponent<RectTransform>();
			((Transform)component).SetParent(GUIManager.CustomGUIFront.transform, false);
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			Vector2 offsetMin = (component.offsetMax = Vector2.zero);
			component.offsetMin = offsetMin;
			Image component2 = backdrop.GetComponent<Image>();
			((Graphic)component2).color = new Color(0f, 0f, 0f, 0.25f);
			((Graphic)component2).raycastTarget = true;
			panel = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, 720f, 680f, false);
			((Object)panel).name = "Hearth Sort Chest Rules";
			Surface(panel.transform, "Reading tint", 12f, 12f, 696f, 656f, new Color(0.1f, 0.08f, 0.055f, 0.48f));
			Label(panel.transform, "Chest rules", 32f, 25f, 470f, 42f, 30, Ink, bold: true, (TextAnchor)3);
			MakeButton(panel.transform, "Close", 600f, 30f, 88f, Close);
			Label(panel.transform, Localization.instance.Localize(target.m_name), 34f, 70f, 580f, 28f, 18, Gold, bold: false, (TextAnchor)3);
			Surface(panel.transform, "Header divider", 34f, 106f, 652f, 1f, new Color(Gold.r, Gold.g, Gold.b, 0.22f));
			Surface(panel.transform, "Header accent", 34f, 105f, 72f, 2f, new Color(Gold.r, Gold.g, Gold.b, 0.7f));
			Surface(panel.transform, "Chest mode inset", 32f, 120f, 656f, 78f, new Color(0.035f, 0.03f, 0.022f, 0.45f));
			modeAccent = Surface(panel.transform, "Chest mode accent", 32f, 120f, 3f, 78f, Muted);
			distributor = MakeToggle(panel.transform, 45f, 135f);
			Label(panel.transform, "Use as distributor", 92f, 128f, 560f, 34f, 20, Ink, bold: true, (TextAnchor)3);
			modeHint = Label(panel.transform, "", 92f, 165f, 560f, 24f, 15, Muted, bold: false, (TextAnchor)3);
			Tooltip(((Component)distributor).gameObject, "Send this chest's contents to nearby accepting chests when you close it.");
			((UnityEvent<bool>)(object)distributor.onValueChanged).AddListener((UnityAction<bool>)delegate(bool value)
			{
				if (!binding)
				{
					Edit(checked(delegate(Rules r)
					{
						r.Distributor = value;
						r.Revision++;
					}));
				}
			});
			Label(panel.transform, "ACCEPTED ITEMS", 34f, 212f, 330f, 26f, 15, Ink, bold: true, (TextAnchor)3);
			count = Label(panel.transform, "", 414f, 212f, 270f, 26f, 14, Muted, bold: false, (TextAnchor)5);
			Label(panel.transform, "Item", 112f, 242f, 380f, 20f, 13, Muted, bold: false, (TextAnchor)3);
			Label(panel.transform, "Accept", 554f, 242f, 56f, 20f, 13, Muted, bold: false, (TextAnchor)4);
			Label(panel.transform, "Forget", 616f, 242f, 52f, 20f, 13, Muted, bold: false, (TextAnchor)4);
			BuildScroll();
			Label(panel.transform, "Mouse wheel to scroll", 34f, 600f, 420f, 20f, 13, Muted, bold: false, (TextAnchor)3);
			Label(panel.transform, "Esc to close", 520f, 600f, 166f, 20f, 13, Muted, bold: false, (TextAnchor)5);
			Surface(panel.transform, "Footer divider", 34f, 625f, 652f, 1f, new Color(Gold.r, Gold.g, Gold.b, 0.18f));
			status = Label(panel.transform, "Toggle to pause acceptance. X forgets an item.", 34f, 636f, 652f, 24f, 14, Muted, bold: false, (TextAnchor)3);
			Read(force: true);
			Scale();
			GUIManager.BlockInput(true);
			blocked = true;
			EventSystem current = EventSystem.current;
			if (current != null)
			{
				current.SetSelectedGameObject(((Component)distributor).gameObject);
			}
		}

		internal void Close()
		{
			if (Object.op_Implicit((Object)(object)panel))
			{
				Object.Destroy((Object)(object)panel);
			}
			if (Object.op_Implicit((Object)(object)backdrop))
			{
				Object.Destroy((Object)(object)backdrop);
			}
			backdrop = null;
			panel = null;
			target = null;
			pool.Clear();
			ordered.Clear();
			scroll = null;
			content = null;
			rules = null;
			modeHint = null;
			modeAccent = null;
			if (blocked)
			{
				GUIManager.BlockInput(false);
			}
			blocked = false;
			EscapeFrame = Time.frameCount;
		}

		internal void Update()
		{
			//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)
			if (Object.op_Implicit((Object)(object)observed) && (!Object.op_Implicit((Object)(object)InventoryGui.instance) || (Object)(object)Patches.Current(InventoryGui.instance) != (Object)(object)observed))
			{
				Observe(null);
			}
			if (!Object.op_Implicit((Object)(object)panel))
			{
				if (Object.op_Implicit((Object)(object)observed) && Input.GetKeyDown((KeyCode)289))
				{
					Open();
				}
				return;
			}
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || ((Character)Player.m_localPlayer).IsDead() || !Object.op_Implicit((Object)(object)target) || !Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront) || !Editable(target) || Vector3.Distance(((Component)Player.m_localPlayer).transform.position, ((Component)target).transform.position) > 5f)
			{
				Close();
				return;
			}
			if (Input.GetKeyDown((KeyCode)27) || ZInput.GetButtonDown("JoyButtonB"))
			{
				Close();
				return;
			}
			Scale();
			if (Time.unscaledTime >= nextRefresh)
			{
				nextRefresh = Time.unscaledTime + 0.25f;
				Read(force: false);
			}
		}

		private static bool Editable(Container c)
		{
			if (GameState.Supported(c) && c.IsOwner() && GameState.LocalAccess(c))
			{
				return !Patches.Locked(c);
			}
			return false;
		}

		private void Scale()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = GUIManager.CustomGUIFront.GetComponent<RectTransform>().rect;
			panel.transform.localScale = Vector3.one * Mathf.Min(1f, Mathf.Min(((Rect)(ref rect)).width / 744f, ((Rect)(ref rect)).height / 704f));
		}

		private void Read(bool force)
		{
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: 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_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			string text = GameState.Encoded(GameState.Data(target));
			if (!force && text == encoded)
			{
				return;
			}
			try
			{
				rules = Rules.Decode(text);
				encoded = text;
				ordered.Clear();
				ordered.AddRange(rules.Items.Keys.OrderBy<string, string>(Name, StringComparer.CurrentCultureIgnoreCase).ThenBy<string, string>((string id) => id, StringComparer.Ordinal));
				binding = true;
				distributor.SetIsOnWithoutNotify(rules.Distributor);
				binding = false;
				modeHint.text = (rules.Distributor ? "Distributes to nearby accepting chests when closed." : "Receives items matching the enabled rules below.");
				((Graphic)modeAccent).color = (Color)(rules.Distributor ? Gold : new Color(0.55f, 0.49f, 0.36f, 0.7f));
				count.text = ordered.Count + " entries";
				((Component)empty).gameObject.SetActive(ordered.Count == 0);
				content.sizeDelta = new Vector2(638f, Mathf.Max(314f, (float)ordered.Count * 76f));
				Rect rect = content.rect;
				float height = ((Rect)(ref rect)).height;
				rect = scroll.viewport.rect;
				float num = Mathf.Max(0f, height - ((Rect)(ref rect)).height);
				content.anchoredPosition = new Vector2(0f, Mathf.Clamp(content.anchoredPosition.y, 0f, num));
				scroll.StopMovement();
				Render();
			}
			catch (Exception e)
			{
				binding = false;
				status.text = "Chest rules could not be read. Saved data was preserved.";
				Plugin.Instance.Error("Acceptance list", e);
			}
		}

		private bool Edit(Action<Rules> change)
		{
			if (!Editable(target))
			{
				status.text = "Chest ownership changed. Reopen chest rules to edit.";
				return false;
			}
			ZDO val = GameState.Data(target);
			if (GameState.Encoded(val) != encoded)
			{
				Read(force: true);
				status.text = "Rules changed. Please try again.";
				return false;
			}
			try
			{
				Rules rules = Rules.Decode(encoded);
				change(rules);
				string text = rules.Encode();
				val.Set("hearthsort.rules.v1", text);
				if (GameState.Encoded(val) != text)
				{
					throw new InvalidOperationException("Rule write did not persist.");
				}
				Plugin.Instance.Network.Publish(val);
				Read(force: true);
				return true;
			}
			catch (Exception e)
			{
				Read(force: true);
				status.text = "Could not save that edit. Please try again.";
				Plugin.Instance.Error("Rule edit", e);
				return false;
			}
		}

		private void BuildScroll()
		{
			//IL_0038: 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_00a0: 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_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: 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)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_0567: Unknown result type (might be due to invalid IL or missing references)
			Image val = Surface(panel.transform, "Inset border", 28f, 264f, 664f, 326f, new Color(0.43f, 0.36f, 0.23f, 0.8f));
			Surface(((Component)val).transform, "Inset", 1f, 1f, 662f, 324f, new Color(0.055f, 0.048f, 0.035f, 0.98f));
			Image val2 = Surface(((Component)val).transform, "Viewport", 6f, 6f, 638f, 314f, Color.clear);
			((Graphic)val2).raycastTarget = true;
			((Component)val2).gameObject.AddComponent<RectMask2D>();
			content = Rect(((Component)val2).transform, "Rows", 0f, 0f, 638f, 326f);
			empty = Label(((Component)val2).transform, "No items learned yet.\nPut an example item in this chest to teach it.", 14f, 20f, 610f, 64f, 18, Muted, bold: false, (TextAnchor)3);
			Image obj = Surface(((Component)val).transform, "Scroll track", 650f, 6f, 10f, 314f, new Color(0.18f, 0.16f, 0.12f));
			((Graphic)obj).raycastTarget = true;
			Image val3 = Surface(((Component)obj).transform, "Scroll thumb", 0f, 0f, 10f, 314f, new Color(0.66f, 0.55f, 0.35f));
			((Graphic)val3).rectTransform.anchorMin = Vector2.zero;
			((Graphic)val3).rectTransform.anchorMax = Vector2.one;
			RectTransform rectTransform = ((Graphic)val3).rectTransform;
			Vector2 offsetMin = (((Graphic)val3).rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
			((Graphic)val3).raycastTarget = true;
			Scrollbar val4 = ((Component)obj).gameObject.AddComponent<Scrollbar>();
			val4.handleRect = ((Graphic)val3).rectTransform;
			((Selectable)val4).targetGraphic = (Graphic)(object)val3;
			val4.direction = (Direction)2;
			scroll = ((Component)val).gameObject.AddComponent<ScrollRect>();
			scroll.viewport = ((Graphic)val2).rectTransform;
			scroll.content = content;
			scroll.horizontal = false;
			scroll.vertical = true;
			scroll.inertia = false;
			scroll.movementType = (MovementType)2;
			scroll.scrollSensitivity = 360f;
			scroll.verticalScrollbar = val4;
			scroll.verticalScrollbarVisibility = (ScrollbarVisibility)0;
			((UnityEvent<Vector2>)(object)scroll.onValueChanged).AddListener((UnityAction<Vector2>)delegate
			{
				Render();
			});
			for (int num = 0; num < 8; num++)
			{
				Row row = new Row();
				Image val5 = Surface((Transform)(object)content, "Acceptance row", 0f, 0f, 638f, 71f, new Color(0.09f, 0.095f, 0.085f, 0.96f));
				row.Object = ((Component)val5).gameObject;
				row.Background = val5;
				row.Accent = Surface(((Component)val5).transform, "Acceptance accent", 0f, 8f, 2f, 55f, Gold);
				row.Icon = Surface(((Component)val5).transform, "Item icon", 14f, 12f, 46f, 46f, Color.white);
				row.Icon.preserveAspect = true;
				row.Name = Label(((Component)val5).transform, "", 78f, 4f, 431f, 46f, 20, Ink, bold: true, (TextAnchor)3);
				row.Name.supportRichText = false;
				row.Name.verticalOverflow = (VerticalWrapMode)0;
				((Graphic)row.Name).raycastTarget = true;
				Tooltip(((Component)row.Name).gameObject, "");
				row.State = Label(((Component)val5).transform, "", 78f, 53f, 420f, 16f, 12, Muted, bold: false, (TextAnchor)3);
				row.Accept = MakeToggle(((Component)val5).transform, 529f, 18f);
				row.Delete = MakeButton(((Component)val5).transform, "X", 587f, 18f, 40f, delegate
				{
					Delete(row);
				});
				Tooltip(((Component)row.Accept).gameObject, "Enable or pause acceptance. Paused items stay on the list.");
				Tooltip(((Component)row.Delete).gameObject, "Forget this item completely. Stored items stay in the chest.");
				((UnityEvent<bool>)(object)row.Accept.onValueChanged).AddListener((UnityAction<bool>)delegate(bool value)
				{
					if (!binding && row.Id != null)
					{
						string id = row.Id;
						if (Edit(delegate(Rules r)
						{
							r.Enable(id, value);
						}))
						{
							status.text = Name(id) + (value ? ": acceptance enabled." : ": acceptance paused.");
						}
					}
				});
				Selectable[] array = (Selectable[])(object)new Selectable[2]
				{
					(Selectable)row.Accept,
					(Selectable)row.Delete
				};
				foreach (Selectable val6 in array)
				{
					Navigation navigation = default(Navigation);
					((Navigation)(ref navigation)).mode = (Mode)0;
					val6.navigation = navigation;
					AcceptanceNavigation acceptanceNavigation = ((Component)val6).gameObject.AddComponent<AcceptanceNavigation>();
					acceptanceNavigation.Window = this;
					acceptanceNavigation.RowIndex = () => row.Index;
					acceptanceNavigation.DeleteColumn = (Object)(object)val6 == (Object)(object)row.Delete;
				}
				pool.Add(row);
			}
		}

		private void Render()
		{
			//IL_001d: 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_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)content) || rules == null)
			{
				return;
			}
			int num = Math.Max(0, (int)(content.anchoredPosition.y / 76f) - 1);
			binding = true;
			foreach (Row item in pool)
			{
				int num2 = (item.Index = num++);
				item.Id = ((num2 < ordered.Count) ? ordered[num2] : null);
				item.Object.SetActive(item.Id != null);
				if (item.Id != null)
				{
					item.Object.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, (float)(-num2) * 76f);
					item.Name.text = Name(item.Id);
					((Component)item.Name).GetComponent<UITooltip>().m_text = item.Name.text;
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item.Id);
					ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
					item.Icon.sprite = (Object.op_Implicit((Object)(object)val) ? val.m_itemData.GetIcon() : null);
					((Graphic)item.Icon).color = (Color)(Object.op_Implicit((Object)(object)item.Icon.sprite) ? Color.white : new Color(0.6f, 0.57f, 0.48f, 0.25f));
					bool flag = rules.Items[item.Id];
					item.Accept.SetIsOnWithoutNotify(flag);
					item.State.text = (flag ? "Accepting" : "Paused");
					((Graphic)item.Background).color = ((num2 % 2 == 0) ? new Color(0.105f, 0.093f, 0.072f, 0.96f) : new Color(0.078f, 0.07f, 0.056f, 0.96f));
					((Graphic)item.Accent).color = (flag ? new Color(Gold.r, Gold.g, Gold.b, 0.5f) : new Color(Muted.r, Muted.g, Muted.b, 0.22f));
					((Graphic)item.Name).color = (flag ? Ink : Muted);
					((Graphic)item.State).color = (Color)(flag ? new Color(0.77f, 0.67f, 0.46f) : Muted);
					if (!flag && Object.op_Implicit((Object)(object)item.Icon.sprite))
					{
						((Graphic)item.Icon).color = new Color(0.7f, 0.7f, 0.7f, 0.85f);
					}
				}
			}
			binding = false;
		}

		private void Delete(Row row)
		{
			string id = row.Id;
			int index = row.Index;
			if (id == null || !Edit(delegate(Rules r)
			{
				r.Delete(id);
			}))
			{
				return;
			}
			status.text = Name(id) + " removed. Stored items are unchanged.";
			if (ordered.Count > 0)
			{
				Select(Math.Min(index, ordered.Count - 1), delete: false);
				return;
			}
			EventSystem current = EventSystem.current;
			if (current != null)
			{
				current.SetSelectedGameObject(((Component)distributor).gameObject);
			}
		}

		internal void Navigate(int index, bool delete, MoveDirection direction)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_0036: 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_0044: Invalid comparison between Unknown and I4
			if ((int)direction == 1)
			{
				Select(Math.Max(0, index - 1), delete);
			}
			else if ((int)direction == 3)
			{
				Select(Math.Min(ordered.Count - 1, index + 1), delete);
			}
			else if ((int)direction == 0)
			{
				Select(index, delete: false);
			}
			else if ((int)direction == 2)
			{
				Select(index, delete: true);
			}
		}

		private void Select(int index, bool delete)
		{
			//IL_0030: 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)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if (index < 0 || index >= ordered.Count)
			{
				return;
			}
			float num = content.anchoredPosition.y;
			float num2 = (float)index * 76f;
			if (num2 < num)
			{
				num = num2;
			}
			else
			{
				float num3 = num2 + 76f;
				float num4 = num;
				Rect rect = scroll.viewport.rect;
				if (num3 > num4 + ((Rect)(ref rect)).height)
				{
					float num5 = num2 + 76f;
					rect = scroll.viewport.rect;
					num = num5 - ((Rect)(ref rect)).height;
				}
			}
			content.anchoredPosition = new Vector2(0f, num);
			Render();
			Row row = pool.FirstOrDefault((Row r) => r.Index == index);
			if (row != null)
			{
				EventSystem current = EventSystem.current;
				if (current != null)
				{
					current.SetSelectedGameObject(delete ? ((Component)row.Delete).gameObject : ((Component)row.Accept).gameObject);
				}
			}
		}

		private static string Name(string id)
		{
			GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(id) : null);
			ItemDrop val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return id;
			}
			return Localization.instance.Localize(val2.m_itemData.m_shared.m_name);
		}

		private static Toggle MakeToggle(Transform parent, float x, float y)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GUIManager.Instance.CreateToggle(parent, 30f, 30f);
			RectTransform component = obj.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			Vector2 val = (component.pivot = TopLeft);
			Vector2 anchorMin = (component.anchorMax = val);
			component.anchorMin = anchorMin;
			component.anchoredPosition = new Vector2(x, 0f - y);
			component.sizeDelta = new Vector2(36f, 36f);
			Transform val3 = obj.transform.Find("Label");
			if (Object.op_Implicit((Object)(object)val3))
			{
				((Component)val3).gameObject.SetActive(false);
			}
			Transform obj2 = obj.transform.Find("Background");
			RectTransform val4 = (RectTransform)(object)((obj2 is RectTransform) ? obj2 : null);
			if (Object.op_Implicit((Object)(object)val4))
			{
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				val4.pivot = val;
				anchorMin = (val4.anchorMax = val);
				val4.anchorMin = anchorMin;
				val4.anchoredPosition = Vector2.zero;
				val4.sizeDelta = new Vector2(30f, 30f);
			}
			return obj.GetComponent<Toggle>();
		}

		private static Button MakeButton(Transform parent, string text, float x, float y, float width, Action action)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_005f: Expected O, but got Unknown
			Button component = GUIManager.Instance.CreateButton(text, parent, TopLeft, TopLeft, new Vector2(x + width / 2f, 0f - y - 18f), width, 36f).GetComponent<Button>();
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				action();
			});
			Button val = (Button)(Object.op_Implicit((Object)(object)InventoryGui.instance) ? /*isinst with value type is only supported in some contexts*/: null);
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)((Selectable)val).image))
			{
				((Graphic)((Selectable)component).image).material = ((Graphic)((Selectable)val).image).material;
			}
			return component;
		}

		private void Tooltip(GameObject control, string text)
		{
			UITooltip obj = control.GetComponent<UITooltip>() ?? control.AddComponent<UITooltip>();
			obj.m_tooltipPrefab = tooltipPrefab;
			obj.m_topic = "";
			obj.m_text = text;
			((Behaviour)obj).enabled = Object.op_Implicit((Object)(object)obj.m_tooltipPrefab);
		}

		private static RectTransform Rect(Transform parent, string name, float x, float y, float width, float height)
		{
			//IL_0014: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			Vector2 val = (component.pivot = TopLeft);
			Vector2 anchorMin = (component.anchorMax = val);
			component.anchorMin = anchorMin;
			component.anchoredPosition = new Vector2(x, 0f - y);
			component.sizeDelta = new Vector2(width, height);
			return component;
		}

		private static Image Surface(Transform parent, string name, float x, float y, float width, float height, Color color)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)Rect(parent, name, x, y, width, height)).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			((Graphic)obj).raycastTarget = false;
			return obj;
		}

		private static Text Label(Transform parent, string text, float x, float y, float width, float height, int size, Color color, bool bold = false, TextAnchor alignment = (TextAnchor)3)
		{
			//IL_0007: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			Text component = GUIManager.Instance.CreateText(text, parent, TopLeft, TopLeft, new Vector2(x + width / 2f, 0f - y - height / 2f), bold ? GUIManager.Instance.AveriaSerifBold : GUIManager.Instance.AveriaSerif, size, color, false, Color.black, width, height, false).GetComponent<Text>();
			component.alignment = alignment;
			((Graphic)component).raycastTarget = false;
			component.horizontalOverflow = (HorizontalWrapMode)0;
			return component;
		}
	}
	public sealed class AcceptanceNavigation : MonoBehaviour, IMoveHandler, IEventSystemHandler
	{
		internal ChestWindow Window;

		internal Func<int> RowIndex;

		internal bool DeleteColumn;

		public void OnMove(AxisEventData data)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Window.Navigate(RowIndex(), DeleteColumn, data.moveDir);
			((AbstractEventData)data).Use();
		}
	}
	internal static class GameState
	{
		internal const string RulesKey = "hearthsort.rules.v1";

		private static readonly int PersonalChest = StringExtensionMethods.GetStableHashCode("piece_chest_private");

		internal static readonly MethodInfo Load = AccessTools.Method(typeof(Container), "Load", Type.EmptyTypes, (Type[])null);

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

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

		private static readonly FieldInfo LastRevision = AccessTools.Field(typeof(Container), "m_lastRevision");

		internal static ZNetView View(Container chest)
		{
			if (!Object.op_Implicit((Object)(object)chest))
			{
				return null;
			}
			return ((Component)chest).GetComponent<ZNetView>();
		}

		internal static ZDO Data(Container chest)
		{
			ZNetView obj = View(chest);
			if (obj == null)
			{
				return null;
			}
			return obj.GetZDO();
		}

		internal static Container Template(ZDO z)
		{
			if (z == null || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(z.GetPrefab());
			if (prefab == null)
			{
				return null;
			}
			return prefab.GetComponent<Container>();
		}

		private static bool SharedStorage(Container chest, int prefab)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			if (Object.op_Implicit((Object)(object)chest))
			{
				return StoragePolicy.Eligible((int)chest.m_privacy == 2, Object.op_Implicit((Object)(object)((Component)chest).GetComponent<Piece>()), Object.op_Implicit((Object)(object)((Component)chest).GetComponent<ZNetView>()), prefab == PersonalChest, Object.op_Implicit((Object)(object)chest.m_rootObjectOverride) || Object.op_Implicit((Object)(object)chest.m_wagon) || Object.op_Implicit((Object)(object)((Component)chest).GetComponent<Vagon>()) || Object.op_Implicit((Object)(object)((Component)chest).GetComponent<Ship>()), chest.m_autoDestroyEmpty || Object.op_Implicit((Object)(object)((Component)chest).GetComponent<TombStone>()));
			}
			return false;
		}

		internal static bool Supported(ZDO z)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if (z == null || !z.IsValid() || !SharedStorage(Template(z), z.GetPrefab()))
			{
				return false;
			}
			Container val = Plugin.Instance?.Registry?.Find(z.m_uid);
			if (Object.op_Implicit((Object)(object)val))
			{
				if (SharedStorage(val, z.GetPrefab()))
				{
					return val.GetInventory() != null;
				}
				return false;
			}
			return true;
		}

		internal static bool Supported(Container chest)
		{
			ZDO val = Data(chest);
			if (val != null && SharedStorage(chest, val.GetPrefab()) && Supported(val))
			{
				return chest.GetInventory() != null;
			}
			return false;
		}

		internal static string Encoded(ZDO z)
		{
			return z.GetString("hearthsort.rules.v1", "");
		}

		internal static Rules Read(ZDO z)
		{
			return Rules.Decode(Encoded(z));
		}

		internal static bool InUse(Container c)
		{
			if (!c.IsInUse())
			{
				ZDO obj = Data(c);
				if (obj == null)
				{
					return true;
				}
				return obj.GetInt(ZDOVars.s_inUse, 0) != 0;
			}
			return true;
		}

		internal static void Refresh(Container c)
		{
			if (Supported(c) && !c.IsInUse())
			{
				Load.Invoke(c, null);
			}
		}

		internal static void Install(Container c, byte[] bytes)
		{
			Snapshot snapshot = Snapshot.Read(bytes, c.GetInventory().GetWidth(), c.GetInventory().GetHeight());
			List<ItemData> allItems = c.GetInventory().GetAllItems();
			Dictionary<(string, int, int), SharedData> dictionary = new Dictionary<(string, int, int), SharedData>();
			foreach (ItemData item in allItems)
			{
				if (Object.op_Implicit((Object)(object)item.m_dropPrefab) && item.m_shared != null)
				{
					dictionary[(((Object)item.m_dropPrefab).name, item.m_quality, item.m_variant)] = item.m_shared;
				}
			}
			List<ItemData> list = snapshot.Materialize(snapshot.Stock).ToList();
			foreach (ItemData item2 in list)
			{
				if (dictionary.TryGetValue((((Object)item2.m_dropPrefab).name, item2.m_quality, item2.m_variant), out var value))
				{
					item2.m_shared = value;
				}
			}
			allItems.Clear();
			allItems.AddRange(list);
			LastRevision.SetValue(c, Data(c).DataRevision);
			try
			{
				Changed.Invoke(c.GetInventory(), new object[2] { false, false });
			}
			catch (Exception e)
			{
				Plugin.Instance.Error("Chest contents synchronized, but an inventory-change listener failed", e);
			}
		}

		internal static bool LocalAccess(Container chest)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!Supported(chest) || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return false;
			}
			if (chest.m_checkGuardStone)
			{
				return PrivateArea.CheckAccess(((Component)chest).transform.position, 0f, false, false);
			}
			return true;
		}

		internal static bool Same(byte[] a, byte[] b)
		{
			if (a != null && b != null)
			{
				return ((ReadOnlySpan<byte>)a).SequenceEqual((ReadOnlySpan<byte>)b);
			}
			return false;
		}

		internal static StackLimits CaptureStackLimits(Container chest, IEnumerable<int> prefabs)
		{
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			if (Object.op_Implicit((Object)(object)chest))
			{
				foreach (ItemData allItem in chest.GetInventory().GetAllItems())
				{
					if (Object.op_Implicit((Object)(object)allItem.m_dropPrefab) && allItem.m_shared != null)
					{
						int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)allItem.m_dropPrefab).name);
						int num = Math.Min(65535, allItem.m_shared.m_maxStackSize);
						dictionary[stableHashCode] = (dictionary.TryGetValue(stableHashCode, out var value) ? Math.Min(value, num) : num);
					}
				}
			}
			StackLimits stackLimits = new StackLimits();
			foreach (int prefab in prefabs)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefab);
				ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if (!Object.op_Implicit((Object)(object)val))
				{
					throw new InvalidDataException("An incoming item's stack definition is missing on the chest owner.");
				}
				stackLimits.Add(prefab, dictionary.TryGetValue(prefab, out var value2) ? value2 : Math.Min(65535, val.m_itemData.m_shared.m_maxStackSize));
			}
			return stackLimits;
		}
	}
	internal sealed class Snapshot
	{
		internal readonly List<Stock> Stock = new List<Stock>();

		private readonly Dictionary<string, ItemData> templates = new Dictionary<string, ItemData>();

		private readonly Dictionary<string, byte[]> records = new Dictionary<string, byte[]>();

		internal int Width;

		internal int Height;

		internal static Snapshot Read(byte[] bytes, int width, int height)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			if (bytes == null || bytes.Length > 1048576 || width < 1 || height < 1 || width > 256 || height > 256 || width * height > 1024)
			{
				throw new InvalidDataException("Unsupported inventory size.");
			}
			Snapshot snapshot = new Snapshot
			{
				Width = width,
				Height = height
			};
			ZPackage val = new ZPackage(bytes);
			int num = val.ReadInt();
			if (!ItemRecord.Supports(num))
			{
				throw new InvalidDataException("Unsupported chest inventory format " + num + "; supported formats are 109 and 110. Contents were preserved.");
			}
			int num2 = val.ReadUShort();
			if (num2 > 1024)
			{
				throw new InvalidDataException("Too many item records.");
			}
			HashSet<Vector2i> hashSet = new HashSet<Vector2i>();
			for (int i = 0; i < num2; i++)
			{
				int pos = val.GetPos();
				(int, ItemData) tuple = ItemData.Load(val, (Item)num);
				byte[] array = new byte[val.GetPos() - pos];
				Array.Copy(bytes, pos, array, 0, array.Length);
				array = ItemRecord.Normalize(array, num);
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(tuple.Item1);
				ItemDrop val2 = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if (!Object.op_Implicit((Object)(object)val2))
				{
					throw new InvalidDataException("An item is missing on the server; contents were preserved.");
				}
				ItemData item = tuple.Item2;
				item.m_dropPrefab = itemPrefab;
				item.m_shared = val2.m_itemData.m_shared;
				if (item.m_stack <= 0 || item.m_stack > 65535 || item.m_gridPos.x < 0 || item.m_gridPos.y < 0 || item.m_gridPos.x >= width || item.m_gridPos.y >= height || !hashSet.Add(item.m_gridPos))
				{
					throw new InvalidDataException("Unsupported or overlapping chest slots; contents were preserved.");
				}
				string text = Convert.ToBase64String(ItemRecord.Place(array, 1, 0, 0));
				snapshot.templates[text] = item;
				snapshot.records[text] = array;
				snapshot.Stock.Add(new Stock
				{
					Id = ((Object)itemPrefab).name,
					Fingerprint = text,
					Quantity = item.m_stack,
					Limit = Math.Min(65535, item.m_shared.m_maxStackSize),
					X = item.m_gridPos.x,
					Y = item.m_gridPos.y
				});
			}
			if (val.GetPos() != bytes.Length)
			{
				throw new InvalidDataException("Unexpected inventory data.");
			}
			return snapshot;
		}

		internal void Include(Snapshot other)
		{
			foreach (KeyValuePair<string, ItemData> template in other.templates)
			{
				if (!templates.ContainsKey(template.Key))
				{
					templates.Add(template.Key, template.Value);
					records.Add(template.Key, other.records[template.Key]);
				}
			}
		}

		internal void ApplyStackLimits(StackLimits limits, ISet<int> requested)
		{
			foreach (Stock item in Stock)
			{
				int stableHashCode = StringExtensionMethods.GetStableHashCode(item.Id);
				if (requested.Contains(stableHashCode))
				{
					item.Limit = limits[stableHashCode];
				}
			}
		}

		internal IEnumerable<ItemData> Materialize(IEnumerable<Stock> stocks)
		{
			foreach (Stock stock in stocks)
			{
				ItemData val = templates[stock.Fingerprint].Clone();
				val.m_stack = stock.Quantity;
				val.m_gridPos = new Vector2i(stock.X, stock.Y);
				yield return val;
			}
		}

		internal byte[] Encode(IEnumerable<Stock> stocks)
		{
			Stock[] array = stocks.ToArray();
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write(110);
			binaryWriter.Write((ushort)array.Length);
			Stock[] array2 = array;
			foreach (Stock stock in array2)
			{
				binaryWriter.Write(ItemRecord.Place(records[stock.Fingerprint], stock.Quantity, stock.X, stock.Y));
			}
			binaryWriter.Flush();
			return memoryStream.ToArray();
		}
	}
	internal sealed class ChestRegistry
	{
		private ZDOMan registeredWorld;

		private const float CellSize = 20f;

		private readonly Dictionary<ZDOID, Container> chests = new Dictionary<ZDOID, Container>();

		private readonly Dictionary<(int, int), HashSet<ZDOID>> cells = new Dictionary<(int, int), HashSet<ZDOID>>();

		private readonly Dictionary<ZDOID, (int, int)> positions = new Dictionary<ZDOID, (int, int)>();

		internal Container Find(ZDOID id)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (!chests.TryGetValue(id, out var value) || !Object.op_Implicit((Object)(object)value))
			{
				return null;
			}
			return value;
		}

		private static (int, int) Cell(Vector3 p)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return ((int)Math.Floor(p.x / 20f), (int)Math.Floor(p.z / 20f));
		}

		internal void Register(Container c)
		{
			//IL_0034: 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)
			//IL_0058: 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_00b0: 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)
			if (GameState.Supported(c))
			{
				if (registeredWorld != ZDOMan.instance)
				{
					Clear();
					registeredWorld = ZDOMan.instance;
				}
				ZDO val = GameState.Data(c);
				(int, int) tuple = Cell(((Component)c).transform.position);
				chests[val.m_uid] = c;
				positions[val.m_uid] = tuple;
				if (!cells.TryGetValue(tuple, out var value))
				{
					value = (cells[tuple] = new HashSet<ZDOID>());
				}
				value.Add(val.m_uid);
				ChestRegistration chestRegistration = ((Component)c).GetComponent<ChestRegistration>();
				if (!Object.op_Implicit((Object)(object)chestRegistration))
				{
					chestRegistration = ((Component)c).gameObject.AddComponent<ChestRegistration>();
				}
				chestRegistration.Identity = val.m_uid;
				chestRegistration.Chest = c;
				Plugin.Instance.Network.Publish(val);
			}
		}

		internal void Remove(ZDOID id, Container instance)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			if (!chests.TryGetValue(id, out var value) || (Object)(object)value != (Object)(object)instance)
			{
				return;
			}
			chests.Remove(id);
			if (positions.TryGetValue(id, out var value2) && cells.TryGetValue(value2, out var value3))
			{
				value3.Remove(id);
				if (value3.Count == 0)
				{
					cells.Remove(value2);
				}
			}
			positions.Remove(id);
		}

		internal void Clear()
		{
			chests.Clear();
			cells.Clear();
			positions.Clear();
		}

		internal List<ZDOID> Nearby(Container source, float range)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//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_00d4: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			Vector3 p = ((Component)source).transform.position;
			(int, int) tuple = Cell(p - new Vector3(range, 0f, range));
			(int, int) tuple2 = Cell(p + new Vector3(range, 0f, range));
			var (i, _) = tuple;
			for (; i <= tuple2.Item1; i++)
			{
				for (int j = tuple.Item2; j <= tuple2.Item2; j++)
				{
					if (!cells.TryGetValue((i, j), out var value))
					{
						continue;
					}
					foreach (ZDOID item in value)
					{
						Container val = Find(item);
						if (Object.op_Implicit((Object)(object)val) && (Object)(object)val != (Object)(object)source)
						{
							Vector3 val2 = ((Component)val).transform.position - p;
							if (((Vector3)(ref val2)).sqrMagnitude <= range * range && GameState.LocalAccess(val))
							{
								list.Add(val);
							}
						}
					}
				}
			}
			return (from c in list.OrderBy(delegate(Container c)
				{
					//IL_0006: 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_0016: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val3 = ((Component)c).transform.position - p;
					return ((Vector3)(ref val3)).sqrMagnitude;
				}).ThenBy((Container c) => ((ZDOID)(ref GameState.Data(c).m_uid)).UserID).ThenBy((Container c) => ((ZDOID)(ref GameState.Data(c).m_uid)).ID)
					.Take(256)
				select GameState.Data(c).m_uid).ToList();
		}
	}
	public sealed class ChestRegistration : MonoBehaviour
	{
		internal ZDOID Identity;

		internal Container Chest;

		private void OnDestroy()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Instance?.Registry?.Remove(Identity, Chest);
		}
	}
	[HarmonyPatch]
	internal static class Patches
	{
		[HarmonyPatch]
		private static class RequestGuard
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				string[] array = new string[3] { "RPC_RequestOpen", "RPC_RequestStack", "RPC_RequestTakeAll" };
				foreach (string text in array)
				{
					yield return AccessTools.Method(typeof(Container), text, (Type[])null, (Type[])null);
				}
			}

			private static bool Prefix(Container __instance, long uid, MethodBase __originalMethod)
			{
				if (!GameState.Supported(__instance))
				{
					return true;
				}
				if (Locked(__instance))
				{
					ZNetView obj = GameState.View(__instance);
					if (obj != null)
					{
						obj.InvokeRPC(uid, __originalMethod.Name.Replace("Request", "") + "Response", new object[1] { false });
					}
					return false;
				}
				if (!__instance.IsInUse())
				{
					GameState.Refresh(__instance);
				}
				return true;
			}
		}

		[HarmonyPatch]
		private static class ResponseGuard
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				string[] array = new string[3] { "RPC_OpenResponse", "RPC_StackResponse", "RPC_TakeAllResponse" };
				foreach (string text in array)
				{
					yield return AccessTools.Method(typeof(Container), text, (Type[])null, (Type[])null);
				}
			}

			private static bool Prefix(Container __instance, bool granted)
			{
				if (!granted || !GameState.Supported(__instance))
				{
					return true;
				}
				if (Locked(__instance))
				{
					return false;
				}
				GameState.Refresh(__instance);
				return true;
			}
		}

		[HarmonyPatch]
		private static class Close
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				yield return AccessTools.Method(typeof(InventoryGui), "Hide", (Type[])null, (Type[])null);
				yield return AccessTools.Method(typeof(InventoryGui), "CloseContainer", (Type[])null, (Type[])null);
			}

			private static void Prefix(InventoryGui __instance, out Container __state)
			{
				__state = Current(__instance);
			}

			private static void Postfix(InventoryGui __instance, Container __state)
			{
				if (!Object.op_Implicit((Object)(object)__state) || (Object)(object)Current(__instance) == (Object)(object)__state)
				{
					return;
				}
				Plugin.Instance.Window.Observe(null);
				if (!GameState.Supported(__state))
				{
					return;
				}
				try
				{
					if (GameState.Read(GameState.Data(__state)).Distributor)
					{
						Plugin.Instance.Network.Queue(__state);
					}
				}
				catch (Exception e)
				{
					Plugin.Instance.Error("Sorting request preserved chest contents", e);
				}
			}
		}

		[HarmonyPatch]
		private static class ManualDeposit
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				yield return AccessTools.Method(typeof(InventoryGui), "OnSelectedItem", (Type[])null, (Type[])null);
				yield return AccessTools.Method(typeof(InventoryGui), "OnStackAll", (Type[])null, (Type[])null);
			}

			private static void Prefix(InventoryGui __instance, out Dictionary<string, long> __state)
			{
				Container val = Current(__instance);
				__state = ((GameState.Supported(val) && val.IsOwner() && !Locked(val)) ? Counts(val) : null);
			}

			private static void Postfix(InventoryGui __instance, Dictionary<string, long> __state)
			{
				Container val = Current(__instance);
				if (__state == null || !GameState.Supported(val) || !val.IsOwner() || Locked(val))
				{
					return;
				}
				try
				{
					Teach(val, __state);
				}
				catch (Exception e)
				{
					Plugin.Instance.Error("Chest learning", e);
				}
			}

			internal static void Teach(Container c, Dictionary<string, long> before)
			{
				ZDO val = GameState.Data(c);
				Rules rules = GameState.Read(val);
				bool flag = false;
				foreach (KeyValuePair<string, long> item in Counts(c))
				{
					if (!before.TryGetValue(item.Key, out var value) || item.Value > value)
					{
						flag |= rules.Teach(item.Key);
					}
				}
				if (flag)
				{
					val.Set("hearthsort.rules.v1", rules.Encode());
					Plugin.Instance.Network.Publish(val);
				}
			}

			internal static Dictionary<string, long> Counts(Container c)
			{
				Dictionary<string, long> dictionary = new Dictionary<string, long>(StringComparer.Ordinal);
				foreach (ItemData allItem in c.GetInventory().GetAllItems())
				{
					if (Object.op_Implicit((Object)(object)allItem.m_dropPrefab))
					{
						string name = ((Object)allItem.m_dropPrefab).name;
						dictionary.TryGetValue(name, out var value);
						dictionary[name] = value + allItem.m_stack;
					}
				}
				return dictionary;
			}
		}

		[HarmonyPatch(typeof(Container), "RPC_StackResponse")]
		private static class ClosedChestDeposit
		{
			private static void Prefix(Container __instance, bool granted, out Dictionary<string, long> __state)
			{
				__state = ((granted && GameState.Supported(__instance) && __instance.IsOwner() && !Locked(__instance)) ? ManualDeposit.Counts(__instance) : null);
			}

			private static void Postfix(Container __instance, Dictionary<string, long> __state)
			{
				if (__state == null || !GameState.Supported(__instance) || !__instance.IsOwner() || Locked(__instance))
				{
					return;
				}
				try
				{
					ManualDeposit.Teach(__instance, __state);
				}
				catch (Exception e)
				{
					Plugin.Instance.Error("Chest quick-stack learning", e);
				}
			}
		}

		private static readonly FieldRef<InventoryGui, Container> CurrentField = AccessTools.FieldRefAccess<InventoryGui, Container>("m_currentContainer");

		internal static Container Current(InventoryGui gui)
		{
			if (!Object.op_Implicit((Object)(object)gui))
			{
				return null;
			}
			return CurrentField.Invoke(gui);
		}

		internal static bool Locked(Container c)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)c) && GameState.Data(c) != null)
			{
				return Plugin.Instance.Network.IsLocked(GameState.Data(c).m_uid);
			}
			return false;
		}

		[HarmonyPatch(typeof(ZDO), "SetOwner")]
		[HarmonyPrefix]
		private static bool PreserveLeaseOwner(ZDO __instance)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if (instance == null)
			{
				return true;
			}
			return instance.Network?.HoldServerOwner(__instance.m_uid) != true;
		}

		[HarmonyPatch(typeof(ZDOMan), "RPC_ZDOData")]
		[HarmonyPrefix]
		private static void Replication(ref ZPackage pkg)
		{
			if (ZNet.instance.IsServer())
			{
				pkg = Plugin.Instance.Network.FilterIncoming(pkg);
			}
		}

		[HarmonyPatch(typeof(WearNTear), "RPC_Damage")]
		[HarmonyPrefix]
		private static bool Damage(WearNTear __instance, HitData hit)
		{
			if (!Locked(((Component)__instance).GetComponent<Container>()))
			{
				return true;
			}
			Plugin.Instance.Network.DeferDamage(__instance, hit);
			return false;
		}

		[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
		[HarmonyPrefix]
		private static bool EnvironmentalDamage(WearNTear __instance, ref bool __result)
		{
			if (!Locked(((Component)__instance).GetComponent<Container>()))
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(WearNTear), "RPC_Remove")]
		[HarmonyPrefix]
		private static bool RemovePiece(WearNTear __instance)
		{
			return !Locked(((Component)__instance).GetComponent<Container>());
		}

		[HarmonyPatch(typeof(ZDOMan), "HandleDestroyedZDO")]
		[HarmonyPrefix]
		private static bool DestroyWorldData(ZDOID uid)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			return !Plugin.Instance.Network.IsLocked(uid);
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Register(Container __instance)
		{
			Plugin.Instance.Registry.Register(__instance);
		}

		[HarmonyPatch(typeof(Container), "Save")]
		[HarmonyPrefix]
		private static bool GuardSave(Container __instance)
		{
			return !Locked(__instance);
		}

		[HarmonyPatch(typeof(Container), "IsInUse")]
		[HarmonyPostfix]
		private static void BusyDuringTransfer(Container __instance, ref bool __result)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			ZDO val = GameState.Data(__instance);
			if (val != null)
			{
				Plugin instance = Plugin.Instance;
				if (instance != null && instance.Network?.IsLocallyLocked(val.m_uid) == true)
				{
					__result = true;
				}
			}
		}

		[HarmonyPatch(typeof(Container), "Interact")]
		[HarmonyPrefix]
		private static bool Interact(Container __instance, ref bool __result)
		{
			if (!Locked(__instance))
			{
				return true;
			}
			Plugin.Instance.Message("Chest sorting is finishing. Try again shortly.");
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(Container), "CanBeRemoved")]
		[HarmonyPrefix]
		private static bool Remove(Container __instance, ref bool __result)
		{
			if (!Locked(__instance))
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(Container), "OnDestroyed")]
		[HarmonyPrefix]
		private static void Destroyed(Container __instance)
		{
			Plugin.Instance.Network.Destroyed(GameState.Data(__instance));
		}

		[HarmonyPatch(typeof(InventoryGui), "Show")]
		[HarmonyPostfix]
		private static void Open(InventoryGui __instance, Container container)
		{
			Plugin.Instance.Window.Observe(container);
		}

		[HarmonyPatch(typeof(InventoryGui), "Update")]
		[HarmonyPrefix]
		private static bool ModalInput()
		{
			if (!Plugin.Instance.Window.IsOpen)
			{
				return Plugin.Instance.Window.EscapeFrame != Time.frameCount;
			}
			return false;
		}
	}
	[BepInPlugin("cheyenne.hearthsort", "Hearth Sort", "0.1.17")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "cheyenne.hearthsort";

		public const string Version = "0.1.17";

		internal static Plugin Instance;

		internal ChestRegistry Registry;

		internal SortingNetwork Network;

		internal ChestWindow Window;

		internal ConfigEntry<float> Range;

		private Harmony patches;

		private bool stopped;

		private void Awake()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			Instance = this;
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("Sorting", "Range", 20f, new ConfigDescription("Maximum chest-to-chest distance in metres. Server controls this setting.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 50f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			Registry = new ChestRegistry();
			Network = new SortingNetwork();
			Window = new ChestWindow();
			try
			{
				ValidateApi();
				patches = new Harmony("cheyenne.hearthsort");
				patches.PatchAll(typeof(Patches).Assembly);
				VerifyPatches();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Hearth Sort 0.1.17 loaded; all 24 chest, UI and ownership patch targets verified.");
			}
			catch (Exception ex)
			{
				stopped = true;
				Harmony obj = patches;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				((BaseUnityPlugin)this).Logger.LogError((object)("Hearth Sort disabled before use: " + ex));
			}
		}

		private static void VerifyPatches()
		{
			int num = 0;
			MethodInfo[] methods = typeof(Patches).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
			foreach (MethodInfo patch in methods)
			{
				Attribute? customAttribute = Attribute.GetCustomAttribute(patch, typeof(HarmonyPatch));
				HarmonyPatch val = (HarmonyPatch)(object)((customAttribute is HarmonyPatch) ? customAttribute : null);
				if (val != null)
				{
					MethodInfo methodInfo = AccessTools.Method(((HarmonyAttribute)val).info.declaringType, ((HarmonyAttribute)val).info.methodName, (Type[])null, (Type[])null);
					Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
					ReadOnlyCollection<Patch> readOnlyCollection = ((!Attribute.IsDefined(patch, typeof(HarmonyPrefix))) ? patchInfo?.Postfixes : patchInfo?.Prefixes);
					if (readOnlyCollection == null || !readOnlyCollection.Any((Patch p) => p.owner == "cheyenne.hearthsort" && p.PatchMethod == patch))
					{
						throw new InvalidOperationException("Required hook did not attach: " + methodInfo.DeclaringType.Name + "." + methodInfo.Name);
					}
					num++;
				}
			}
			Type[] array = new Type[2]
			{
				typeof(Container),
				typeof(InventoryGui)
			};
			string[][] array2 = new string[2][]
			{
				new string[6] { "RPC_RequestOpen", "RPC_RequestStack", "RPC_RequestTakeAll", "RPC_OpenResponse", "RPC_StackResponse", "RPC_TakeAllResponse" },
				new string[4] { "Hide", "CloseContainer", "OnSelectedItem", "OnStackAll" }
			};
			for (int num2 = 0; num2 < array.Length; num2++)
			{
				string[] array3 = array2[num2];
				foreach (string text in array3)
				{
					Patches patchInfo2 = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(array[num2], text, (Type[])null, (Type[])null));
					if (patchInfo2 == null || !patchInfo2.Owners.Contains("cheyenne.hearthsort"))
					{
						throw new InvalidOperationException("Required hook did not attach: " + array[num2].Name + "." + text);
					}
					num++;
				}
			}
			if (num != 24)
			{
				throw new InvalidOperationException("Unexpected Hearth Sort hook count: " + num);
			}
		}

		private static void ValidateApi()
		{
			if (GameState.Load == null || GameState.Save == null || GameState.Changed == null || AccessTools.Field(typeof(Container), "m_lastRevision") == null)
			{
				throw new MissingMemberException("Container persistence contract changed.");
			}
			string[] array = new string[8] { "RPC_RequestOpen", "RPC_RequestStack", "RPC_RequestTakeAll", "RPC_OpenResponse", "RPC_StackResponse", "RPC_TakeAllResponse", "OnDestroyed", "CanBeRemoved" };
			foreach (string text in array)
			{
				if (AccessTools.Method(typeof(Container), text, (Type[])null, (Type[])null) == null)
				{
					throw new MissingMethodException(typeof(Container).Name, text);
				}
			}
			array = new string[5] { "Show", "Hide", "CloseContainer", "OnSelectedItem", "OnStackAll" };
			foreach (string text2 in array)
			{
				if (AccessTools.Method(typeof(InventoryGui), text2, (Type[])null, (Type[])null) == null)
				{
					throw new MissingMethodException(typeof(InventoryGui).Name, text2);
				}
			}
			if (AccessTools.Method(typeof(ZDOMan), "FindObjects", new Type[3]
			{
				typeof(Vector2s),
				typeof(List<ZDO>),
				typeof(HashSet<SectorIndex>)
			}, (Type[])null) == null || AccessTools.Method(typeof(ZDOMan), "RPC_ZDOData", (Type[])null, (Type[])null) == null)
			{
				throw new MissingMemberException("World replication contract changed.");
			}
		}

		private void Update()
		{
			if (stopped)
			{
				return;
			}
			try
			{
				Network.Update();
				Window.Update();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
				Window.Close();
			}
		}

		private void OnDestroy()
		{
			Window?.Close();
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Instance = null;
		}

		internal void Error(string message, Exception e)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)(message + ": " + e.Message));
		}

		internal void Trace(string message)
		{
			((BaseUnityPlugin)this).Logger.LogDebug((object)message);
		}

		internal void Warn(string message)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)message);
		}

		internal void Message(string message)
		{
			if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				((Character)Player.m_localPlayer).Message((MessageType)1, message, 0, (Sprite)null, false);
			}
		}
	}
	internal sealed class SortingNetwork
	{
		private sealed class Metadata
		{
			internal long Owner;

			internal string Rules;
		}

		private sealed class Job
		{
			internal long Peer;

			internal long Nonce;

			internal long Player;

			internal ZDOID Source;

			internal List<ZDOID> Targets;

			internal float Deadline;

			internal float NextRead;

			internal float RetryAt;

			internal int Index;

			internal int Moved;

			internal int Operations;

			internal bool Initialized;

			internal bool Matched;

			internal bool Busy;

			internal bool Full;

			internal bool Unknown;

			internal bool Retried;

			internal bool MetadataBlocked;

			internal readonly List<ZDOID> Deferred = new List<ZDOID>();

			internal HashSet<string> Remaining;

			internal double WorkMs;

			internal double MaximumTickMs;
		}

		private sealed class Prepared
		{
			internal ZDOID Id;

			internal long Owner;

			internal long OriginalOwner;

			internal uint OwnerRevision;

			internal uint DataRevision;

			internal uint ObservedRevision;

			internal int Width;

			internal int Height;

			internal byte[] Before;

			internal byte[] After;

			internal string Rules;

			internal StackLimits Limits;
		}

		private sealed class Transaction
		{
			internal long Token;

			internal Lease Guard;

			internal readonly Dictionary<ZDOID, Prepared> Chests = new Dictionary<ZDOID, Prepared>();

			internal float Deadline;

			internal float NextSend;

			internal float NextWarning;

			internal float CommittedAt;

			internal long Peer;

			internal ZDOID Source;

			internal int Moved;

			internal bool Failed;

			internal bool Conflicted;

			internal Snapshot SourceSnapshot;

			internal Snapshot DestinationSnapshot;

			internal HashSet<int> RequestedLimits;

			internal float NextLimitsRequest;
		}

		private sealed class LocalLease
		{
			internal long Token;

			internal Prepared Prepared;

			internal byte[] Expected;

			internal float NextAck;

			internal float NextProbe;

			internal float NextError;

			internal bool Installed;
		}

		private const string SortRpc = "HS_Sort_v1";

		private const string MetaRpc = "HS_Meta_v1";

		private const string ReadRpc = "HS_Read_v1";

		private const string PrepareRpc = "HS_Prepare_v1";

		private const string ReadyRpc = "HS_Ready_v1";

		private const string ApplyRpc = "HS_Apply_v1";

		private const string AppliedRpc = "HS_Applied_v1";

		private const string ReleaseRpc = "HS_Release_v1";

		private const string ReplyRpc = "HS_Reply_v1";

		private const string HelloRpc = "HS_Hello_v1";

		private const string SettingsRpc = "HS_Settings_v1";

		private const string ProbeRpc = "HS_Probe_v1";

		private const string LimitsRpc = "HS_Limits_v1";

		private const string LimitsReadyRpc = "HS_LimitsReady_v1";

		private ZRoutedRpc registered;

		private ZDOMan world;

		private readonly Queue<Job> jobs = new Queue<Job>();

		private readonly HashSet<ZDOID> queued = new HashSet<ZDOID>();

		private readonly Dictionary<ZDOID, Metadata> metadata = new Dictionary<ZDOID, Metadata>();

		private readonly Dictionary<ZDOID, LocalLease> local = new Dictionary<ZDOID, LocalLease>();

		private readonly List<(Container Chest, float At, float Deadline)> requests = new List<(Container, float, float)>();

		private readonly Dictionary<long, float> rate = new Dictionary<long, float>();

		private readonly Dictionary<ZDOID, string> status = new Dictionary<ZDOID, string>();

		private readonly List<(WearNTear Piece, HitData Hit)> deferredDamage = new List<(WearNTear, HitData)>();

		private Job active;

		private Transaction transaction;

		private readonly Dictionary<long, Transaction> settling = new Dictionary<long, Transaction>();

		private readonly Dictionary<ZDOID, Transaction> settlingChests = new Dictionary<ZDOID, Transaction>();

		private readonly Queue<long> settleOrder = new Queue<long>();

		private long serial;

		private float nextPump;

		private float nextHello;

		private bool settingsReceived;

		private bool changingOwner;

		private float wardRadius = -1f;

		internal float ServerRange = 20f;

		private static readonly MethodInfo FindSector = AccessTools.Method(typeof(ZDOMan), "FindObjects", new Type[3]
		{
			typeof(Vector2s),
			typeof(List<ZDO>),
			typeof(HashSet<SectorIndex>)
		}, (Type[])null);

		private static long Self => ZNet.GetUID();

		private static long Server
		{
			get
			{
				if (!ZNet.instance.IsServer())
				{
					return ZNet.instance.GetServerPeer()?.m_uid ?? 0;
				}
				return Self;
			}
		}

		internal bool IsLocked(ZDOID id)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (!local.ContainsKey(id))
			{
				Transaction obj = transaction;
				if (obj == null || !obj.Chests.ContainsKey(id))
				{
					return settlingChests.ContainsKey(id);
				}
			}
			return true;
		}

		internal bool IsLocallyLocked(ZDOID id)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return local.ContainsKey(id);
		}

		internal void DeferDamage(WearNTear piece, HitData hit)
		{
			deferredDamage.Add((piece, hit));
		}

		internal bool HoldServerOwner(ZDOID id)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!changingOwner)
			{
				Transaction obj = transaction;
				if (obj == null || obj.Guard.Phase != LeasePhase.Committed || !transaction.Chests.ContainsKey(id))
				{
					return settlingChests.ContainsKey(id);
				}
				return true;
			}
			return false;
		}

		private void ChangeOwner(ZDO z, long owner)
		{
			changingOwner = true;
			try
			{
				z.SetOwner(owner);
			}
			finally
			{
				changingOwner = false;
			}
		}

		internal ZPackage FilterIncoming(ZPackage input)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: 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_0098: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			Transaction obj = transaction;
			if ((obj == null || obj.Guard.Phase != LeasePhase.Committed) && settling.Count == 0)
			{
				return input;
			}
			ZPackage val = new ZPackage(input.GetArray());
			ZPackage val2 = new ZPackage();
			int num = val.ReadInt();
			val2.Write(num);
			for (int i = 0; i < num; i++)
			{
				val2.Write(val.ReadZDOID());
			}
			while (true)
			{
				ZDOID val3 = val.ReadZDOID();
				if (((ZDOID)(ref val3)).IsNone())
				{
					break;
				}
				ushort num2 = val.ReadUShort();
				uint num3 = val.ReadUInt();
				long num4 = val.ReadLong();
				Vector3 val4 = val.ReadVector3();
				ZPackage val5 = val.ReadPackage();
				Transaction obj2 = transaction;
				if ((obj2 == null || obj2.Guard.Phase != LeasePhase.Committed || !transaction.Chests.ContainsKey(val3)) && !settlingChests.ContainsKey(val3))
				{
					val2.Write(val3);
					val2.Write(num2);
					val2.Write(num3);
					val2.Write(num4);
					val2.Write(val4);
					val2.Write(val5);
				}
			}
			val2.Write(ZDOID.None);
			val2.SetPos(0);
			return val2;
		}

		internal string Status(ZDOID id)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (!status.TryGetValue(id, out var value))
			{
				return "";
			}
			return value;
		}

		private static ZPackage Packet()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_001d: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(1);
			val.Write(ZNet.instance.GetWorldUID());
			return val;
		}

		private static bool Valid(ZPackage p)
		{
			if (p.GetArray().Length <= 2200000 && p.ReadInt() == 1)
			{
				return p.ReadLong() == ZNet.instance.GetWorldUID();
			}
			return false;
		}

		private void Send(long peer, string rpc, ZPackage p)
		{
			if (peer != 0L && registered != null)
			{
				registered.InvokeRoutedRPC(peer, rpc, new object[1] { p });
			}
		}

		internal unsafe void Update()
		{
			//IL_059e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0474: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZRoutedRpc.instance == null || ZDOMan.instance == null)
			{
				return;
			}
			if (registered != ZRoutedRpc.instance)
			{
				registered = ZRoutedRpc.instance;
				registered.Register<ZPackage>("HS_Sort_v1", (Action<long, ZPackage>)ReceiveSort);
				registered.Register<ZPackage>("HS_Meta_v1", (Action<long, ZPackage>)ReceiveMetadata);
				registered.Register<ZPackage>("HS_Read_v1", (Action<long, ZPackage>)ReadMetadata);
				registered.Register<ZPackage>("HS_Prepare_v1", (Action<long, ZPackage>)Prepare);
				registered.Register<ZPackage>("HS_Ready_v1", (Action<long, ZPackage>)Ready);
				registered.Register<ZPackage>("HS_Apply_v1", (Action<long, ZPackage>)Apply);
				registered.Register<ZPackage>("HS_Applied_v1", (Action<long, ZPackage>)Applied);
				registered.Register<ZPackage>("HS_Release_v1", (Action<long, ZPackage>)Release);
				registered.Register<ZPackage>("HS_Reply_v1", (Action<long, ZPackage>)Reply);
				registered.Register<ZPackage>("HS_Hello_v1", (Action<long, ZPackage>)Hello);
				registered.Register<ZPackage>("HS_Settings_v1", (Action<long, ZPackage>)Settings);
				registered.Register<ZPackage>("HS_Probe_v1", (Action<long, ZPackage>)Probe);
				registered.Register<ZPackage>("HS_Limits_v1", (Action<long, ZPackage>)ReadStackLimits);
				registered.Register<ZPackage>("HS_LimitsReady_v1", (Action<long, ZPackage>)StackLimitsReady);
			}
			if (world != ZDOMan.instance)
			{
				world = ZDOMan.instance;
				jobs.Clear();
				queued.Clear();
				metadata.Clear();
				local.Clear();
				requests.Clear();
				rate.Clear();
				status.Clear();
				deferredDamage.Clear();
				transaction = null;
				active = null;
				settingsReceived = false;
				nextHello = (nextPump = 0f);
				wardRadius = -1f;
				settling.Clear();
				settlingChests.Clear();
				settleOrder.Clear();
			}
			if (Time.unscaledTime < nextPump)
			{
				return;
			}
			nextPump = Time.unscaledTime + 0.05f;
			if (!settingsReceived && Server != 0L && Time.unscaledTime >= nextHello)
			{
				nextHello = Time.unscaledTime + 2f;
				Send(Server, "HS_Hello_v1", Packet());
			}
			for (int num = requests.Count - 1; num >= 0; num--)
			{
				(Container, float, float) tuple = requests[num];
				if (!(Time.unscaledTime < tuple.Item2))
				{
					if (!Object.op_Implicit((Object)(object)tuple.Item1) || !GameState.LocalAccess(tuple.Item1) || (Object)(object)Patches.Current(InventoryGui.instance) == (Object)(object)tuple.Item1)
					{
						requests.RemoveAt(num);
					}
					else
					{
						CloseRequestAction closeRequestAction = SyncRecovery.CloseRequest(Time.unscaledTime, tuple.Item3, settingsReceived, GameState.InUse(tuple.Item1));
						if (closeRequestAction != CloseRequestAction.Wait)
						{
							requests.RemoveAt(num);
							if (closeRequestAction == CloseRequestAction.Expire)
							{
								Plugin instance = Plugin.Instance;
								string text = settingsReceived.ToString();
								ZDOID uid = GameState.Data(tuple.Item1).m_uid;
								instance.Warn("Distributor close request expired: settings=" + text + ", chest=" + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString());
								Plugin.Instance.Message("Sorting did not start because the chest was still busy or server settings were unavailable. Close it again to retry.");
							}
							else
							{
								ZDO val = GameState.Data(tuple.Item1);
								if (GameState.Read(val).Distributor)
								{
									ZPackage val2 = Packet();
									val2.Write(val.m_uid);
									val2.Write(++serial);
									List<ZDOID> list = Plugin.Instance.Registry.Nearby(tuple.Item1, ServerRange);
									val2.Write(list.Count);
									foreach (ZDOID item in list)
									{
										val2.Write(item);
									}
									Send(Server, "HS_Sort_v1", val2);
								}
							}
						}
					}
				}
			}
			PumpLocal();
			if (ZNet.instance.IsServer())
			{
				if (settleOrder.Count > 0)
				{
					long num2 = settleOrder.Dequeue();
					if (settling.TryGetValue(num2, out var value))
					{
						try
						{
							PumpCommitted(value);
						}
						catch (Exception e)
						{
							Plugin.Instance.Error("Background chest synchronization is retrying", e);
						}
						if (settling.ContainsKey(num2))
						{
							settleOrder.Enqueue(num2);
						}
					}
				}
				PumpServer();
			}
			for (int num3 = deferredDamage.Count - 1; num3 >= 0; num3--)
			{
				(WearNTear, HitData) tuple2 = deferredDamage[num3];
				Container val3 = (Object.op_Implicit((Object)(object)tuple2.Item1) ? ((Component)tuple2.Item1).GetComponent<Container>() : null);
				if (!Object.op_Implicit((Object)(object)val3))
				{
					deferredDamage.RemoveAt(num3);
				}
				else
				{
					ZDO val4 = GameState.Data(val3);
					if (val4 != null && !IsLocked(val4.m_uid) && (val4.IsOwner() || val4.GetOwner() != Server))
					{
						deferredDamage.RemoveAt(num3);
						tuple2.Item1.Damage(tuple2.Item2);
					}
				}
			}
		}

		internal void Queue(Container chest)
		{
			if (GameState.Supported(chest))
			{
				requests.RemoveAll(((Container Chest, float At, float Deadline) p) => (Object)(object)p.Chest == (Object)(object)chest);
				requests.Add((chest, Time.unscaledTime + 0.3f, Time.unscaledTime + 8f));
			}
		}

		internal void Publish(ZDO z)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (GameState.Supported(z) && z.IsOwner() && registered != null && Server != 0L)
			{
				ZPackage val = Packet();
				val.Write(z.m_uid);
				val.Write(GameState.Encoded(z));
				Send(Server, "HS_Meta_v1", val);
				ZDOMan.instance.ForceSendZDO(Server, z.m_uid);
			}
		}

		private void Hello(long sender, ZPackage p)
		{
			if (ZNet.instance.IsServer() && Valid(p) && ZNet.instance.IsConnected(sender))
			{
				ZPackage val = Packet();
				val.Write(Plugin.Instance.Range.Value);
				Send(sender, "HS_Settings_v1", val);
			}
		}

		private void Settings(long sender, ZPackage p)
		{
			if (sender == Server && Valid(p))
			{
				ServerRange = Mathf.Clamp(p.ReadSingle(), 5f, 50f);
				settingsReceived = true;
			}
		}

		private void ReceiveMetadata(long sender, ZPackage p)
		{
			//IL_001a: 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)
			//IL_002d: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!ZNet.instance.IsServer() || !Valid(p))
				{
					return;
				}
				ZDOID val = p.ReadZDOID();
				string text = p.ReadString();
				ZDO zDO = world.GetZDO(val);
				if (!GameState.Supported(zDO) || zDO.GetOwner() != sender)
				{
					return;
				}
				Rules rules = Rules.Decode(text);
				if (!metadata.TryGetValue(val, out var value) || value.Owner != sender || Rules.Decode(value.Rules).Revision <= rules.Revision)
				{
					if (metadata.Count >= 8192 && !metadata.ContainsKey(val))
					{
						metadata.Remove(metadata.Keys.First());
					}
					metadata[val] = new Metadata
					{
						Owner = sender,
						Rules = text
					};
				}
			}
			catch (Exception e)
			{
				Plugin.Instance.Error("Rejected chest metadata", e);
			}
		}

		private void ReadMetadata(long sender, ZPackage p)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (sender == Server && Valid(p))
				{
					ZDO zDO = world.GetZDO(p.ReadZDOID());
					if (GameState.Supported(zDO) && zDO.IsOwner())
					{
						Publish(zDO);
					}
				}
			}
			catch (Exception e)
			{
				Plugin.Instance.Error("Chest metadata response", e);
			}
		}

		private bool TryRules(ZDO z, out Rules rules)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			rules = null;
			if (!GameState.Supported(z))
			{
				return false;
			}
			string text = GameState.Encoded(z);
			if (metadata.TryGetValue(z.m_uid, out var value) && value.Owner == z.GetOwner())
			{
				Rules rules2 = Rules.Decode(value.Rules);
				Rules rules3 = Rules.Decode(text);
				rules = ((rules2.Revision >= rules3.Revision) ? rules2 : rules3);
				return true;
			}
			if (z.IsOwner() || z.GetOwner() == 0L || !ZNet.instance.IsConnected(z.GetOwner()))
			{
				rules = Rules.Decode(text);
				return true;
			}
			return false;
		}

		private void ReceiveSort(long sender, ZPackage p)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: 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_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: 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_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: 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)
			try
			{
				if (!ZNet.instance.IsServer() || !Valid(p) || !ZNet.instance.IsConnected(sender) || (rate.TryGetValue(sender, out var value) && Time.unscaledTime < value))
				{
					return;
				}
				rate[sender] = Time.unscaledTime + 0.25f;
				ZDOID val = p.ReadZDOID();
				long num = p.ReadLong();
				int num2 = p.ReadInt();
				if (num <= 0 || num2 < 0 || num2 > 256)
				{
					return;
				}
				if (IsLocked(val))
				{
					SendStatus(sender, val, "This chest is still synchronizing. Other available chests can continue sorting.");
					return;
				}
				if (settling.Count >= 8)
				{
					SendStatus(sender, val, "Sorting is waiting for several chest owners to synchronize. Try again shortly.");
					return;
				}
				if (queued.Contains(val))
				{
					SendStatus(sender, val, "This distributor already has a sorting job queued or synchronizing.");
					return;
				}
				if (jobs.Count >= 64)
				{
					SendStatus(sender, val, "The sorting queue is busy. Close the distributor again shortly.");
					return;
				}
				ZDO zDO = world.GetZDO(val);
				long num3 = PlayerId(sender);
				if (num3 == 0L || !GameState.Supported(zDO) || !NearPlayer(sender, zDO.GetPosition(), 10f) || !Access(zDO, num3))
				{
					SendStatus(sender, val, "Sorting was not started: chest access or player position could not be verified.");
					return;
				}
				List<ZDOID> list = new List<ZDOID>();
				HashSet<ZDOID> hashSet = new HashSet<ZDOID>();
				for (int i = 0; i < num2; i++)
				{
					ZDOID val2 = p.ReadZDOID();
					ZDO zDO2 = world.GetZDO(val2);
					if (val2 != val && hashSet.Add(val2) && GameState.Supported(zDO2))
					{
						Vector3 val3 = zDO2.GetPosition() - zDO.GetPosition();
						if (((Vector3)(ref val3)).sqrMagnitude <= Plugin.Instance.Range.Value * Plugin.Instance.Range.Value && Access(zDO2, num3))
						{
							list.Add(val2);
						}
					}
				}
				queued.Add(val);
				jobs.Enqueue(new Job
				{
					Peer = sender,
					Nonce = num,
					Player = num3,
					Source = val,
					Targets = list,
					Deadline = Time.unscaledTime + 30f
				});
			}
			catch (Exception e)
			{
				Plugin.Instance.Error("Rejected sort request", e);
			}
		}

		private long PlayerId(long peer)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			ZDOID val = ((peer == Self) ? ZNet.instance.LocalPlayerCharacterID : (ZNet.instance.GetPeer(peer)?.m_characterID ?? ZDOID.None));
			ZDO zDO = world.GetZDO(val);
			if (zDO == null)
			{
				return 0L;
			}
			return zDO.GetLong(ZDOVars.s_playerID, 0L);
		}

		private bool NearPlayer(long peer, Vector3 position, float distance)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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)
			ZDOID val = ((peer == Self) ? ZNet.instance.LocalPlayerCharacterID : (ZNet.instance.GetPeer(peer)?.m_characterID ?? ZDOID.None));
			ZDO zDO = world.GetZDO(val);
			if (zDO != null)
			{
				Vector3 val2 = zDO.GetPosition() - position;
				return ((Vector3)(ref val2)).sqrMagnitude <= distance * distance;
			}
			return false;
		}

		private bool Access(ZDO chest, long player)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: 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_00d9: 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_00e3: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: 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)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			Container val = GameState.Template(chest);
			if (!GameState.Supported(chest))
			{
				return false;
			}
			if (!val.m_checkGuardStone)
			{
				return true;
			}
			if (FindSector == null || !Object.op_Implicit((Object)(object)ZoneSystem.instance))
			{
				return false;
			}
			if (wardRadius < 0f)
			{
				wardRadius = 0f;
				foreach (GameObject prefab2 in ZNetScene.instance.m_prefabs)
				{
					PrivateArea val2 = (Object.op_Implicit((Object)(object)prefab2) ? prefab2.GetComponent<PrivateArea>() : null);
					if (Object.op_Implicit((Object)(object)val2))
					{
						wardRadius = Mathf.Max(wardRadius, val2.m_radius);
					}
				}
			}
			float num = wardRadius;
			if (num > 128f)
			{
				return false;
			}
			Vector3 position = chest.GetPosition();
			Vector2s zone = ZoneSystem.GetZone(position - new Vector3(num, 0f, num));
			Vector2s zone2 = ZoneSystem.GetZone(position + new Vector3(num, 0f, num));
			List<ZDO> list = new List<ZDO>();
			HashSet<SectorIndex> hashSet = new HashSet<SectorIndex>();
			for (int i = zone.x; i <= zone2.x; i++)
			{
				for (int j = zone.y; j <= zone2.y; j++)
				{
					FindSector.Invoke(world, new object[3]
					{
						(object)new Vector2s(i, j),
						list,
						hashSet
					});
				}
			}
			bool flag = false;
			foreach (ZDO item in list)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab(item.GetPrefab());
				PrivateArea val3 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<PrivateArea>() : null);
				if (!Object.op_Implicit((Object)(object)val3) || !item.GetBool(ZDOVars.s_enabled, false))
				{
					continue;
				}
				Vector3 val4 = item.GetPosition() - position;
				val4.y = 0f;
				if (((Vector3)(ref val4)).sqrMagnitude >= val3.m_radius * val3.m_radius)
				{
					continue;
				}
				flag = true;
				if (item.GetLong(ZDOVars.s_creator, 0L) == player)
				{
					return true;
				}
				int num2 = item.GetInt(ZDOVars.s_permitted, 0);
				if (num2 < 0 || num2 > 1024)
				{
					return false;
				}
				for (int k = 0; k < num2; k++)
				{
					if (item.GetLong("pu_id" + k, 0L) == player)
					{
						return true;
					}
				}
			}
			return !flag;
		}

		private unsafe void PumpServer()
		{
			//IL_00bc: 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_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0476: Unknown result type (might be due to invalid IL or missing references)
			//IL_056d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0573: Unknown result type (might be due to invalid IL or missing references)
			//IL_0578: Unknown result type (might be due to invalid IL or missing references)
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			if (transaction == null && active == null && jobs.Count == 0)
			{
				return;
			}
			Job job = active ?? ((jobs.Count > 0) ? jobs.Peek() : null);
			long timestamp = Stopwatch.GetTimestamp();
			try
			{
				if (transaction != null)
				{
					PumpTransaction();
					return;
				}
				if (active == null && jobs.Count > 0)
				{
					acti