Decompiled source of VoidGems v2.0.2

VoidGems.dll

Decompiled 5 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CreatureManager;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;
using VoidGems.Registration;
using VoidGems.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("VoidGems")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CookieMilk")]
[assembly: AssemblyProduct("VoidGems")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")]
[assembly: AssemblyFileVersion("1.0.3")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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;
		}
	}
}
public static class ItemManagerVersion
{
	public const string Version = "1.2.9";
}
namespace VoidGems
{
	[BepInPlugin("CookieMilk.VoidGems", "VoidGems", "1.0.3")]
	public class VoidGemsPlugin : BaseUnityPlugin
	{
		private class ConfigurationManagerAttributes
		{
			public bool? Browsable;

			public string? Category;

			public Action<ConfigEntryBase>? CustomDrawer;

			public int? Order;
		}

		private class AcceptableShortcuts : AcceptableValueBase
		{
			public AcceptableShortcuts()
				: base(typeof(KeyboardShortcut))
			{
			}

			public override object Clamp(object value)
			{
				return value;
			}

			public override bool IsValid(object value)
			{
				return true;
			}

			public override string ToDescriptionString()
			{
				return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes);
			}
		}

		internal const string ModName = "VoidGems";

		internal const string ModVersion = "1.0.3";

		internal const string Author = "CookieMilk";

		private const string ModGUID = "CookieMilk.VoidGems";

		private readonly Harmony _harmony = new Harmony("CookieMilk.VoidGems");

		internal static VoidGemsPlugin? context;

		public static readonly ManualLogSource VoidGemsLogger = Logger.CreateLogSource("VoidGems");

		public const string bundleName = "vg_bundle";

		private static readonly Dictionary<string, AssetBundle> _assetBundleCache = new Dictionary<string, AssetBundle>();

		private static readonly string ConfigFileName = "CookieMilk.VoidGems.cfg";

		private static readonly string ConfigFileFullPath;

		private static readonly ConfigSync ConfigSync;

		private static ConfigEntry<bool>? _serverConfigLocked;

		private FileSystemWatcher? _watcher;

		private string _configText = "";

		private readonly object _reloadLock = new object();

		public void Awake()
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			context = this;
			_serverConfigLocked = config("01 - ServerSync", "01 - Lock Configuration", value: true, "Whether to enable or disable if the configuration is locked in which only server admins can change");
			ConfigSync.AddLockingConfigEntry<bool>(_serverConfigLocked);
			Config.RegisterAll(((BaseUnityPlugin)this).Config, "CookieMilk.VoidGems");
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(CreatureManager.LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
			ItemManager.Item.DefaultConfigurability = Configurability.Recipe | Configurability.Drop | Configurability.Trader;
			VoidGems.Registration.Item.RegisterAll("vg_bundle");
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private void OnDestroy()
		{
			SaveWithRespectToConfigSet();
			_watcher?.Dispose();
		}

		public static AssetBundle? GetAssetBundle(string filename)
		{
			if (_assetBundleCache.TryGetValue(filename, out AssetBundle value))
			{
				return value;
			}
			AssetBundle val = ((IEnumerable<AssetBundle>)Resources.FindObjectsOfTypeAll<AssetBundle>()).FirstOrDefault((Func<AssetBundle, bool>)((AssetBundle a) => ((Object)a).name == filename));
			if ((Object)(object)val != (Object)null)
			{
				_assetBundleCache[filename] = val;
				return val;
			}
			try
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(filename));
				Stream manifestResourceStream = executingAssembly.GetManifestResourceStream(name);
				AssetBundle val2 = AssetBundle.LoadFromStream(manifestResourceStream);
				_assetBundleCache[filename] = val2;
				return val2;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private void SetupWatcher()
		{
			_watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			_watcher.Changed += ReadConfigValues;
			_watcher.Created += ReadConfigValues;
			_watcher.Renamed += ReadConfigValues;
			_watcher.IncludeSubdirectories = false;
			_watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			_watcher.EnableRaisingEvents = true;
		}

		private void ReloadKeepingLocal()
		{
			List<(OwnConfigEntryBase, object)> list = new List<(OwnConfigEntryBase, object)>();
			foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in ((BaseUnityPlugin)this).Config)
			{
				if (item.Value.Description.Tags == null || item.Value.GetSerializedValue() != TomlTypeConverter.ConvertToString(item.Value.BoxedValue, item.Value.SettingType))
				{
					continue;
				}
				object[] tags = item.Value.Description.Tags;
				foreach (object obj in tags)
				{
					if (obj is OwnConfigEntryBase { LocalBaseValue: not null } ownConfigEntryBase)
					{
						list.Add((ownConfigEntryBase, ownConfigEntryBase.LocalBaseValue));
					}
				}
			}
			((BaseUnityPlugin)this).Config.Reload();
			foreach (var (ownConfigEntryBase2, localBaseValue) in list)
			{
				if (object.Equals(ownConfigEntryBase2.LocalBaseValue, ownConfigEntryBase2.BaseConfig.BoxedValue))
				{
					ownConfigEntryBase2.LocalBaseValue = localBaseValue;
				}
			}
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			lock (_reloadLock)
			{
				if (!File.Exists(ConfigFileFullPath))
				{
					VoidGemsLogger.LogWarning((object)"Config file does not exist. Skipping reload.");
				}
				else if (!(ConfigText() == _configText))
				{
					try
					{
						SaveWithRespectToConfigSet(reload: true);
						Reload.OnConfigReloaded();
					}
					catch (Exception ex)
					{
						VoidGemsLogger.LogError((object)("Error reloading configuration: " + ex.Message));
					}
					_configText = ConfigText();
				}
			}
		}

		private string ConfigText()
		{
			try
			{
				return File.ReadAllText(ConfigFileFullPath);
			}
			catch (IOException)
			{
				return _configText;
			}
		}

		private void SaveWithRespectToConfigSet(bool reload = false)
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			if (reload)
			{
				ReloadKeepingLocal();
			}
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		internal ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			SyncedConfigEntry<T> syncedConfigEntry = ConfigSync.AddConfigEntry<T>(val2);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val2;
		}

		internal ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		static VoidGemsPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConfigSync = new ConfigSync("CookieMilk.VoidGems")
			{
				DisplayName = "VoidGems",
				CurrentVersion = "1.0.3",
				MinimumRequiredVersion = "1.0.3",
				ModRequired = true
			};
		}
	}
	public static class KeyboardExtensions
	{
		public static bool IsKeyDown(this KeyboardShortcut shortcut)
		{
			//IL_0003: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			return (int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && ZInput.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey, false) && ModifiersHeld(shortcut);
		}

		public static bool IsKeyHeld(this KeyboardShortcut shortcut)
		{
			//IL_0003: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			return (int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && ZInput.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey, false) && ModifiersHeld(shortcut);
		}

		public static string Label(this KeyboardShortcut shortcut)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			return string.Join(" + ", ((KeyboardShortcut)(ref shortcut)).Modifiers.Append(((KeyboardShortcut)(ref shortcut)).MainKey).Select(KeyName));
		}

		private static bool ModifiersHeld(KeyboardShortcut shortcut)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			//IL_0021: 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_0028: 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_0041: Invalid comparison between Unknown and I4
			bool flag = (int)((KeyboardShortcut)(ref shortcut)).MainKey == 308;
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref shortcut)).Modifiers)
			{
				if (!ZInput.GetKey(modifier, false))
				{
					return false;
				}
				if ((int)modifier == 308)
				{
					flag = true;
				}
			}
			return flag || !ZInput.GetKey((KeyCode)308, false);
		}

		private unsafe static string KeyName(KeyCode key)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			string text = ZInput.KeyCodeToDisplayName(key);
			return (text.Length > 0 && text[0] != '$') ? text : ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			VoidGemsPlugin.VoidGemsLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("VoidGems_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_VoidGems_Version);
			VoidGemsPlugin.VoidGemsLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("1.0.3");
			peer.m_rpc.Invoke("VoidGems_VersionCheck", new object[1] { val });
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	public static class VerifyClient
	{
		private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance)
		{
			if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc))
			{
				return true;
			}
			VoidGemsPlugin.VoidGemsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting"));
			rpc.Invoke("Error", new object[1] { 3 });
			return false;
		}

		private static void Postfix(ZNet __instance)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "VoidGemsRequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				VoidGemsPlugin.VoidGemsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"));
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_VoidGems_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			VoidGemsPlugin.VoidGemsLogger.LogInfo((object)("Version check, local: 1.0.3,  remote: " + text));
			if (text != "1.0.3")
			{
				if (ZNet.instance.IsServer())
				{
					VoidGemsPlugin.VoidGemsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting"));
					rpc.Invoke("Error", new object[1] { 3 });
				}
			}
			else if (!ZNet.instance.IsServer())
			{
				VoidGemsPlugin.VoidGemsLogger.LogInfo((object)"Received same version from server!");
			}
			else
			{
				VoidGemsPlugin.VoidGemsLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"));
				ValidatedPeers.Add(rpc);
			}
		}
	}
}
namespace VoidGems.Utils
{
	[HarmonyPatch(typeof(Game), "RequestRespawn")]
	public static class Reload
	{
		public static bool PlayerHasSpawned { get; private set; }

		[UsedImplicitly]
		[HarmonyPriority(100)]
		private static void Postfix(bool ___m_firstSpawn)
		{
			if (___m_firstSpawn)
			{
				((MonoBehaviour)Game.instance).StartCoroutine(DelayedEnableMessages());
			}
		}

		private static IEnumerator DelayedEnableMessages()
		{
			yield return (object)new WaitForSeconds(5f);
			PlayerHasSpawned = true;
		}

		public static void OnConfigReloaded()
		{
			if (PlayerHasSpawned)
			{
				VoidGemsPlugin.VoidGemsLogger.LogInfo((object)"Configuration reloaded successfully");
			}
		}
	}
}
namespace VoidGems.Registration
{
	public static class Config
	{
		public static ConfigEntry<bool> PortalGemCooldownEnabled { get; private set; }

		public static ConfigEntry<float> PortalGemCooldown { get; private set; }

		public static ConfigEntry<T> LocalConfig<T>(string section, string key, T defaultValue, string description)
		{
			if ((Object)(object)VoidGemsPlugin.context == (Object)null)
			{
				return null;
			}
			return ((BaseUnityPlugin)VoidGemsPlugin.context).Config.Bind<T>(section, key, defaultValue, description);
		}

		public static ConfigEntry<T> LocalConfig<T>(string section, string key, T defaultValue, ConfigDescription description)
		{
			if ((Object)(object)VoidGemsPlugin.context == (Object)null || ((BaseUnityPlugin)VoidGemsPlugin.context).Config == null)
			{
				return null;
			}
			return ((BaseUnityPlugin)VoidGemsPlugin.context).Config.Bind<T>(section, key, defaultValue, description);
		}

		public static ConfigEntry<T> SyncConfig<T>(string section, string key, T defaultValue, string description)
		{
			if ((Object)(object)VoidGemsPlugin.context == (Object)null)
			{
				return null;
			}
			return VoidGemsPlugin.context.config(section, key, defaultValue, description);
		}

		public static ConfigEntry<T> SyncConfig<T>(string section, string key, T defaultValue, ConfigDescription description)
		{
			if ((Object)(object)VoidGemsPlugin.context == (Object)null)
			{
				return null;
			}
			return VoidGemsPlugin.context.config(section, key, defaultValue, description);
		}

		public static void RegisterAll(ConfigFile config, string modGuid)
		{
			PortalGemCooldownEnabled = SyncConfig("02 - Portal Gem", "01 - Cooldown", defaultValue: true, "Whether to enable or disable the cooldown between Portal Gem uses");
			PortalGemCooldown = SyncConfig("02 - Portal Gem", "02 - Cooldown Duration", 60f, "Seconds a player must wait between Portal Gem uses");
		}
	}
	public static class Item
	{
		private static readonly (string prefab, string name, string description)[] Gems = new(string, string, string)[14]
		{
			("vg_gem_mountain", "Mountain Void Gem", "A void gem from the Mountain biome"),
			("vg_gem_forest", "Forest Void Gem", "A void gem from the Forest biome"),
			("vg_gem_ash", "Ash Void Gem", "A void gem from the Ashlands biome"),
			("vg_gem_meadows", "Meadows Void Gem", "A void gem from the Meadows biome"),
			("vg_gem_mist", "Mist Void Gem", "A void gem from the Mistlands biome"),
			("vg_gem_ocean", "Ocean Void Gem", "A void gem from the Ocean biome"),
			("vg_gem_plains", "Plains Void Gem", "A void gem from the Plains biome"),
			("vg_gem_swamp", "Swamp Void Gem", "A void gem from the Swamp biome"),
			("vg_gem_cosmic_amethyst", "Cosmic Amethyst", "A rare cosmic amethyst gem"),
			("vg_gem_cosmic_opal", "Cosmic Opal", "A rare cosmic opal gem"),
			("vg_gem_cosmic_topaz", "Cosmic Topaz", "A rare cosmic topaz gem"),
			("vg_gem_cosmic_ruby", "Cosmic Ruby", "A rare cosmic ruby gem"),
			("vg_gem_portal", "Portal Gem", "A mysterious portal gem that teleports you to your bed when consumed"),
			("vg_gem_cosmic_sapphire", "Cosmic Sapphire", "A rare cosmic sapphire gem")
		};

		public static void RegisterAll(string bundleName)
		{
			(string, string, string)[] gems = Gems;
			for (int i = 0; i < gems.Length; i++)
			{
				(string, string, string) tuple = gems[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				string item3 = tuple.Item3;
				ItemManager.Item item4 = new ItemManager.Item(bundleName, item);
				item4.Name.English(item2);
				item4.Description.English(item3);
				item4.Crafting.Add(CraftingTable.Disabled, 1);
			}
		}
	}
}
namespace VoidGems.Patches
{
	public static class Misc
	{
		[HarmonyPatch(typeof(Debug), "Log", new Type[] { typeof(object) })]
		private static class Log
		{
			private static bool Prefix(object message)
			{
				return message == null || !message.ToString().Contains("PlatformUserID");
			}
		}
	}
	public static class Player
	{
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static class UseItem
		{
			private static bool Prefix(Humanoid __instance, Inventory inventory, ItemData item, bool fromInventoryGui, bool __runOriginal)
			{
				//IL_0291: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Unknown result type (might be due to invalid IL or missing references)
				//IL_029e: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
				if (!__runOriginal)
				{
					return false;
				}
				if (item == null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return true;
				}
				string text = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : item.m_shared.m_name);
				if (text != "vg_gem_portal")
				{
					return true;
				}
				Inventory val = inventory ?? __instance.m_inventory;
				if (!val.ContainsItem(item))
				{
					return true;
				}
				PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
				if (!playerProfile.HaveCustomSpawnPoint())
				{
					((Character)__instance).Message((MessageType)2, "<color=red>No bed assigned! Set your spawn point first.</color>", 0, (Sprite)null, false);
					return false;
				}
				if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)32))
				{
					((Character)__instance).Message((MessageType)2, "$msg_blocked", 0, (Sprite)null, false);
					return false;
				}
				float num = default(float);
				if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)33) && (RandEventSystem.instance.GetBossEvent() != null || (ZoneSystem.instance.GetGlobalKey((GlobalKeys)47, ref num) && num > 0f)))
				{
					((Character)__instance).Message((MessageType)2, "$msg_blockedbyboss", 0, (Sprite)null, false);
					return false;
				}
				if (!__instance.IsTeleportable(false))
				{
					((Character)__instance).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null, false);
					return false;
				}
				if (Config.PortalGemCooldownEnabled.Value)
				{
					Player val2 = (Player)(object)((__instance is Player) ? __instance : null);
					if (val2 == null)
					{
						return true;
					}
					double timeSeconds = ZNet.instance.GetTimeSeconds();
					if (val2.m_customData.TryGetValue("VoidGems_PortalGemLastUse", out var value) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && result <= timeSeconds)
					{
						float num2 = (float)((double)Config.PortalGemCooldown.Value - (timeSeconds - result));
						if (num2 > 0f)
						{
							int num3 = Mathf.FloorToInt(num2 / 60f);
							int num4 = Mathf.FloorToInt(num2 % 60f);
							string text2 = ((num3 > 0) ? $"{num3}m {num4}s" : $"{num4}s");
							((Character)__instance).Message((MessageType)2, "<color=orange>Portal Gem on cooldown! " + text2 + " remaining.</color>", 0, (Sprite)null, false);
							return false;
						}
					}
				}
				Vector3 customSpawnPoint = playerProfile.GetCustomSpawnPoint();
				Vector3 position = ((Component)__instance).transform.position;
				if (!((Character)__instance).TeleportTo(customSpawnPoint, ((Component)__instance).transform.rotation, true))
				{
					return false;
				}
				_returnTo = position;
				_bedPoint = customSpawnPoint;
				_gem = item.m_dropPrefab;
				_checkUntil = Time.time + 120f;
				val.RemoveOneItem(item);
				if (Config.PortalGemCooldownEnabled.Value)
				{
					Player.m_localPlayer.m_customData["VoidGems_PortalGemLastUse"] = ZNet.instance.GetTimeSeconds().ToString(CultureInfo.InvariantCulture);
				}
				((Character)__instance).Message((MessageType)2, "<color=green>Teleporting to bed...</color>", 0, (Sprite)null, false);
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "UpdateTeleport")]
		private static class ConfirmBed
		{
			private static void Prefix(Player __instance, float dt)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_0092: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: 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)
				if (!_returnTo.HasValue || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				if (Time.time > _checkUntil || !__instance.m_teleporting || __instance.m_teleportTargetPos != _bedPoint)
				{
					_returnTo = null;
				}
				else
				{
					if (__instance.m_teleportTimer + dt <= 8f || !ZNetScene.instance.IsAreaReady(_bedPoint))
					{
						return;
					}
					Vector3 value = _returnTo.Value;
					_returnTo = null;
					if (!((Object)(object)Game.instance.FindBedNearby(_bedPoint, 5f) != (Object)null))
					{
						__instance.m_teleportTargetPos = value;
						Game.instance.GetPlayerProfile().ClearCustomSpawnPoint();
						__instance.m_customData.Remove("VoidGems_PortalGemLastUse");
						if ((Object)(object)_gem != (Object)null)
						{
							((Humanoid)__instance).GetInventory().AddItem(_gem, 1);
						}
						((Character)__instance).Message((MessageType)2, "<color=red>Your bed is gone. The gem returns you.</color>", 0, (Sprite)null, false);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Game), "Shutdown")]
		private static class Logout
		{
			private static void Prefix()
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Player localPlayer = Player.m_localPlayer;
				if (_returnTo.HasValue && !((Object)(object)localPlayer == (Object)null) && localPlayer.m_teleporting && !(localPlayer.m_teleportTimer > 2f) && !(localPlayer.m_teleportTargetPos != _bedPoint))
				{
					_returnTo = null;
					localPlayer.m_customData.Remove("VoidGems_PortalGemLastUse");
					if ((Object)(object)_gem != (Object)null)
					{
						((Humanoid)localPlayer).GetInventory().AddItem(_gem, 1);
					}
				}
			}
		}

		private const string PortalGemLastUseKey = "VoidGems_PortalGemLastUse";

		private const float BedCheckTimeout = 120f;

		private const float LandingDelay = 8f;

		private static Vector3? _returnTo;

		private static Vector3 _bedPoint;

		private static GameObject? _gem;

		private static float _checkUntil;
	}
}
namespace ItemManager
{
	[PublicAPI]
	public enum CraftingTable
	{
		Disabled,
		Inventory,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("piece_MeadCauldron")]
		MeadCauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("piece_preptable")]
		PrepTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[PublicAPI]
	public enum ConversionPiece
	{
		Disabled,
		[InternalName("smelter")]
		Smelter,
		[InternalName("charcoal_kiln")]
		CharcoalKiln,
		[InternalName("blastfurnace")]
		BlastFurnace,
		[InternalName("windmill")]
		Windmill,
		[InternalName("piece_spinningwheel")]
		SpinningWheel,
		[InternalName("eitrrefinery")]
		EitrRefinery,
		Custom
	}
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[PublicAPI]
	public class RequiredResourceList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public bool Free;

		public void Add(string itemName, int amount, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amount = amount,
				quality = quality
			});
		}

		public void Add(string itemName, ConfigEntry<int> amountConfig, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amountConfig = amountConfig,
				quality = quality
			});
		}
	}
	[PublicAPI]
	public class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Add(CraftingTable table, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table,
				level = level
			});
		}

		public void Add(string customTable, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				level = level,
				custom = customTable
			});
		}
	}
	[PublicAPI]
	public class ItemRecipe
	{
		public readonly CraftingStationList Crafting = new CraftingStationList();

		public readonly RequiredResourceList RequiredItems = new RequiredResourceList();

		public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList();

		public int CraftAmount = 1;

		public float QualityResultAmountMultiplier = 1f;

		public ConfigEntryBase? RecipeIsActive;

		public bool RequireOnlyOneIngredient;
	}
	[PublicAPI]
	public class Trade
	{
		public uint Price;

		public string? RequiredGlobalKey;

		public uint Stack = 1u;

		public Trader Trader = Trader.None;
	}
	[PublicAPI]
	[Flags]
	public enum Trader
	{
		None = 0,
		Haldor = 1,
		Hildir = 2,
		BogWitch = 4
	}
	public struct Requirement
	{
		public string itemName;

		public int amount;

		public ConfigEntry<int>? amountConfig;

		[Description("Set to a non-zero value to apply the requirement only for a specific quality")]
		public int quality;
	}
	public struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		public string? custom;
	}
	[Flags]
	public enum Configurability
	{
		Disabled = 0,
		Recipe = 1,
		Stats = 2,
		Drop = 4,
		Trader = 8,
		Full = 0xF
	}
	[PublicAPI]
	public class DropTargets
	{
		public readonly List<DropTarget> Drops = new List<DropTarget>();

		public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true)
		{
			Drops.Add(new DropTarget
			{
				creature = creatureName,
				chance = chance,
				min = min,
				max = (max ?? min),
				levelMultiplier = levelMultiplier
			});
		}
	}
	public struct DropTarget
	{
		public string creature;

		public int min;

		public int max;

		public float chance;

		public bool levelMultiplier;
	}
	public enum Toggle
	{
		On = 1,
		Off = 0
	}
	[PublicAPI]
	public class Item
	{
		[PublicAPI]
		public enum DamageModifier
		{
			Normal,
			Resistant,
			Weak,
			Immune,
			Ignore,
			VeryResistant,
			VeryWeak,
			None
		}

		private class ItemConfig
		{
			public ConfigEntry<string>? craft;

			public ConfigEntry<string> customTable = null;

			public ConfigEntry<int>? maximumTableLevel;

			public ConfigEntry<float> qualityResultAmountMultiplier = null;

			public ConfigEntry<Toggle> requireOneIngredient = null;

			public ConfigEntry<CraftingTable> table = null;

			public ConfigEntry<int> tableLevel = null;

			public ConfigEntry<string>? upgrade;
		}

		private class TraderConfig
		{
			public ConfigEntry<uint> price = null;

			public ConfigEntry<string> requiredGlobalKey = null;

			public ConfigEntry<uint> stack = null;

			public ConfigEntry<Trader> trader = null;

			public ConfigEntry<int> value = null;
		}

		private class RequirementQuality
		{
			public int quality;
		}

		private class ConfigurationManagerAttributes
		{
			public Func<bool>? browsability;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string? Category;

			[UsedImplicitly]
			public Action<ConfigEntryBase>? CustomDrawer;

			[UsedImplicitly]
			public int? Order;
		}

		private delegate void setDmgFunc(ref DamageTypes dmg, float value);

		public class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
				: this(reqs.Split(new char[1] { ',' }).Select(delegate(string r)
				{
					string[] array = r.Split(new char[1] { ':' });
					int result;
					int result2;
					return new Requirement
					{
						itemName = array[0],
						amount = ((array.Length <= 1 || !int.TryParse(array[1], out result)) ? 1 : result),
						quality = ((array.Length > 2 && int.TryParse(array[2], out result2)) ? result2 : 0)
					};
				}).ToList())
			{
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select((Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : "")));
			}

			public static ItemDrop? fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The required item '" + name + "' does not exist."));
				}
				return val;
			}

			public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade)
			{
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_0104: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_019a: Unknown result type (might be due to invalid IL or missing references)
				//IL_019f: 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_01ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b1: Expected O, but got Unknown
				//IL_01b6: Expected O, but got Unknown
				//IL_012b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0134: Expected O, but got Unknown
				Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)((Requirement r) => r.itemName), (Func<Requirement, Requirement>)delegate(Requirement r)
				{
					//IL_000e: 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)
					//IL_0030: 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)
					ItemDrop val6 = ResItem(r);
					return (val6 == null) ? ((Requirement)null) : new Requirement
					{
						m_amount = (r.amountConfig?.Value ?? r.amount),
						m_resItem = val6,
						m_amountPerLevel = 0
					};
				});
				List<Requirement> list = dictionary.Values.Where((Requirement v) => v != null).ToList();
				foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != ""))
				{
					if (item.quality > 0)
					{
						ItemDrop val = ResItem(item);
						if (val != null)
						{
							Requirement val2 = new Requirement
							{
								m_resItem = val,
								m_amountPerLevel = (item.amountConfig?.Value ?? item.amount),
								m_amount = 0
							};
							list.Add(val2);
							requirementQuality.Add(val2, new RequirementQuality
							{
								quality = item.quality
							});
						}
						continue;
					}
					if (!dictionary.TryGetValue(item.itemName, out var value) || value == null)
					{
						ItemDrop val3 = ResItem(item);
						if (val3 != null)
						{
							string itemName = item.itemName;
							Requirement val4 = new Requirement
							{
								m_resItem = val3,
								m_amount = 0
							};
							Requirement val5 = val4;
							dictionary[itemName] = val4;
							value = val5;
							list.Add(value);
						}
					}
					if (value != null)
					{
						value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount;
					}
				}
				return list.ToArray();
				ItemDrop? ResItem(Requirement r)
				{
					return fetchByName(objectDB, r.itemName);
				}
			}
		}

		private class SerializedDrop
		{
			public readonly List<DropTarget> Drops;

			public SerializedDrop(List<DropTarget> drops)
			{
				Drops = drops;
			}

			public SerializedDrop(string drops)
			{
				Drops = ((drops == "") ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)drops.Split(new char[1] { ',' }))).Select(delegate(string r)
				{
					string[] array = r.Split(new char[1] { ':' });
					if (array.Length <= 2 || !int.TryParse(array[2], out var result))
					{
						result = 1;
					}
					if (array.Length <= 3 || !int.TryParse(array[3], out var result2))
					{
						result2 = result;
					}
					bool levelMultiplier = array.Length <= 4 || array[4] != "0";
					float result3;
					return new DropTarget
					{
						creature = array[0],
						chance = ((array.Length > 1 && float.TryParse(array[1], out result3)) ? result3 : 1f),
						min = result,
						max = result2,
						levelMultiplier = levelMultiplier
					};
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Drops.Select((DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0")));
			}

			private static Character? fetchByName(ZNetScene netScene, string name)
			{
				GameObject prefab = netScene.GetPrefab(name);
				Character val = ((prefab != null) ? prefab.GetComponent<Character>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The drop target character '" + name + "' does not exist."));
				}
				return val;
			}

			public Dictionary<Character, Drop> toCharacterDrops(ZNetScene netScene, GameObject item)
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: 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_0078: Expected O, but got Unknown
				Dictionary<Character, Drop> dictionary = new Dictionary<Character, Drop>();
				foreach (DropTarget drop in Drops)
				{
					Character val = fetchByName(netScene, drop.creature);
					if (val != null)
					{
						dictionary[val] = new Drop
						{
							m_prefab = item,
							m_amountMin = drop.min,
							m_amountMax = drop.max,
							m_chance = drop.chance,
							m_levelMultiplier = drop.levelMultiplier
						};
					}
				}
				return dictionary;
			}
		}

		private static readonly List<Item> registeredItems = new List<Item>();

		private static readonly Dictionary<ItemDrop, Item> itemDropMap = new Dictionary<ItemDrop, Item>();

		private static Dictionary<Item, Dictionary<string, List<Recipe>>> activeRecipes = new Dictionary<Item, Dictionary<string, List<Recipe>>>();

		private static Dictionary<Recipe, ConfigEntryBase?> hiddenCraftRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		private static Dictionary<Recipe, ConfigEntryBase?> hiddenUpgradeRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		private static Dictionary<Item, Dictionary<string, ItemConfig>> itemCraftConfigs = new Dictionary<Item, Dictionary<string, ItemConfig>>();

		private static Dictionary<Item, ConfigEntry<string>> itemDropConfigs = new Dictionary<Item, ConfigEntry<string>>();

		private static readonly ConditionalWeakTable<Requirement, RequirementQuality> requirementQuality = new ConditionalWeakTable<Requirement, RequirementQuality>();

		public static Configurability DefaultConfigurability = Configurability.Disabled;

		private static object? configManager;

		private static Localization? _english;

		private static BaseUnityPlugin? _plugin;

		private static bool hasConfigSync = true;

		private static object? _configSync;

		[Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")]
		public readonly DropTargets DropsFrom = new DropTargets();

		public readonly GameObject Prefab;

		private readonly Dictionary<ConfigEntryBase, Action> statsConfigs = new Dictionary<ConfigEntryBase, Action>();

		[Description("Configures whether the item can be bought at the trader.\nDon't forget to set cost to something above 0 or the item will be sold for free.")]
		public readonly Trade Trade = new Trade();

		private LocalizeKey? _description;

		private LocalizeKey? _name;

		private Dictionary<CharacterDrop, Drop> characterDrops = new Dictionary<CharacterDrop, Drop>();

		public Configurability? Configurable;

		private Configurability configurationVisible = Configurability.Full;

		internal List<ItemConversion> conversions = new List<ItemConversion>();

		internal List<Conversion> Conversions = new List<Conversion>();

		[Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")]
		public int MaximumRequiredStationLevel = int.MaxValue;

		public Dictionary<string, ItemRecipe> Recipes = new Dictionary<string, ItemRecipe>();

		private TraderConfig? traderConfig;

		private Configurability configurability => Configurable ?? DefaultConfigurability;

		[Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")]
		public RequiredResourceList RequiredItems => this[""].RequiredItems;

		[Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")]
		public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems;

		[Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")]
		public CraftingStationList Crafting => this[""].Crafting;

		[Description("Specifies a config entry which toggles whether a recipe is active.")]
		public ConfigEntryBase? RecipeIsActive
		{
			get
			{
				return this[""].RecipeIsActive;
			}
			set
			{
				this[""].RecipeIsActive = value;
			}
		}

		[Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")]
		public int CraftAmount
		{
			get
			{
				return this[""].CraftAmount;
			}
			set
			{
				this[""].CraftAmount = value;
			}
		}

		public bool RequireOnlyOneIngredient
		{
			get
			{
				return this[""].RequireOnlyOneIngredient;
			}
			set
			{
				this[""].RequireOnlyOneIngredient = value;
			}
		}

		public float QualityResultAmountMultiplier
		{
			get
			{
				return this[""].QualityResultAmountMultiplier;
			}
			set
			{
				this[""].QualityResultAmountMultiplier = value;
			}
		}

		public ItemRecipe this[string name]
		{
			get
			{
				if (Recipes.TryGetValue(name, out ItemRecipe value))
				{
					return value;
				}
				return Recipes[name] = new ItemRecipe();
			}
		}

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(shared.m_name);
				}
				else
				{
					string text = "$item_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(shared.m_name);
					shared.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(shared.m_description);
				}
				else
				{
					string text = "$itemdesc_" + ((Object)Prefab).name.Replace(" ", "_");
					_description = new LocalizeKey(text).English(shared.m_description);
					shared.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Expected O, but got Unknown
				if (_plugin == null)
				{
					IEnumerable<TypeInfo> source;
					try
					{
						source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = from t in ex.Types
							where t != null
							select t.GetTypeInfo();
					}
					_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				}
				return _plugin;
			}
		}

		private static object? configSync
		{
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		public Item(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public Item(AssetBundle bundle, string prefabName)
			: this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true)
		{
		}

		public Item(GameObject prefab, bool skipRegistering = false)
		{
			if (!skipRegistering)
			{
				PrefabManager.RegisterPrefab(prefab, addToObjectDb: true);
			}
			Prefab = prefab;
			registeredItems.Add(this);
			itemDropMap[Prefab.GetComponent<ItemDrop>()] = this;
			Prefab.GetComponent<ItemDrop>().m_itemData.m_dropPrefab = Prefab;
		}

		public void ToggleConfigurationVisibility(Configurability visible)
		{
			configurationVisible = visible;
			if (itemDropConfigs.TryGetValue(this, out ConfigEntry<string> value))
			{
				Toggle((ConfigEntryBase)(object)value, Configurability.Drop);
			}
			if (itemCraftConfigs.TryGetValue(this, out Dictionary<string, ItemConfig> value2))
			{
				foreach (ItemConfig value4 in value2.Values)
				{
					ToggleObj(value4, Configurability.Recipe);
				}
			}
			foreach (Conversion conversion in Conversions)
			{
				if (conversion.config != null)
				{
					ToggleObj(conversion.config, Configurability.Recipe);
				}
			}
			foreach (KeyValuePair<ConfigEntryBase, Action> statsConfig in statsConfigs)
			{
				Toggle(statsConfig.Key, Configurability.Stats);
				if ((visible & Configurability.Stats) != Configurability.Disabled)
				{
					statsConfig.Value();
				}
			}
			reloadConfigDisplay();
			void Toggle(ConfigEntryBase cfg, Configurability check)
			{
				object[] tags = cfg.Description.Tags;
				foreach (object obj in tags)
				{
					if (obj is ConfigurationManagerAttributes configurationManagerAttributes)
					{
						configurationManagerAttributes.Browsable = (visible & check) != Configurability.Disabled && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability());
					}
				}
			}
			void ToggleObj(object obj, Configurability check)
			{
				FieldInfo[] fields = obj.GetType().GetFields();
				foreach (FieldInfo fieldInfo in fields)
				{
					object? value3 = fieldInfo.GetValue(obj);
					ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null);
					if (val != null)
					{
						Toggle(val, check);
					}
				}
			}
		}

		internal static void reloadConfigDisplay()
		{
			if (configManager?.GetType().GetProperty("DisplayingWindow").GetValue(configManager) is int num && num != 0)
			{
				configManager.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>());
			}
		}

		public void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue)
		{
			if (!activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				return;
			}
			Recipe val = value.FirstOrDefault();
			if (!((Object)(object)val == (Object)null))
			{
				val.m_enabled = table != CraftingTable.Disabled;
				if ((uint)table <= 1u)
				{
					val.m_craftingStation = null;
				}
				else if (table == CraftingTable.Custom)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue);
					val.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
				}
				else
				{
					val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent<CraftingStation>();
				}
			}
		}

		public void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements)
		{
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements);
			}
		}

		public void UpdateStationLevel(string recipeKey, int stationLevel)
		{
			if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				Recipe val = value.FirstOrDefault();
				if ((Object)(object)val != (Object)null)
				{
					val.m_minStationLevel = stationLevel;
				}
			}
		}

		public void UpdateRequireOneIngredient(string recipeKey, bool requireOne)
		{
			if (!activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_requireOnlyOneIngredient = requireOne;
			}
		}

		public void UpdateQualityMultiplier(string recipeKey, float multiplier)
		{
			if (!activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_qualityResultAmountMultiplier = multiplier;
			}
		}

		public void UpdateCraftAmount(string recipeKey, int amount)
		{
			if (!activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List<Recipe> value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_amount = amount;
			}
		}

		internal static void Patch_FejdStartup()
		{
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			//IL_137b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1380: Unknown result type (might be due to invalid IL or missing references)
			//IL_26de: Unknown result type (might be due to invalid IL or missing references)
			//IL_26e8: Expected O, but got Unknown
			//IL_1444: Unknown result type (might be due to invalid IL or missing references)
			//IL_1447: Unknown result type (might be due to invalid IL or missing references)
			//IL_149d: Expected I4, but got Unknown
			//IL_0fe7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ff1: Expected O, but got Unknown
			//IL_15d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_15da: Unknown result type (might be due to invalid IL or missing references)
			//IL_15dc: Invalid comparison between Unknown and I4
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_052b: Expected O, but got Unknown
			//IL_1138: Unknown result type (might be due to invalid IL or missing references)
			//IL_1142: Expected O, but got Unknown
			//IL_11f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_1202: Expected O, but got Unknown
			//IL_15e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_15e4: Invalid comparison between Unknown and I4
			//IL_12c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_12cb: Expected O, but got Unknown
			//IL_17ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_17f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_17f4: Invalid comparison between Unknown and I4
			//IL_0656: Unknown result type (might be due to invalid IL or missing references)
			//IL_0660: Expected O, but got Unknown
			//IL_15e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ec: Invalid comparison between Unknown and I4
			//IL_17f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_17fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_17fe: Invalid comparison between Unknown and I4
			//IL_07e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07eb: Expected O, but got Unknown
			//IL_18e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_18e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_18ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_18ed: Invalid comparison between Unknown and I4
			//IL_1802: Unknown result type (might be due to invalid IL or missing references)
			//IL_1806: Invalid comparison between Unknown and I4
			//IL_18f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_18f5: Invalid comparison between Unknown and I4
			//IL_0a2c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a36: Expected O, but got Unknown
			//IL_094b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0955: Expected O, but got Unknown
			//IL_196a: Unknown result type (might be due to invalid IL or missing references)
			//IL_196d: Unknown result type (might be due to invalid IL or missing references)
			//IL_196f: Invalid comparison between Unknown and I4
			//IL_0b82: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b8c: Expected O, but got Unknown
			//IL_1973: Unknown result type (might be due to invalid IL or missing references)
			//IL_1977: Unknown result type (might be due to invalid IL or missing references)
			//IL_1979: Invalid comparison between Unknown and I4
			//IL_1ac8: Unknown result type (might be due to invalid IL or missing references)
			//IL_1acb: Invalid comparison between Unknown and I4
			//IL_197d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1981: Invalid comparison between Unknown and I4
			//IL_1cd0: Unknown result type (might be due to invalid IL or missing references)
			//IL_1cd7: Invalid comparison between Unknown and I4
			//IL_1da8: Unknown result type (might be due to invalid IL or missing references)
			//IL_1dad: Unknown result type (might be due to invalid IL or missing references)
			//IL_1daf: Unknown result type (might be due to invalid IL or missing references)
			//IL_1db3: Unknown result type (might be due to invalid IL or missing references)
			//IL_1db5: Invalid comparison between Unknown and I4
			//IL_1a3c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a41: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e2a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e2d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e2f: Invalid comparison between Unknown and I4
			//IL_1e33: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e37: Invalid comparison between Unknown and I4
			//IL_1e3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e3f: Invalid comparison between Unknown and I4
			//IL_22b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_22b7: Invalid comparison between Unknown and I4
			Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			if (DefaultConfigurability != Configurability.Disabled)
			{
				bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
				plugin.Config.SaveOnConfigSet = false;
				List<Item> list = registeredItems.Where((Item i) => i.configurability != Configurability.Disabled).ToList();
				foreach (Item item4 in list)
				{
					Item item = item4;
					ItemDrop itemDrop = item.Prefab.GetComponent<ItemDrop>();
					string name = itemDrop.m_itemData.m_shared.m_name;
					string englishName = new Regex("[=\\n\\t\\\"\\'\\[\\]]*").Replace(english.Localize(name), "").Trim();
					string localizedName = Localization.instance.Localize(name).Trim();
					int order = 0;
					ConfigEntry<string> nameConfig = config(englishName, "Name", itemDrop.m_itemData.m_shared.m_name, new ConfigDescription("Display name for " + englishName + ".", (AcceptableValueBase)null, new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (order -= 1),
							Category = localizedName
						}
					}));
					nameConfig.SettingChanged += delegate
					{
						itemDrop.m_itemData.m_shared.m_name = nameConfig.Value;
						item.ApplyToAllInstances(delegate(ItemData itemData)
						{
							itemData.m_shared.m_name = nameConfig.Value;
						});
					};
					ConfigEntry<string> descriptionConfig = config(englishName, "Description", itemDrop.m_itemData.m_shared.m_description, new ConfigDescription("Description for " + englishName + ".", (AcceptableValueBase)null, new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (order -= 1),
							Category = localizedName
						}
					}));
					descriptionConfig.SettingChanged += delegate
					{
						itemDrop.m_itemData.m_shared.m_description = descriptionConfig.Value;
						item.ApplyToAllInstances(delegate(ItemData itemData)
						{
							itemData.m_shared.m_description = descriptionConfig.Value;
						});
					};
					if ((item.configurability & Configurability.Recipe) != Configurability.Disabled)
					{
						itemCraftConfigs[item] = new Dictionary<string, ItemConfig>();
						foreach (string item5 in item.Recipes.Keys.DefaultIfEmpty(""))
						{
							string configKey = item5;
							string text = ((configKey == "") ? "" : (" (" + configKey + ")"));
							if (!item.Recipes.ContainsKey(configKey) || item.Recipes[configKey].Crafting.Stations.Count <= 0)
							{
								continue;
							}
							ItemConfig itemConfig = (itemCraftConfigs[item][configKey] = new ItemConfig());
							ItemConfig cfg = itemConfig;
							List<ConfigurationManagerAttributes> hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
							ItemConfig itemConfig3 = cfg;
							string text2 = englishName;
							string name2 = "Crafting Station" + text;
							CraftingTable table = item.Recipes[configKey].Crafting.Stations.First().Table;
							string text3 = "Crafting station where " + englishName + " is available.";
							object[] array = new object[1];
							ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes();
							int num = order - 1;
							order = num;
							configurationManagerAttributes.Order = num;
							configurationManagerAttributes.Browsable = (item.configurationVisible & Configurability.Recipe) != 0;
							configurationManagerAttributes.Category = localizedName;
							array[0] = configurationManagerAttributes;
							itemConfig3.table = config(text2, name2, table, new ConfigDescription(text3, (AcceptableValueBase)null, array));
							ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes();
							num = order - 1;
							order = num;
							configurationManagerAttributes2.Order = num;
							configurationManagerAttributes2.browsability = CustomTableBrowsability;
							configurationManagerAttributes2.Browsable = CustomTableBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0;
							configurationManagerAttributes2.Category = localizedName;
							ConfigurationManagerAttributes customTableAttributes = configurationManagerAttributes2;
							cfg.customTable = config(englishName, "Custom Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
							cfg.table.SettingChanged += TableConfigChanged;
							cfg.customTable.SettingChanged += TableConfigChanged;
							ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes();
							num = order - 1;
							order = num;
							configurationManagerAttributes3.Order = num;
							configurationManagerAttributes3.browsability = TableLevelBrowsability;
							configurationManagerAttributes3.Browsable = TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0;
							configurationManagerAttributes3.Category = localizedName;
							ConfigurationManagerAttributes configurationManagerAttributes4 = configurationManagerAttributes3;
							hideWhenNoneAttributes.Add(configurationManagerAttributes4);
							cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes4 }));
							cfg.tableLevel.SettingChanged += delegate
							{
								if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List<Recipe> value2))
								{
									value2.First().m_minStationLevel = cfg.tableLevel.Value;
								}
							};
							if (item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1)
							{
								cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item.MaximumRequiredStationLevel == int.MaxValue) ? (item.Recipes[configKey].Crafting.Stations.First().level + item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality - 1) : item.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes4 }));
							}
							ItemConfig itemConfig4 = cfg;
							string text4 = englishName;
							string name3 = "Require only one resource" + text;
							int value = (item.Recipes[configKey].RequireOnlyOneIngredient ? 1 : 0);
							string text5 = "Whether only one of the ingredients is needed to craft " + englishName;
							object[] array2 = new object[1];
							ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes();
							num = order - 1;
							order = num;
							configurationManagerAttributes5.Order = num;
							configurationManagerAttributes5.Category = localizedName;
							array2[0] = configurationManagerAttributes5;
							itemConfig4.requireOneIngredient = config(text4, name3, (Toggle)value, new ConfigDescription(text5, (AcceptableValueBase)null, array2));
							ConfigurationManagerAttributes configurationManagerAttributes6 = new ConfigurationManagerAttributes();
							num = order - 1;
							order = num;
							configurationManagerAttributes6.Order = num;
							configurationManagerAttributes6.browsability = QualityResultBrowsability;
							configurationManagerAttributes6.Browsable = QualityResultBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0;
							configurationManagerAttributes6.Category = localizedName;
							ConfigurationManagerAttributes qualityResultAttributes = configurationManagerAttributes6;
							cfg.requireOneIngredient.SettingChanged += delegate
							{
								if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List<Recipe> value2))
								{
									foreach (Recipe item6 in value2)
									{
										item6.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On;
									}
								}
								qualityResultAttributes.Browsable = QualityResultBrowsability();
								reloadConfigDisplay();
							};
							cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes }));
							cfg.qualityResultAmountMultiplier.SettingChanged += delegate
							{
								if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List<Recipe> value2))
								{
									foreach (Recipe item7 in value2)
									{
										item7.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value;
									}
								}
							};
							if ((!item.Recipes[configKey].RequiredItems.Free || item.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.craft = itemConfig5("Crafting Costs" + text, new SerializedRequirements(item.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false);
							}
							if (item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1 && (!item.Recipes[configKey].RequiredUpgradeItems.Free || item.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.upgrade = itemConfig5("Upgrading Costs" + text, new SerializedRequirements(item.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName, isUpgrade: true);
							}
							if (cfg.craft != null)
							{
								cfg.craft.SettingChanged += ConfigChanged;
							}
							if (cfg.upgrade != null)
							{
								cfg.upgrade.SettingChanged += ConfigChanged;
							}
							void ConfigChanged(object o, EventArgs e)
							{
								item.UpdateCraftConfig(configKey, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? ""));
							}
							bool CustomTableBrowsability()
							{
								return cfg.table.Value == CraftingTable.Custom;
							}
							bool ItemBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							bool QualityResultBrowsability()
							{
								return cfg.requireOneIngredient.Value == Toggle.On;
							}
							void TableConfigChanged(object o, EventArgs e)
							{
								item.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value);
								customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom;
								foreach (ConfigurationManagerAttributes item8 in hideWhenNoneAttributes)
								{
									item8.Browsable = cfg.table.Value != CraftingTable.Disabled;
								}
								reloadConfigDisplay();
							}
							bool TableLevelBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							ConfigEntry<string> itemConfig5(string name4, string value2, string desc, bool isUpgrade)
							{
								//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
								//IL_00ec: Expected O, but got Unknown
								ConfigurationManagerAttributes obj = new ConfigurationManagerAttributes
								{
									CustomDrawer = drawRequirementsConfigTable(item, isUpgrade)
								};
								int num5 = order - 1;
								order = num5;
								obj.Order = num5;
								obj.browsability = ItemBrowsability;
								obj.Browsable = ItemBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0;
								obj.Category = localizedName;
								ConfigurationManagerAttributes configurationManagerAttributes8 = obj;
								hideWhenNoneAttributes.Add(configurationManagerAttributes8);
								return config(englishName, name4, value2, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes8 }));
							}
						}
						if ((item.configurability & Configurability.Drop) != Configurability.Disabled)
						{
							ConfigEntry<string> val = (itemDropConfigs[item] = config(englishName, "Drop from", new SerializedDrop(item.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									CustomDrawer = drawDropsConfigTable,
									Category = localizedName,
									Browsable = ((item.configurationVisible & Configurability.Drop) != 0)
								}
							})));
							ConfigEntry<string> val3 = val;
							val3.SettingChanged += delegate
							{
								item.UpdateCharacterDrop();
							};
						}
						for (int num2 = 0; num2 < item.Conversions.Count; num2++)
						{
							string text6 = ((item.Conversions.Count > 1) ? $"{num2 + 1}. " : "");
							Conversion conversion = item.Conversions[num2];
							conversion.config = new Conversion.ConversionConfig();
							int index = num2;
							conversion.config.input = config(englishName, text6 + "Conversion Input Item", conversion.Input, new ConfigDescription("Input item to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.input.SettingChanged += delegate
							{
								if (index < item.conversions.Count)
								{
									ObjectDB instance = ObjectDB.instance;
									if (instance != null)
									{
										ItemDrop val4 = SerializedRequirements.fetchByName(instance, conversion.config.input.Value);
										item.conversions[index].m_from = val4;
										UpdatePiece();
									}
								}
							};
							conversion.config.piece = config(englishName, text6 + "Conversion Piece", conversion.Piece, new ConfigDescription("Conversion piece used to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.piece.SettingChanged += delegate
							{
								UpdatePiece();
							};
							conversion.config.customPiece = config(englishName, text6 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Custom conversion piece to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.customPiece.SettingChanged += delegate
							{
								UpdatePiece();
							};
							void UpdatePiece()
							{
								if (index < item.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance))
								{
									string text9 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value)));
									string activePiece = conversion.config.activePiece;
									if (conversion.config.activePiece != null)
									{
										Smelter component = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent<Smelter>();
										int num5 = component.m_conversion.IndexOf(item.conversions[index]);
										if (num5 >= 0)
										{
											Smelter[] array6 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val4 in array6)
											{
												if (Utils.GetPrefabName(((Component)val4).gameObject) == activePiece)
												{
													val4.m_conversion.RemoveAt(num5);
												}
											}
										}
										conversion.config.activePiece = null;
									}
									if (item.conversions[index].m_from != null && conversion.config.piece.Value != ConversionPiece.Disabled)
									{
										GameObject prefab = ZNetScene.instance.GetPrefab(text9);
										if (((prefab != null) ? prefab.GetComponent<Smelter>() : null) != null)
										{
											conversion.config.activePiece = text9;
											Smelter[] array7 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val5 in array7)
											{
												if (Utils.GetPrefabName(((Component)val5).gameObject) == text9)
												{
													val5.m_conversion.Add(item.conversions[index]);
												}
											}
										}
									}
								}
							}
						}
					}
					if ((item.configurability & Configurability.Stats) != Configurability.Disabled)
					{
						item.statsConfigs.Clear();
						SharedData shared = item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
						ItemType itemType = shared.m_itemType;
						statcfg<float>("Weight", "Weight of " + englishName + ".", (SharedData val4) => val4.m_weight, delegate(SharedData val4, float weight)
						{
							val4.m_weight = weight;
						});
						statcfg<int>("Trader Value", "Trader value of " + englishName + ".", (SharedData val4) => val4.m_value, delegate(SharedData val4, int value2)
						{
							val4.m_value = value2;
						});
						bool flag;
						switch (itemType - 3)
						{
						case 0:
						case 1:
						case 2:
						case 3:
						case 4:
						case 8:
						case 9:
						case 11:
						case 14:
						case 16:
						case 19:
							flag = true;
							break;
						default:
							flag = false;
							break;
						}
						if (flag)
						{
							statcfg<float>("Durability", "Durability of " + englishName + ".", (SharedData val4) => val4.m_maxDurability, delegate(SharedData val4, float maxDurability)
							{
								val4.m_maxDurability = maxDurability;
							});
							statcfg<float>("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData val4) => val4.m_durabilityPerLevel, delegate(SharedData val4, float durabilityPerLevel)
							{
								val4.m_durabilityPerLevel = durabilityPerLevel;
							});
							statcfg<float>("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData val4) => val4.m_movementModifier, delegate(SharedData val4, float movementModifier)
							{
								val4.m_movementModifier = movementModifier;
							});
						}
						if ((itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22) ? true : false)
						{
							statcfg<float>("Block Armor", "Block armor of " + englishName + ".", (SharedData val4) => val4.m_blockPower, delegate(SharedData val4, float blockPower)
							{
								val4.m_blockPower = blockPower;
							});
							statcfg<float>("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData val4) => val4.m_blockPowerPerLevel, delegate(SharedData val4, float blockPowerPerLevel)
							{
								val4.m_blockPowerPerLevel = blockPowerPerLevel;
							});
							statcfg<float>("Block Force", "Block force of " + englishName + ".", (SharedData val4) => val4.m_deflectionForce, delegate(SharedData val4, float deflectionForce)
							{
								val4.m_deflectionForce = deflectionForce;
							});
							statcfg<float>("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData val4) => val4.m_deflectionForcePerLevel, delegate(SharedData val4, float deflectionForcePerLevel)
							{
								val4.m_deflectionForcePerLevel = deflectionForcePerLevel;
							});
							statcfg<float>("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData val4) => val4.m_timedBlockBonus, delegate(SharedData val4, float timedBlockBonus)
							{
								val4.m_timedBlockBonus = timedBlockBonus;
							});
						}
						else if ((itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false)
						{
							statcfg<float>("Armor", "Armor of " + englishName + ".", (SharedData val4) => val4.m_armor, delegate(SharedData val4, float armor)
							{
								val4.m_armor = armor;
							});
							statcfg<float>("Armor per Level", "Armor per level for " + englishName + ".", (SharedData val4) => val4.m_armorPerLevel, delegate(SharedData val4, float armorPerLevel)
							{
								val4.m_armorPerLevel = armorPerLevel;
							});
						}
						SkillType skillType = shared.m_skillType;
						if (((int)skillType == 7 || (int)skillType == 12) ? true : false)
						{
							statcfg<int>("Tool tier", "Tool tier of " + englishName + ".", (SharedData val4) => val4.m_toolTier, delegate(SharedData val4, int toolTier)
							{
								val4.m_toolTier = toolTier;
							});
						}
						if ((itemType - 5 <= 2 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false)
						{
							Dictionary<DamageType, DamageModifier> modifiers = shared.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier);
							DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType));
							DamageType[] array3 = new DamageType[5];
							RuntimeHelpers.InitializeArray(array3, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
							foreach (DamageType damageType in first.Except((IEnumerable<DamageType>)(object)array3))
							{
								statcfg<DamageModifier>(((object)Unsafe.As<DamageType, DamageType>(ref damageType)/*cast due to .constrained prefix*/).ToString() + " Resistance", ((object)Unsafe.As<DamageType, DamageType>(ref damageType)/*cast due to .constrained prefix*/).ToString() + " resistance of " + englishName + ".", (SharedData _) => modifiers.TryGetValue(damageType, out var value2) ? value2 : DamageModifier.None, delegate(SharedData val5, DamageModifier damageModifier)
								{
									//IL_0003: 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_0019: Unknown result type (might be due to invalid IL or missing references)
									//IL_001e: Unknown result type (might be due to invalid IL or missing references)
									//IL_001f: Unknown result type (might be due to invalid IL or missing references)
									//IL_002b: Unknown result type (might be due to invalid IL or missing references)
									//IL_0030: Unknown result type (might be due to invalid IL or missing references)
									//IL_0036: Unknown result type (might be due to invalid IL or missing references)
									//IL_0096: Unknown result type (might be due to invalid IL or missing references)
									//IL_0062: Unknown result type (might be due to invalid IL or missing references)
									DamageModPair val4 = new DamageModPair
									{
										m_type = damageType,
										m_modifier = (DamageModifier)damageModifier
									};
									for (int i = 0; i < val5.m_damageModifiers.Count; i++)
									{
										if (val5.m_damageModifiers[i].m_type == damageType)
										{
											if (damageModifier == DamageModifier.None)
											{
												val5.m_damageModifiers.RemoveAt(i);
											}
											else
											{
												val5.m_damageModifiers[i] = val4;
											}
											return;
										}
									}
									if (damageModifier != DamageModifier.None)
									{
										val5.m_damageModifiers.Add(val4);
									}
								});
							}
						}
						if ((int)itemType == 2 && shared.m_food > 0f)
						{
							statcfg<float>("Health", "Health value of " + englishName + ".", (SharedData val4) => val4.m_food, delegate(SharedData val4, float food)
							{
								val4.m_food = food;
							});
							statcfg<float>("Stamina", "Stamina value of " + englishName + ".", (SharedData val4) => val4.m_foodStamina, delegate(SharedData val4, float foodStamina)
							{
								val4.m_foodStamina = foodStamina;
							});
							statcfg<float>("Eitr", "Eitr value of " + englishName + ".", (SharedData val4) => val4.m_foodEitr, delegate(SharedData val4, float foodEitr)
							{
								val4.m_foodEitr = foodEitr;
							});
							statcfg<float>("Duration", "Duration of " + englishName + ".", (SharedData val4) => val4.m_foodBurnTime, delegate(SharedData val4, float foodBurnTime)
							{
								val4.m_foodBurnTime = foodBurnTime;
							});
							statcfg<float>("Health Regen", "Health regen value of " + englishName + ".", (SharedData val4) => val4.m_foodRegen, delegate(SharedData val4, float foodRegen)
							{
								val4.m_foodRegen = foodRegen;
							});
						}
						if ((int)shared.m_skillType == 10)
						{
							statcfg<float>("Health Cost", "Health cost of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackHealth, delegate(SharedData val4, float attackHealth)
							{
								val4.m_attack.m_attackHealth = attackHealth;
							});
							statcfg<float>("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackHealthPercentage, delegate(SharedData val4, float attackHealthPercentage)
							{
								val4.m_attack.m_attackHealthPercentage = attackHealthPercentage;
							});
						}
						skillType = shared.m_skillType;
						if (skillType - 9 <= 1)
						{
							statcfg<float>("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackEitr, delegate(SharedData val4, float attackEitr)
							{
								val4.m_attack.m_attackEitr = attackEitr;
							});
						}
						if ((itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22) ? true : false)
						{
							statcfg<float>("Knockback", "Knockback of " + englishName + ".", (SharedData val4) => val4.m_attackForce, delegate(SharedData val4, float attackForce)
							{
								val4.m_attackForce = attackForce;
							});
							statcfg<float>("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData val4) => val4.m_backstabBonus, delegate(SharedData val4, float backstabBonus)
							{
								val4.m_backstabBonus = backstabBonus;
							});
							statcfg<float>("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackStamina, delegate(SharedData val4, float attackStamina)
							{
								val4.m_attack.m_attackStamina = attackStamina;
							});
							SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float damage)
							{
								dmg.m_damage = damage;
							});
							SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float slash)
							{
								dmg.m_slash = slash;
							});
							SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float pierce)
							{
								dmg.m_pierce = pierce;
							});
							SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float blunt)
							{
								dmg.m_blunt = blunt;
							});
							SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float chop)
							{
								dmg.m_chop = chop;
							});
							SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float pickaxe)
							{
								dmg.m_pickaxe = pickaxe;
							});
							SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float fire)
							{
								dmg.m_fire = fire;
							});
							SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float poison)
							{
								dmg.m_poison = poison;
							});
							SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float frost)
							{
								dmg.m_frost = frost;
							});
							SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float lightning)
							{
								dmg.m_lightning = lightning;
							});
							SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float spirit)
							{
								dmg.m_spirit = spirit;
							});
							if ((int)itemType == 4)
							{
								statcfg<int>("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData val4) => val4.m_attack.m_projectileBursts, delegate(SharedData val4, int projectileBursts)
								{
									val4.m_attack.m_projectileBursts = projectileBursts;
								});
								statcfg<float>("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData val4) => val4.m_attack.m_burstInterval, delegate(SharedData val4, float burstInterval)
								{
									val4.m_attack.m_burstInterval = burstInterval;
								});
								statcfg<float>("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileAccuracyMin, delegate(SharedData val4, float projectileAccuracyMin)
								{
									val4.m_attack.m_projectileAccuracyMin = projectileAccuracyMin;
								});
								statcfg<float>("Accuracy", "Accuracy for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileAccuracy, delegate(SharedData val4, float projectileAccuracy)
								{
									val4.m_attack.m_projectileAccuracy = projectileAccuracy;
								});
								statcfg<float>("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileVelMin, delegate(SharedData val4, float projectileVelMin)
								{
									val4.m_attack.m_projectileVelMin = projectileVelMin;
								});
								statcfg<float>("Velocity", "Velocity for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileVel, delegate(SharedData val4, float projectileVel)
								{
									val4.m_attack.m_projectileVel = projectileVel;
								});
								statcfg<float>("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData val4) => val4.m_attack.m_drawDurationMin, delegate(SharedData val4, float drawDurationMin)
								{
									val4.m_attack.m_drawDurationMin = drawDurationMin;
								});
								statcfg<float>("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData val4) => val4.m_attack.m_drawStaminaDrain, delegate(SharedData val4, float drawStaminaDrain)
								{
									val4.m_attack.m_drawStaminaDrain = drawStaminaDrain;
								});
							}
						}
					}
					List<ConfigurationManagerAttributes> traderAttributes;
					if ((item.configurability & Configurability.Trader) != Configurability.Disabled)
					{
						traderAttributes = new List<ConfigurationManagerAttributes>();
						Item item2 = item;
						TraderConfig traderConfig = new TraderConfig();
						string text7 = englishName;
						Trader trader = item.Trade.Trader;
						string text8 = "Which traders sell " + englishName + ".";
						object[] array4 = new object[1];
						ConfigurationManagerAttributes configurationManagerAttributes7 = new ConfigurationManagerAttributes();
						int num = order - 1;
						order = num;
						configurationManagerAttributes7.Order = num;
						configurationManagerAttributes7.Browsable = (item.configurationVisible & Configurability.Trader) != 0;
						configurationManagerAttributes7.Category = localizedName;
						array4[0] = configurationManagerAttributes7;
						traderConfig.trader = config(text7, "Trader Selling", trader, new ConfigDescription(text8, (AcceptableValueBase)null, array4));
						item2.traderConfig = traderConfig;
						item.traderConfig.trader.SettingChanged += delegate
						{
							item.ReloadTraderConfiguration();
							foreach (ConfigurationManagerAttributes item9 in traderAttributes)
							{
								item9.Browsable = TraderBrowsability();
							}
							reloadConfigDisplay();
						};
						item.traderConfig.price = traderConfig2<uint>("Trader Price", item.Trade.Price, "Price of " + englishName + " at the trader.");
						item.traderConfig.stack = traderConfig2<uint>("Trader Stack", item.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction.");
						item.traderConfig.requiredGlobalKey = traderConfig2<string>("Trader Required Global Key", item.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader.");
						item.traderConfig.value = traderConfig2<int>("Trader Value", item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_value, "Value of " + englishName + " when sold to the trader (what Haldor buys it for).");
						if (item.traderConfig.trader.Value != Trader.None)
						{
							PrefabManager.AddItemToTrader(item.Prefab, item.traderConfig.trader.Value, item.traderConfig.price.Value, item.traderConfig.stack.Value, item.traderConfig.requiredGlobalKey.Value);
						}
					}
					else if (item.Trade.Trader != Trader.None)
					{
						PrefabManager.AddItemToTrader(item.Prefab, item.Trade.Trader, item.Trade.Price, item.Trade.Stack, item.Trade.RequiredGlobalKey);
					}
					void SetDmg(string dmgType, Func<DamageTypes, float> readDmg, setDmgFunc setDmg)
					{
						statcfg<float>(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData val4) => readDmg(val4.m_damages), delegate(SharedData val4, float value2)
						{
							setDmg(ref val4.m_damages, value2);
						});
						statcfg<float>(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData val4) => readDmg(val4.m_damagesPerLevel), delegate(SharedData val4, float value2)
						{
							setDmg(ref val4.m_damagesPerLevel, value2);
						});
					}
					bool TraderBrowsability()
					{
						return item.traderConfig.trader.Value != Trader.None;
					}
					void statcfg<T>(string configName, string description, Func<SharedData, T> readDefault, Action<SharedData, T> setValue) where T : notnull
					{
						//IL_0081: Unknown result type (might be due to invalid IL or missing references)
						//IL_008b: Expected O, but got Unknown
						SharedData shared2 = item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
						ConfigEntry<T> cfg2 = config(englishName, configName, readDefault(shared2), new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
						{
							new ConfigurationManagerAttributes
							{
								Category = localizedName,
								Browsable = ((item.configurationVisible & Configurability.Stats) != 0)
							}
						}));
						if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled)
						{
							setValue(shared2, cfg2.Value);
						}
						item.statsConfigs.Add((ConfigEntryBase)(object)cfg2, ApplyConfig);
						cfg2.SettingChanged += delegate
						{
							if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled)
							{
								ApplyConfig();
							}
						};
						void ApplyConfig()
						{
							item.ApplyToAllInstances(delegate(ItemData val4)
							{
								setValue(val4.m_shared, cfg2.Value);
							});
						}
					}
					ConfigEntry<T> traderConfig2<T>(string name4, T value2, string desc) where T : notnull
					{
						//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
						//IL_00c4: Expected O, but got Unknown
						ConfigurationManagerAttributes configurationManagerAttributes8 = new ConfigurationManagerAttributes();
						int num5 = order - 1;
						order = num5;
						configurationManagerAttributes8.Order = num5;
						configurationManagerAttributes8.browsability = TraderBrowsability;
						configurationManagerAttributes8.Browsable = TraderBrowsability() && (item.configurationVisible & Configurability.Trader) != 0;
						configurationManagerAttributes8.Category = localizedName;
						ConfigurationManagerAttributes configurationManagerAttributes9 = configurationManagerAttributes8;
						traderAttributes.Add(configurationManagerAttributes9);
						ConfigEntry<T> val4 = config(englishName, name4, value2, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes9 }));
						val4.SettingChanged += delegate
						{
							item.ReloadTraderConfiguration();
						};
						return val4;
					}
				}
				if (saveOnConfigSet)
				{
					plugin.Config.SaveOnConfigSet = true;
					plugin.Config.Save();
				}
			}
			configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type));
			foreach (Item registeredItem in registeredItems)
			{
				Item item3 = registeredItem;
				foreach (KeyValuePair<string, ItemRecipe> recipe in item3.Recipes)
				{
					KeyValuePair<string, ItemRecipe> kv = recipe;
					RequiredResourceList[] array5 = new RequiredResourceList[2]
					{
						kv.Value.RequiredItems,
						kv.Value.RequiredUpgradeItems
					};
					foreach (RequiredResourceList requiredResourceList in array5)
					{
						for (int num4 = 0; num4 < requiredResourceList.Requirements.Count; num4++)
						{
							ConfigEntry<int> amountCfg;
							int resourceIndex;
							if ((item3.configurability & Configurability.Recipe) != Configurability.Disabled)
							{
								amountCfg = requiredResourceList.Requirements[num4].amountConfig;
								if (amountCfg != null)
								{
									resourceIndex = num4;
									amountCfg.SettingChanged += ConfigChanged2;
								}
							}
							void ConfigChanged2(object o, EventArgs e)
							{
								if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(kv.Key, out List<Recipe> value2))
								{
									foreach (Recipe item10 in value2)
									{
										item10.m_resources[resourceIndex].m_amount = amountCfg.Value;
									}
								}
							}
						}
					}
				}
				item3.InitializeNewRegisteredItem();
			}
		}

		private void InitializeNewRegisteredItem()
		{
			foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes)
			{
				KeyValuePair<string, ItemRecipe> kv = recipe;
				ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive;
				if (enabledCfg != null)
				{
					((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged));
				}
				void ConfigChanged(object o, EventArgs e)
				{
					if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out List<Recipe> value))
					{
						object boxedValue = enabledCfg.BoxedValue;
						bool enabled = ((boxedValue is bool flag) ? flag : (boxedValue is int num && num != 0));
						foreach (Recipe item in value)
						{
							item.m_enabled = enabled;
						}
					}
				}
			}
		}

		public void ReloadCraftingConfiguration()
		{
			if (Object.op_Implicit((Object)(object)ObjectDB.instance) && ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name)) == null)
			{
				registerRecipesInObjectDB(ObjectDB.instance);
				ObjectDB.instance.m_items.Add(Prefab);
				ObjectDB.instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab);
				if (!ZNetScene.instance.m_prefabs.Contains(Prefab))
				{
					ZNetScene.instance.m_prefabs.Add(Prefab);
				}
				int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)Prefab).name);
				if (!ZNetScene.instance.m_namedPrefabs.ContainsKey(stableHashCode))
				{
					ZNetScene.instance.m_namedPrefabs.Add(stableHashCode, Prefab);
				}
				else
				{
					ZNetScene.instance.m_namedPrefabs[stableHashCode] = Prefab;
				}
			}
			foreach (string item in Recipes.Keys.DefaultIfEmpty(""))
			{
				if (Recipes.TryGetValue(item, out ItemRecipe value) && value.Crafting.Stations.Count > 0)
				{
					UpdateItemTableConfig(item, value.Crafting.Stations.First().Table, value.Crafting.Stations.First().custom ?? "");
					UpdateCraftConfig(item, new SerializedRequirements(value.RequiredItems.Requirements), new SerializedRequirements(value.RequiredUpgradeItems.Requirements));
				}
			}
		}

		public void ReloadTraderConfiguration()
		{
			if (traderConfig.trader.Value == Trader.None)
			{
				PrefabManager.RemoveItemFromTrader(Prefab);
			}
			else
			{
				PrefabManager.AddItemToTrader(Prefab, traderConfig.trader.Value, traderConfig.price.Value, traderConfig.stack.Value, traderConfig.requiredGlobalKey.Value);
			}
		}

		public static void ApplyToAllInstances(GameObject prefab, Action<ItemData> callback)
		{
			callback(prefab.GetComponent<ItemDrop>().m_itemData);
			string name = prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
			Inventory[] source = (from c in Player.s_players.Select((Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsByType<Container>((FindObjectsSortMode)0)
					select c.GetInventory())
				where c != null
				select c).ToArray();
			foreach (ItemData item in (from i in (from p in ObjectDB.instance.m_items
					select p.GetComponent<ItemDrop>() into c
					where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>())
					select c).Concat(ItemDrop.s_instances)
				select i.m_itemData).Concat(source.SelectMany((Inventory i) => i.GetAllItems())))
			{
				if (item.m_shared.m_name == name)
				{
					callback(item);
				}
			}
		}

		public void ApplyToAllInstances(Action<ItemData> callback)
		{
			ApplyToAllInstances(Prefab, callback);
		}

		private static string getInternalName<T>(T value) where T : struct
		{
			return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName;
		}

		private void registerRecipesInObjectDB(ObjectDB objectDB)
		{
			//IL_04b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0507: Expected O, but got Unknown
			activeRecipes[this] = new Dictionary<string, List<Recipe>>();
			itemCraftConfigs.TryGetValue(this, out Dictionary<string, ItemConfig> value);
			foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes)
			{
				List<Recipe> list = new List<Recipe>();
				foreach (CraftingStationConfig station in recipe.Value.Crafting.Stations)
				{
					ItemConfig itemConfig = value?[recipe.Key];
					Recipe val = ScriptableObject.CreateInstance<Recipe>();
					string name = ((Object)Prefab).name;
					CraftingTable table = station.Table;
					((Object)val).name = name + "_Recipe_" + table;
					val.m_amount = recipe.Value.CraftAmount;
					int enabled;
					if (itemConfig != null)
					{
						enable