Decompiled source of HexAutoStorage v1.1.3

Plugins/HexAutoStorage.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HexAutoStorage.Configuration;
using HexAutoStorage.Core;
using HexAutoStorage.Features;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HexAutoStorage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HexAutoStorage")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("536277cd-6e46-4758-853f-ae19c2ded793")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HexAutoStorage
{
	[BepInPlugin("com.hex.autostorage", "HexAutoStorage", "1.1.3")]
	public class Plugin : BaseUnityPlugin
	{
		private const string PluginGuid = "com.hex.autostorage";

		private const string PluginName = "HexAutoStorage";

		private const string PluginVersion = "1.1.3";

		private Harmony _harmonyInstance;

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		private void Awake()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			StorageConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmonyInstance = new Harmony("com.hex.autostorage");
			_harmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
			Log.LogInfo((object)"HexAutoStorage v1.1.3 loaded.");
		}

		private void OnDestroy()
		{
			Log.LogInfo((object)"HexAutoStorage v1.1.3 unloaded.");
			Harmony harmonyInstance = _harmonyInstance;
			if (harmonyInstance != null)
			{
				harmonyInstance.UnpatchSelf();
			}
			_harmonyInstance = null;
			Instance = null;
			Log = null;
		}
	}
	internal static class AutoStorageService
	{
		private sealed class FallbackLogState
		{
			internal float NextLogTime;
		}

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

		private static readonly ConditionalWeakTable<Smelter, FallbackLogState> FallbackLogs = new ConditionalWeakTable<Smelter, FallbackLogState>();

		internal static bool TryStore(Smelter smelter, ItemDrop producedItem, int stack)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)smelter == (Object)null || (Object)(object)producedItem == (Object)null || stack <= 0)
			{
				return false;
			}
			ZNetView componentInParent = ((Component)smelter).GetComponentInParent<ZNetView>();
			if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsValid())
			{
				return false;
			}
			List<Container> list = FindNearbyContainers(((Component)smelter).transform.position, StorageConfig.StorageRadius.Value);
			if (list.Count == 0)
			{
				LogStorageFallback(smelter, producedItem, stack, list);
				return false;
			}
			string prefabName = ((Object)((Component)producedItem).gameObject).name;
			foreach (Container item in (from container in list
				where ContainerTagEditor.HasTag(container, prefabName)
				orderby Vector3.SqrMagnitude(((Component)container).transform.position - ((Component)smelter).transform.position)
				select container).ToList())
			{
				if (TryAddToContainer(item, smelter, producedItem, stack))
				{
					StorageConfig.DebugLog($"Stored {stack}x {prefabName} in tagged container {((Object)((Component)item).gameObject).name}.");
					return true;
				}
			}
			foreach (Container item2 in (from container in list
				where !HasTags(container) && ContainsProducedItem(container, prefabName)
				orderby Vector3.SqrMagnitude(((Component)container).transform.position - ((Component)smelter).transform.position)
				select container).ToList())
			{
				if (TryAddToContainer(item2, smelter, producedItem, stack))
				{
					StorageConfig.DebugLog($"Stored {stack}x {prefabName} in untagged existing-item container {((Object)((Component)item2).gameObject).name}.");
					return true;
				}
			}
			LogStorageFallback(smelter, producedItem, stack, list);
			return false;
		}

		private static void LogStorageFallback(Smelter smelter, ItemDrop producedItem, int stack, List<Container> containers)
		{
			//IL_0168: 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)
			ConfigEntry<bool> enableDebugLogging = StorageConfig.EnableDebugLogging;
			if (enableDebugLogging == null || !enableDebugLogging.Value)
			{
				return;
			}
			FallbackLogState value = FallbackLogs.GetValue(smelter, (Smelter key) => new FallbackLogState());
			if (Time.realtimeSinceStartup < value.NextLogTime)
			{
				return;
			}
			value.NextLogTime = Time.realtimeSinceStartup + 10f;
			string name = ((Object)((Component)producedItem).gameObject).name;
			List<string> list = new List<string>();
			ItemData val = CreateProducedItemData(smelter, producedItem, stack);
			foreach (Container item in containers.OrderBy((Container candidate) => Vector3.SqrMagnitude(((Component)candidate).transform.position - ((Component)smelter).transform.position)))
			{
				string tags = ContainerTagEditor.GetTags(item);
				string text = ((!string.IsNullOrWhiteSpace(tags) && !ContainerTagEditor.HasTag(item, name)) ? "tag does not match" : ((string.IsNullOrWhiteSpace(tags) && !ContainsProducedItem(item, name)) ? "untagged and item absent" : (item.IsOwner() ? (item.GetInventory().CanAddItem(val, stack) ? "inventory rejected deposit despite capacity check" : "insufficient capacity for entire output stack") : "remote network owner")));
				list.Add($"{((Object)((Component)item).gameObject).name} at {((Component)item).transform.position} tags='{tags}': {text}");
			}
			string arg = ((list.Count == 0) ? "No supported public containers were loaded within collider range." : string.Join("; ", list));
			StorageConfig.DebugLog($"Normal ground drop: {stack}x {name} from {((Object)((Component)smelter).gameObject).name} " + $"at {((Component)smelter).transform.position}, radius {StorageConfig.StorageRadius.Value:F2}m. {arg} " + "(Drop diagnostics limited to once per station every 10 seconds.)");
		}

		private static List<Container> FindNearbyContainers(Vector3 position, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(position, radius);
			HashSet<Container> hashSet = new HashSet<Container>();
			Collider[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				Piece componentInParent = ((Component)array2[i]).GetComponentInParent<Piece>();
				if ((Object)(object)componentInParent == (Object)null)
				{
					continue;
				}
				string text = ((Object)((Component)componentInParent).gameObject).name.Replace("(Clone)", "");
				if (!StoragePrefabRules.TryGetStorageType(text, out var storageType))
				{
					continue;
				}
				Container componentInChildren = ((Component)componentInParent).GetComponentInChildren<Container>(true);
				if (IsPublicStorage(componentInChildren) && hashSet.Add(componentInChildren))
				{
					ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
					if ((Object)(object)component == (Object)null || !component.IsValid() || componentInChildren.GetInventory() == null)
					{
						hashSet.Remove(componentInChildren);
						continue;
					}
					LoadContainer.Invoke(componentInChildren, null);
					float num = Vector3.Distance(position, ((Component)componentInParent).transform.position);
					StorageConfig.DebugLog($"Found supported storage {text} ({storageType}) at {num:F2}m. Scan radius: {radius:F2}m.");
				}
			}
			return hashSet.ToList();
		}

		internal static bool IsPublicStorage(Container container)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			if ((Object)(object)container != (Object)null)
			{
				return (int)container.m_privacy == 2;
			}
			return false;
		}

		private static bool HasTags(Container container)
		{
			return !string.IsNullOrWhiteSpace(ContainerTagEditor.GetTags(container));
		}

		private static bool ContainsProducedItem(Container container, string prefabName)
		{
			if ((Object)(object)container == (Object)null)
			{
				return false;
			}
			Inventory inventory = container.GetInventory();
			if (inventory == null)
			{
				return false;
			}
			return inventory.GetItem(prefabName, -1, true) != null;
		}

		internal static ItemData CreateProducedItemData(Smelter smelter, ItemDrop producedItem, int stack)
		{
			ItemData obj = producedItem.m_itemData.Clone();
			obj.m_stack = stack;
			ZDO zDO = ((Component)smelter).GetComponentInParent<ZNetView>().GetZDO();
			obj.m_worldLevel = (byte)Game.m_worldLevel;
			obj.m_cheated = (zDO.GetBool(ZDOVars.s_cheatedQueued, false) || zDO.GetInt(ZDOVars.s_cheated, 0) == 2) && !PlayerProfile.s_bypassCheatChecks;
			return obj;
		}

		private static bool TryAddToContainer(Container container, Smelter smelter, ItemDrop producedItem, int stack)
		{
			if (!IsPublicStorage(container) || (Object)(object)producedItem == (Object)null)
			{
				return false;
			}
			if (!container.IsOwner())
			{
				StorageConfig.DebugLog("Skipped remotely owned storage " + ((Object)((Component)container).gameObject).name + "; no items were deposited.");
				return false;
			}
			Inventory inventory = container.GetInventory();
			if (inventory == null)
			{
				return false;
			}
			ItemData val = CreateProducedItemData(smelter, producedItem, stack);
			if (!inventory.CanAddItem(val, stack))
			{
				return false;
			}
			return inventory.AddItem(val);
		}
	}
}
namespace HexAutoStorage.Patches
{
	[HarmonyPatch(typeof(Container), "GetHoverText")]
	[HarmonyAfter(new string[] { "shudnal.MyLittleUI" })]
	internal static class ContainerHoverTextPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Container __instance, ref string __result)
		{
			if ((Object)(object)Plugin.Instance == (Object)null || !StorageConfig.ModEnabled.Value || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			Piece componentInParent = ((Component)__instance).GetComponentInParent<Piece>();
			if (!((Object)(object)componentInParent == (Object)null) && StoragePrefabRules.TryGetStorageType(((Object)((Component)componentInParent).gameObject).name.Replace("(Clone)", ""), out var _))
			{
				string editTagsShortcutDisplay = ContainerTagEditor.GetEditTagsShortcutDisplay();
				string text = ContainerTagEditor.GetDisplayTags(__instance);
				if (string.IsNullOrWhiteSpace(text))
				{
					text = "None";
				}
				__result = __result + "\n[<color=#ffff00ff><b>" + editTagsShortcutDisplay + "</b></color>] Edit Auto Storage Tags";
				__result = __result + "\n[<color=#ffff00ff><b>Tags:</b></color> " + text + "]";
			}
		}
	}
	[HarmonyPatch(typeof(Player), "FindHoverObject")]
	internal static class PlayerFindHoverObjectPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Player __instance, GameObject hover)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			ContainerTagEditor.HoveredObject = hover;
			if ((Object)(object)hover == (Object)null)
			{
				StorageRadiusVisualizer.HoveredSmelter = null;
				return;
			}
			Smelter componentInParent = hover.GetComponentInParent<Smelter>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				StorageRadiusVisualizer.HoveredSmelter = null;
				return;
			}
			string text = ((Object)((Component)componentInParent).gameObject).name.Replace("(Clone)", "");
			StorageConfig.DebugLog("FindHoverObject pathc Prefab name: " + text);
			if (!StoragePrefabRules.IsSupportedSmelter(text))
			{
				StorageRadiusVisualizer.HoveredSmelter = null;
			}
			else
			{
				StorageRadiusVisualizer.HoveredSmelter = componentInParent;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "Start")]
	internal static class PlayerStartPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Player __instance)
		{
			if (!((Object)(object)Plugin.Instance == (Object)null) && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && (Object)(object)((Component)__instance).GetComponent<ContainerTagEditor>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<ContainerTagEditor>();
				StorageConfig.DebugLog("ContainerTagEditor added to local player.");
			}
		}
	}
	[HarmonyPatch(typeof(Smelter), "Awake")]
	internal static class SmelterAwakePatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Smelter __instance)
		{
			if (!((Object)(object)Plugin.Instance == (Object)null) && !((Object)(object)__instance == (Object)null))
			{
				string text = ((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "");
				if (StoragePrefabRules.IsSupportedSmelter(text) && (Object)(object)((Component)__instance).GetComponent<StorageRadiusVisualizer>() == (Object)null)
				{
					((Component)__instance).gameObject.AddComponent<StorageRadiusVisualizer>();
					StorageConfig.DebugLog($"StorageRadiusVisualizer added to {text} (Instance: {((Object)__instance).GetInstanceID()}).");
				}
			}
		}
	}
	[HarmonyPatch(typeof(Smelter), "UpdateSmelter")]
	internal static class SmelterUpdateStorageReadyPatch
	{
		[HarmonyPrefix]
		internal static bool Prefix(Smelter __instance)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Plugin.Instance == (Object)null || !StorageConfig.ModEnabled.Value)
			{
				return true;
			}
			if (!StoragePrefabRules.IsSupportedSmelter(((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "")))
			{
				return true;
			}
			if ((Object)(object)ZNetScene.instance != (Object)null)
			{
				return ZNetScene.instance.IsAreaReady(((Component)__instance).transform.position);
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Smelter), "Spawn")]
	internal static class SmelterSpawnPatch
	{
		[HarmonyPrefix]
		internal static bool Prefix(Smelter __instance, string ore, int stack)
		{
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: 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)
			if ((Object)(object)Plugin.Instance == (Object)null || !StorageConfig.ModEnabled.Value)
			{
				return true;
			}
			if (!StoragePrefabRules.IsSupportedSmelter(((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "")))
			{
				return true;
			}
			ItemConversion val = null;
			foreach (ItemConversion item in __instance.m_conversion)
			{
				if ((Object)(object)item.m_from == (Object)null || ((Object)((Component)item.m_from).gameObject).name == ore)
				{
					val = item;
					break;
				}
			}
			if (val == null || (Object)(object)val.m_to == (Object)null)
			{
				return true;
			}
			if (!AutoStorageService.TryStore(__instance, val.m_to, stack))
			{
				return true;
			}
			__instance.m_produceEffects.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, (Transform)null, 1f, -1, default(ZDOID));
			return false;
		}
	}
	[HarmonyPatch(typeof(TextInput), "setText")]
	internal static class TextInputSetTextPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(string text)
		{
			if (ContainerTagEditor.IsEditing)
			{
				ContainerTagEditor.SaveTags(text);
			}
		}
	}
	[HarmonyPatch(typeof(TextInput), "Hide")]
	internal static class TextInputHidePatch
	{
		[HarmonyPostfix]
		internal static void Postfix()
		{
			if (ContainerTagEditor.IsEditing)
			{
				ContainerTagEditor.CancelEditing();
			}
		}
	}
}
namespace HexAutoStorage.Features
{
	internal class ContainerTagEditor : MonoBehaviour
	{
		private const string TagsKey = "HexAutoStorage_Tags";

		private const int MaxTagLength = 200;

		private const string SetTagsRpc = "HexAutoStorage_SetTags";

		private const string TagsResultRpc = "HexAutoStorage_TagsResult";

		private const string TagEditorTitle = "Auto Storage Tags - Example: Copper,Tin,Bronze,Iron,Silver,Blackmetal,Flametal,Coal,Flour,Eitr,Linen,Bloodgold,LiquidFrost";

		private static readonly Dictionary<string, string> ValidTags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			{ "Copper", "Copper" },
			{ "Tin", "Tin" },
			{ "Bronze", "Bronze" },
			{ "Iron", "Iron" },
			{ "Silver", "Silver" },
			{ "Blackmetal", "BlackMetal" },
			{ "Flametal", "FlametalNew" },
			{ "Coal", "Coal" },
			{ "Flour", "BarleyFlour" },
			{ "Eitr", "Eitr" },
			{ "Linen", "LinenThread" },
			{ "Bloodgold", "Gold" },
			{ "LiquidFrost", "FrozenFuel" }
		};

		private static readonly Dictionary<string, string> DisplayTags = ValidTags.ToDictionary<KeyValuePair<string, string>, string, string>((KeyValuePair<string, string> entry) => entry.Value, (KeyValuePair<string, string> entry) => entry.Key, StringComparer.OrdinalIgnoreCase);

		private static readonly MethodInfo TextInputShowMethod = AccessTools.Method(typeof(TextInput), "Show", new Type[3]
		{
			typeof(string),
			typeof(string),
			typeof(int)
		}, (Type[])null);

		private static Container _editingContainer;

		private static Container _pendingContainer;

		private static long _pendingOwner;

		private static long _requestSequence;

		private static long _pendingRequest;

		private static float _pendingSince;

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

		private static readonly FieldInfo AllWards = AccessTools.Field(typeof(PrivateArea), "m_allAreas");

		private static readonly MethodInfo WardEnabled = AccessTools.Method(typeof(PrivateArea), "IsEnabled", (Type[])null, (Type[])null);

		private static readonly MethodInfo WardContains = AccessTools.Method(typeof(PrivateArea), "IsInside", (Type[])null, (Type[])null);

		private static readonly MethodInfo WardPermitted = AccessTools.Method(typeof(PrivateArea), "IsPermitted", (Type[])null, (Type[])null);

		internal static GameObject HoveredObject;

		internal static bool IsEditing => (Object)(object)_editingContainer != (Object)null;

		internal unsafe static string GetEditTagsShortcutDisplay()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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)
			KeyboardShortcut value = StorageConfig.EditTagsShortcut.Value;
			List<string> list = ((KeyboardShortcut)(ref value)).Modifiers.Select((KeyCode modifier) => ((object)(*(KeyCode*)(&modifier))/*cast due to .constrained prefix*/).ToString()).ToList();
			list.Add(((object)((KeyboardShortcut)(ref value)).MainKey/*cast due to .constrained prefix*/).ToString());
			return string.Join(" + ", list);
		}

		private void Update()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_pendingContainer != (Object)null)
			{
				if (!(Time.realtimeSinceStartup - _pendingSince >= 10f))
				{
					return;
				}
				_pendingContainer = null;
				StorageConfig.DebugLog("Auto Storage tag save timed out without owner confirmation.");
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Auto Storage tag save was not confirmed. The chest owner must have HexAutoStorage installed. Reopen the editor to check saved tags.", 0, (Sprite)null, false);
				}
			}
			if (!((Object)(object)Plugin.Instance == (Object)null) && StorageConfig.ModEnabled.Value && !((Object)(object)Player.m_localPlayer == (Object)null) && !IsEditing)
			{
				KeyboardShortcut value = StorageConfig.EditTagsShortcut.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					TryOpenHoveredContainer();
				}
			}
		}

		private void TryOpenHoveredContainer()
		{
			if ((Object)(object)HoveredObject == (Object)null)
			{
				return;
			}
			Piece componentInParent = HoveredObject.GetComponentInParent<Piece>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return;
			}
			string text = ((Object)((Component)componentInParent).gameObject).name.Replace("(Clone)", "");
			if (!StoragePrefabRules.TryGetStorageType(text, out var _))
			{
				return;
			}
			Container componentInChildren = ((Component)componentInParent).GetComponentInChildren<Container>(true);
			ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
			if (!((Object)(object)componentInChildren == (Object)null) && !((Object)(object)component == (Object)null) && component.IsValid())
			{
				if (!CanEditTags(componentInChildren, Player.m_localPlayer))
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_cantopen", 0, (Sprite)null, false);
					return;
				}
				if ((Object)(object)TextInput.instance == (Object)null)
				{
					StorageConfig.DebugLog("Unable to open Auto Storage tag editor because TextInput.instance is null.");
					return;
				}
				_editingContainer = componentInChildren;
				TextInputShowMethod.Invoke(TextInput.instance, new object[3]
				{
					"Auto Storage Tags - Example: Copper,Tin,Bronze,Iron,Silver,Blackmetal,Flametal,Coal,Flour,Eitr,Linen,Bloodgold,LiquidFrost",
					GetDisplayTags(componentInChildren),
					200
				});
				StorageConfig.DebugLog("Opened Auto Storage tag editor for " + text + ".");
			}
		}

		private static bool TryNormalizeTags(string value, out string normalizedTags, out string invalidTag)
		{
			normalizedTags = "";
			invalidTag = "";
			if (string.IsNullOrWhiteSpace(value))
			{
				return true;
			}
			List<string> list = new List<string>();
			string[] array = value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (!string.IsNullOrWhiteSpace(text))
				{
					if (!ValidTags.TryGetValue(text, out var value2))
					{
						invalidTag = text;
						return false;
					}
					if (!list.Contains<string>(value2, StringComparer.OrdinalIgnoreCase))
					{
						list.Add(value2);
					}
				}
			}
			normalizedTags = string.Join(",", list);
			return true;
		}

		internal static string GetTags(Container container)
		{
			if (!TryGetContainerZNetView(container, out var nview))
			{
				return "";
			}
			return nview.GetZDO().GetString("HexAutoStorage_Tags", "");
		}

		internal static bool HasTag(Container container, string prefabName)
		{
			if (string.IsNullOrWhiteSpace(prefabName))
			{
				return false;
			}
			string tags = GetTags(container);
			if (string.IsNullOrWhiteSpace(tags))
			{
				return false;
			}
			return tags.Split(new char[1] { ',' }).Any((string tag) => tag.Trim().Equals(prefabName, StringComparison.OrdinalIgnoreCase));
		}

		internal static void SaveTags(string text)
		{
			if ((Object)(object)_editingContainer == (Object)null)
			{
				return;
			}
			if (!TryGetContainerZNetView(_editingContainer, out var nview))
			{
				_editingContainer = null;
				return;
			}
			if (!TryNormalizeTags(text, out var _, out var invalidTag))
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Invalid Auto Storage tag: " + invalidTag, 0, (Sprite)null, false);
				}
				StorageConfig.DebugLog("Invalid Auto Storage tag '" + invalidTag + "' rejected.");
				_editingContainer = null;
				return;
			}
			Container editingContainer = _editingContainer;
			_editingContainer = null;
			if (text == null || text.Length > 200 || !CanEditTags(editingContainer, Player.m_localPlayer))
			{
				Player localPlayer2 = Player.m_localPlayer;
				if (localPlayer2 != null)
				{
					((Character)localPlayer2).Message((MessageType)2, "Unable to edit Auto Storage tags.", 0, (Sprite)null, false);
				}
				return;
			}
			_pendingContainer = editingContainer;
			_pendingOwner = nview.GetZDO().GetOwner();
			_pendingRequest = ++_requestSequence;
			_pendingSince = Time.realtimeSinceStartup;
			StorageConfig.DebugLog($"Tag save request {_pendingRequest} for {((Object)((Component)editingContainer).gameObject).name}: " + $"requester={ZDOMan.GetSessionID()}, owner={_pendingOwner}, localOwner={nview.IsOwner()}.");
			if (nview.IsOwner())
			{
				HandleTagRequest(editingContainer, ZDOMan.GetSessionID(), _pendingRequest, text);
				return;
			}
			nview.InvokeRPC("HexAutoStorage_SetTags", new object[2] { _pendingRequest, text });
		}

		internal static void RegisterTagRpcs(Container container)
		{
			if (TryGetContainerZNetView(container, out var nview) && StoragePrefabRules.TryGetStorageType(((Object)((Component)((Component)container).GetComponentInParent<Piece>()).gameObject).name.Replace("(Clone)", ""), out var _))
			{
				nview.Register<long, string>("HexAutoStorage_SetTags", (Action<long, long, string>)delegate(long sender, long request, string text)
				{
					HandleTagRequest(container, sender, request, text);
				});
				nview.Register<long, string>("HexAutoStorage_TagsResult", (Action<long, long, string>)delegate(long sender, long request, string message)
				{
					HandleTagResult(container, sender, request, message);
				});
			}
		}

		private static void HandleTagRequest(Container container, long sender, long request, string text)
		{
			if (!((Object)(object)Plugin.Instance == (Object)null) && StorageConfig.ModEnabled.Value && TryGetContainerZNetView(container, out var nview) && nview.IsOwner())
			{
				Player player = (Player)((sender == ZDOMan.GetSessionID()) ? ((object)Player.m_localPlayer) : ((object)((IEnumerable<Player>)Player.GetAllPlayers()).FirstOrDefault((Func<Player, bool>)delegate(Player candidate)
				{
					ZNetView component = ((Component)candidate).GetComponent<ZNetView>();
					return (Object)(object)component != (Object)null && component.IsValid() && component.GetZDO().GetOwner() == sender;
				})));
				StorageConfig.DebugLog($"Owner received tag save request {request} from {sender} for {((Object)((Component)container).gameObject).name}.");
				string text2;
				string normalizedTags;
				string invalidTag;
				if (text == null || text.Length > 200 || !CanEditTags(container, player))
				{
					text2 = "Auto Storage tags were not saved: access denied or invalid request.";
				}
				else if (!TryNormalizeTags(text, out normalizedTags, out invalidTag))
				{
					text2 = "Invalid Auto Storage tag: " + invalidTag;
				}
				else
				{
					nview.GetZDO().Set("HexAutoStorage_Tags", normalizedTags);
					text2 = "Auto Storage tags saved.";
					StorageConfig.DebugLog("Owner saved Auto Storage tags '" + normalizedTags + "' to " + ((Object)((Component)container).gameObject).name + ".");
				}
				if (sender == ZDOMan.GetSessionID())
				{
					HandleTagResult(container, sender, request, text2);
					return;
				}
				nview.InvokeRPC(sender, "HexAutoStorage_TagsResult", new object[2] { request, text2 });
			}
		}

		private static void HandleTagResult(Container container, long sender, long request, string message)
		{
			if (!((Object)(object)Plugin.Instance == (Object)null) && !((Object)(object)_pendingContainer != (Object)(object)container) && sender == _pendingOwner && request == _pendingRequest)
			{
				_pendingContainer = null;
				StorageConfig.DebugLog($"Tag save response {request} from owner {sender}: {message}");
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, message, 0, (Sprite)null, false);
				}
			}
		}

		private static bool CanEditTags(Container container, Player player)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container == (Object)null || (Object)(object)player == (Object)null || Vector3.Distance(((Component)player).transform.position, ((Component)container).transform.position) > player.m_maxInteractDistance + 2f || !(bool)CheckContainerAccess.Invoke(container, new object[1] { player.GetPlayerID() }))
			{
				return false;
			}
			if (!container.m_checkGuardStone)
			{
				return true;
			}
			bool flag = false;
			foreach (PrivateArea item in (List<PrivateArea>)AllWards.GetValue(null))
			{
				if (!((Object)(object)item == (Object)null) && (bool)WardEnabled.Invoke(item, null) && (bool)WardContains.Invoke(item, new object[2]
				{
					((Component)container).transform.position,
					0f
				}))
				{
					flag = true;
					Piece component = ((Component)item).GetComponent<Piece>();
					if (((Object)(object)component != (Object)null && component.GetCreator() == player.GetPlayerID()) || (bool)WardPermitted.Invoke(item, new object[1] { player.GetPlayerID() }))
					{
						return true;
					}
				}
			}
			return !flag;
		}

		internal static void CancelEditing()
		{
			_editingContainer = null;
		}

		internal static string GetDisplayTags(Container container)
		{
			string tags = GetTags(container);
			if (string.IsNullOrWhiteSpace(tags))
			{
				return "";
			}
			List<string> list = new List<string>();
			string[] array = tags.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (DisplayTags.TryGetValue(text, out var value))
				{
					list.Add(value);
				}
				else
				{
					list.Add(text);
				}
			}
			return string.Join(",", list);
		}

		private static bool TryGetContainerZNetView(Container container, out ZNetView nview)
		{
			nview = null;
			if ((Object)(object)container == (Object)null)
			{
				return false;
			}
			if ((Object)(object)((Component)container).GetComponentInParent<Piece>() == (Object)null)
			{
				return false;
			}
			nview = (((Object)(object)container.m_rootObjectOverride != (Object)null) ? ((Component)container.m_rootObjectOverride).GetComponent<ZNetView>() : ((Component)container).GetComponent<ZNetView>());
			if ((Object)(object)nview != (Object)null)
			{
				return nview.IsValid();
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerTagRpcRegistrationPatch
	{
		[HarmonyPostfix]
		internal static void Postfix(Container __instance)
		{
			ContainerTagEditor.RegisterTagRpcs(__instance);
		}
	}
	internal class StorageRadiusVisualizer : MonoBehaviour
	{
		private const int SegmentCount = 96;

		private const float LineWidth = 0.4f;

		private const float HeightOffset = 0.05f;

		private const float RaycastHeight = 20f;

		private const float RaycastDistance = 50f;

		private LineRenderer _lineRenderer;

		private Smelter _smelter;

		private int _terrainMask;

		internal static Smelter HoveredSmelter;

		private void Awake()
		{
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			_smelter = ((Component)this).GetComponent<Smelter>();
			if ((Object)(object)_smelter == (Object)null)
			{
				StorageConfig.DebugLog("StorageRadiusVisualizer attached to non-Smelter object: " + ((Object)((Component)this).gameObject).name);
				Object.Destroy((Object)(object)this);
				return;
			}
			_terrainMask = LayerMask.GetMask(new string[1] { "terrain" });
			_lineRenderer = ((Component)this).gameObject.AddComponent<LineRenderer>();
			_lineRenderer.loop = true;
			_lineRenderer.useWorldSpace = true;
			_lineRenderer.positionCount = 96;
			_lineRenderer.startWidth = 0.4f;
			_lineRenderer.endWidth = 0.4f;
			((Renderer)_lineRenderer).material = new Material(Shader.Find("Sprites/Default"));
			((Renderer)_lineRenderer).enabled = false;
		}

		private void Update()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_0102: 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_011e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_lineRenderer == (Object)null)
			{
				return;
			}
			if ((Object)(object)Plugin.Instance == (Object)null || !StorageConfig.ModEnabled.Value || !StorageConfig.ShowStorageRadius.Value || (Object)(object)HoveredSmelter != (Object)(object)_smelter)
			{
				((Renderer)_lineRenderer).enabled = false;
				return;
			}
			((Renderer)_lineRenderer).enabled = true;
			float value = StorageConfig.StorageRadius.Value;
			RaycastHit val2 = default(RaycastHit);
			for (int i = 0; i < 96; i++)
			{
				float num = (float)i * (float)Math.PI * 2f / 96f;
				Vector3 val = ((Component)this).transform.position + new Vector3(Mathf.Cos(num) * value, 0f, Mathf.Sin(num) * value);
				if (Physics.Raycast(val + Vector3.up * 20f, Vector3.down, ref val2, 50f, _terrainMask))
				{
					val.y = ((RaycastHit)(ref val2)).point.y + 0.05f;
				}
				else
				{
					val.y = ((Component)this).transform.position.y + 0.05f;
				}
				_lineRenderer.SetPosition(i, val);
			}
		}

		private void OnDestroy()
		{
			if (!((Object)(object)_lineRenderer == (Object)null))
			{
				if ((Object)(object)((Renderer)_lineRenderer).material != (Object)null)
				{
					Object.Destroy((Object)(object)((Renderer)_lineRenderer).material);
				}
				Object.Destroy((Object)(object)_lineRenderer);
				_lineRenderer = null;
			}
		}
	}
}
namespace HexAutoStorage.Core
{
	internal enum StorageType
	{
		Chest,
		Barrel,
		Cart
	}
	internal static class StoragePrefabRules
	{
		private static readonly HashSet<string> SupportedSmelterPrefabs = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "smelter", "charcoal_kiln", "piece_FrostKiln", "blastfurnace", "windmill", "eitrrefinery", "piece_spinningwheel" };

		private static readonly Dictionary<string, StorageType> SupportedPrefabs = new Dictionary<string, StorageType>(StringComparer.OrdinalIgnoreCase)
		{
			{
				"piece_chest_wood",
				StorageType.Chest
			},
			{
				"piece_chest_barrel",
				StorageType.Barrel
			},
			{
				"piece_chest",
				StorageType.Chest
			},
			{
				"piece_chest_blackmetal",
				StorageType.Chest
			},
			{
				"piece_chest_private",
				StorageType.Chest
			},
			{
				"Cart",
				StorageType.Cart
			}
		};

		internal static bool TryGetStorageType(string prefabName, out StorageType storageType)
		{
			return SupportedPrefabs.TryGetValue(prefabName, out storageType);
		}

		internal static bool IsSupportedSmelter(string prefabName)
		{
			return SupportedSmelterPrefabs.Contains(prefabName);
		}
	}
}
namespace HexAutoStorage.Configuration
{
	internal static class StorageConfig
	{
		internal static ConfigEntry<bool> ModEnabled;

		internal static ConfigEntry<float> StorageRadius;

		internal static ConfigEntry<KeyboardShortcut> EditTagsShortcut;

		internal static ConfigEntry<bool> ShowStorageRadius;

		internal static ConfigEntry<bool> EnableDebugLogging;

		internal static void Bind(ConfigFile config)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			ModEnabled = config.Bind<bool>("General", "Enabled", true, "Enable or disable HexAutoStorage.");
			EnableDebugLogging = config.Bind<bool>("General", "EnableDebugLogging", false, "Write diagnostic logs for storage, container tags, and radius visuals. Does not change production speed.");
			StorageRadius = config.Bind<float>("General", "StorageRadius", 5f, new ConfigDescription("Radius in meters that production stations search for nearby containers.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 100f), Array.Empty<object>()));
			ShowStorageRadius = config.Bind<bool>("General", "ShowRadiusVisual", false, "Show storage radius outline.");
			EditTagsShortcut = config.Bind<KeyboardShortcut>("Input", "EditTagsShortcut", new KeyboardShortcut((KeyCode)112, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard shortcut used to edit Auto Storage tags while looking at a container. Supported tags: Copper, Tin, Bronze, Iron, Silver, Blackmetal, Flametal, Coal, Flour, Eitr, Linen, Bloodgold, LiquidFrost");
		}

		internal static void DebugLog(string message)
		{
			ConfigEntry<bool> enableDebugLogging = EnableDebugLogging;
			if (enableDebugLogging != null && enableDebugLogging.Value)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)message);
				}
			}
		}
	}
}