Decompiled source of Glitnir Crossroads v7.3.2

ServerChangeMap.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ServerChangeMap")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("KG")]
[assembly: AssemblyProduct("ServerChangeMap")]
[assembly: AssemblyCopyright("Copyright © KG 2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("232A2218-DED5-4631-8FBE-413E81EF3226")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.0.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;
		}
	}
}
namespace ServerChangeMap.Plugin
{
	[BepInPlugin("kg.ServerChangeMap", "ServerChangeMap", "1.5.0")]
	public class ServerChangeMap : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ZNet), "RPC_ClientHandshake")]
		private static class ZNet_RPC_ClientHandshake_Patch
		{
			private static void Postfix(ZNet __instance)
			{
				if (_autoConnectInProgress)
				{
					__instance.OnPasswordEntered("12457800");
					_autoConnectInProgress = false;
					LogSwitchPhase("Senha enviada; aguardando sincronização do servidor");
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class ZNet_OnNewConnection_TravelSave_Patch
		{
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (!__instance.IsServer())
				{
					_serverSupportsTravelAck = false;
				}
				peer.m_rpc.Register<int>("Crossroads PrepareTravel", (Action<ZRpc, int>)delegate(ZRpc rpc, int nonce)
				{
					if (__instance.IsServer())
					{
						ServerChangeMap instance = Instance;
						if (instance != null)
						{
							((BaseUnityPlugin)instance).Logger.LogInfo((object)$"[Viagem servidor] Perfil persistido; confirmando token {nonce}.");
						}
						rpc.Invoke("Crossroads TravelReady", new object[1] { nonce });
					}
				});
				peer.m_rpc.Register<int>("Crossroads TravelReady", (Action<ZRpc, int>)delegate(ZRpc rpc, int nonce)
				{
					if (!__instance.IsServer() && _waitingForTravelSave && nonce == _travelSaveNonce)
					{
						_travelSaveAcknowledged = true;
					}
				});
				peer.m_rpc.Register<int>("Crossroads TravelCapability", (Action<ZRpc, int>)delegate(ZRpc rpc, int protocolVersion)
				{
					if (!__instance.IsServer() && protocolVersion >= 1)
					{
						_serverSupportsTravelAck = true;
						ServerChangeMap instance = Instance;
						if (instance != null)
						{
							((BaseUnityPlugin)instance).Logger.LogInfo((object)"Servidor compatível com confirmação segura de viagem.");
						}
					}
				});
				if (__instance.IsServer())
				{
					peer.m_rpc.Invoke("Crossroads TravelCapability", new object[1] { 1 });
				}
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "Start")]
		private static class FejdStartup_Start_Patch
		{
			private static void Postfix(FejdStartup __instance)
			{
				if (!_switching.HasValue)
				{
					return;
				}
				int value = _switching.Value;
				_switching = null;
				ZNet.SetServerHost("177.54.147.114", value, (OnlineBackendType)0);
				FejdStartup.ResetPendingInvite?.Invoke();
				LogSwitchPhase($"Menu inicial pronto; conectando à porta {value}");
				MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(FejdStartup), "LoadMainScene", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					LogSwitchPhase("Destino definido; removendo 1,5 s de espera do menu");
					methodInfo.Invoke(__instance, null);
					return;
				}
				ServerChangeMap instance = Instance;
				if (instance != null)
				{
					((BaseUnityPlugin)instance).Logger.LogWarning((object)"LoadMainScene não encontrado; usando transição nativa.");
				}
				__instance.TransitionToMainScene();
			}
		}

		[HarmonyPatch(typeof(Game), "Awake")]
		private static class Game_Awake_TravelTiming_Patch
		{
			private static void Postfix()
			{
				if (_switchInProgress)
				{
					LogSwitchPhase("Cena principal carregada; iniciando conexão e sincronização");
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static class ZNet_RPC_PeerInfo_TravelTiming_Patch
		{
			private static void Postfix(ZNet __instance)
			{
				if (_switchInProgress && !__instance.IsServer())
				{
					LogSwitchPhase("PeerInfo recebido; aguardando personagem e mundo");
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class Player_OnSpawned_TravelTiming_Patch
		{
			private static void Postfix(Player __instance)
			{
				if (_switchInProgress && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
				{
					LogSwitchPhase("Viagem concluída; personagem liberado");
					_switchInProgress = false;
					_autoConnectInProgress = false;
				}
			}
		}

		[HarmonyPatch(typeof(Game), "SavePlayerProfile")]
		private static class Game_SavePlayerProfile_TravelPatch
		{
			private static bool Prefix(Game __instance)
			{
				if (!_skipNextShutdownProfileSave || !__instance.m_shuttingDown)
				{
					return true;
				}
				_skipNextShutdownProfileSave = false;
				LogSwitchPhase("Gravação final já confirmada; encerrando sem duplicar o save");
				return false;
			}
		}

		private class Button_OnHover : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
		{
			private Image _image;

			private Sprite _orig;

			private Sprite _change;

			public void Init(Image image, Sprite orig, Sprite change)
			{
				_image = image;
				_orig = orig;
				_change = change;
			}

			public void OnPointerEnter(PointerEventData eventData)
			{
				_image.sprite = _change;
			}

			public void OnPointerExit(PointerEventData eventData)
			{
				_image.sprite = _orig;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static class Humanoid_UseItem_Patch
		{
			private static bool Prefix(ItemData item)
			{
				if ((Object)(object)item?.m_dropPrefab != (Object)null && (Object)(object)Map != (Object)null && ((Object)item.m_dropPrefab).name == ((Object)Map).name)
				{
					MapUI.Show();
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "DropItem")]
		private static class Humanoid_DropItem_Patch
		{
			private static bool Prefix(ItemData item, ref bool __result)
			{
				if (!IsCrossroadsMap(item))
				{
					return true;
				}
				ShowEpicMessage("O mapa escolheu você. Seu destino não pode ser lançado ao chão.");
				__result = false;
				return false;
			}
		}

		[HarmonyPatch]
		private static class Inventory_AddItem_Patch
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				yield return AccessTools.Method(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null);
				yield return AccessTools.Method(typeof(Inventory), "AddItem", new Type[2]
				{
					typeof(ItemData),
					typeof(Vector2i)
				}, (Type[])null);
				yield return AccessTools.Method(typeof(Inventory), "AddItem", new Type[4]
				{
					typeof(ItemData),
					typeof(int),
					typeof(int),
					typeof(int)
				}, (Type[])null);
			}

			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (!IsCrossroadsMap(item) || (Object)(object)Player.m_localPlayer == (Object)null || __instance == ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return true;
				}
				ShowEpicMessage("Nenhum cofre supera a guarda de seu portador. O lugar mais seguro para este mapa é sempre com você.");
				__result = false;
				return false;
			}
		}

		private static class MapUI
		{
			[HarmonyPatch(typeof(TextInput), "IsVisible")]
			private static class TextInput_IsVisible_Patch
			{
				private static void Postfix(ref bool __result)
				{
					__result |= IsVisible;
				}
			}

			[HarmonyPatch(typeof(StoreGui), "IsVisible")]
			private static class StoreGui_IsVisible_Patch
			{
				private static void Postfix(ref bool __result)
				{
					__result |= IsVisible;
				}
			}

			[CompilerGenerated]
			private static class <>O
			{
				public static PopupButtonCallback <0>__Pop;
			}

			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static PopupButtonCallback <>9__9_2;

				public static UnityAction <>9__9_0;

				public static PopupButtonCallback <>9__9_3;

				public static UnityAction <>9__9_1;

				internal void <Init>b__9_0()
				{
					//IL_0023: 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_002e: Expected O, but got Unknown
					//IL_004a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0054: Expected O, but got Unknown
					//IL_003e: 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_0049: Expected O, but got Unknown
					Hide();
					object obj = <>9__9_2;
					if (obj == null)
					{
						PopupButtonCallback val = delegate
						{
							UnifiedPopup.Pop();
							SwitchServer(24856);
						};
						<>9__9_2 = val;
						obj = (object)val;
					}
					object obj2 = <>O.<0>__Pop;
					if (obj2 == null)
					{
						PopupButtonCallback val2 = UnifiedPopup.Pop;
						<>O.<0>__Pop = val2;
						obj2 = (object)val2;
					}
					UnifiedPopup.Push((PopupBase)new YesNoPopup("Confirmação de Viagem", "Tem certeza que deseja viajar?", (PopupButtonCallback)obj, (PopupButtonCallback)obj2, true));
				}

				internal void <Init>b__9_2()
				{
					UnifiedPopup.Pop();
					SwitchServer(24856);
				}

				internal void <Init>b__9_1()
				{
					//IL_0023: 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_002e: Expected O, but got Unknown
					//IL_004a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0054: Expected O, but got Unknown
					//IL_003e: 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_0049: Expected O, but got Unknown
					Hide();
					object obj = <>9__9_3;
					if (obj == null)
					{
						PopupButtonCallback val = delegate
						{
							UnifiedPopup.Pop();
							SwitchServer(24956);
						};
						<>9__9_3 = val;
						obj = (object)val;
					}
					object obj2 = <>O.<0>__Pop;
					if (obj2 == null)
					{
						PopupButtonCallback val2 = UnifiedPopup.Pop;
						<>O.<0>__Pop = val2;
						obj2 = (object)val2;
					}
					UnifiedPopup.Push((PopupBase)new YesNoPopup("Confirmação de Viagem", "Tem certeza que deseja viajar?", (PopupButtonCallback)obj, (PopupButtonCallback)obj2, true));
				}

				internal void <Init>b__9_3()
				{
					UnifiedPopup.Pop();
					SwitchServer(24956);
				}
			}

			private static GameObject UI;

			private static Sprite Orig_Icon;

			private static Image Map_Image;

			private static Button ShadowWar;

			private static Button Expedition;

			public static bool IsVisible
			{
				get
				{
					if (Object.op_Implicit((Object)(object)UI))
					{
						return UI.activeSelf;
					}
					return false;
				}
			}

			public static void Init()
			{
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Expected O, but got Unknown
				//IL_0141: Unknown result type (might be due to invalid IL or missing references)
				//IL_0146: Unknown result type (might be due to invalid IL or missing references)
				//IL_014c: Expected O, but got Unknown
				UI = Object.Instantiate<GameObject>(Asset.LoadAsset<GameObject>("ServerChangeMapUI"));
				Object.DontDestroyOnLoad((Object)(object)UI);
				UI.SetActive(false);
				Map_Image = ((Component)UI.transform.Find("Canvas/UI/MapImage")).GetComponent<Image>();
				Orig_Icon = Map_Image.sprite;
				ShadowWar = ((Component)UI.transform.Find("Canvas/UI/ShadowWar")).GetComponent<Button>();
				Sprite change = Asset.LoadAsset<Sprite>("world1_shadowwar_epic");
				((Component)ShadowWar).gameObject.AddComponent<Button_OnHover>().Init(Map_Image, Orig_Icon, change);
				ButtonClickedEvent onClick = ShadowWar.onClick;
				object obj = <>c.<>9__9_0;
				if (obj == null)
				{
					UnityAction val = delegate
					{
						//IL_0023: 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_002e: Expected O, but got Unknown
						//IL_004a: Unknown result type (might be due to invalid IL or missing references)
						//IL_0054: Expected O, but got Unknown
						//IL_003e: 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_0049: Expected O, but got Unknown
						Hide();
						object obj3 = <>c.<>9__9_2;
						if (obj3 == null)
						{
							PopupButtonCallback val3 = delegate
							{
								UnifiedPopup.Pop();
								SwitchServer(24856);
							};
							<>c.<>9__9_2 = val3;
							obj3 = (object)val3;
						}
						object obj4 = <>O.<0>__Pop;
						if (obj4 == null)
						{
							PopupButtonCallback val4 = UnifiedPopup.Pop;
							<>O.<0>__Pop = val4;
							obj4 = (object)val4;
						}
						UnifiedPopup.Push((PopupBase)new YesNoPopup("Confirmação de Viagem", "Tem certeza que deseja viajar?", (PopupButtonCallback)obj3, (PopupButtonCallback)obj4, true));
					};
					<>c.<>9__9_0 = val;
					obj = (object)val;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				Expedition = ((Component)UI.transform.Find("Canvas/UI/Expedition")).GetComponent<Button>();
				Sprite change2 = Asset.LoadAsset<Sprite>("world2_expedition_epic");
				((Component)Expedition).gameObject.AddComponent<Button_OnHover>().Init(Map_Image, Orig_Icon, change2);
				ButtonClickedEvent onClick2 = Expedition.onClick;
				object obj2 = <>c.<>9__9_1;
				if (obj2 == null)
				{
					UnityAction val2 = delegate
					{
						//IL_0023: 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_002e: Expected O, but got Unknown
						//IL_004a: Unknown result type (might be due to invalid IL or missing references)
						//IL_0054: Expected O, but got Unknown
						//IL_003e: 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_0049: Expected O, but got Unknown
						Hide();
						object obj3 = <>c.<>9__9_3;
						if (obj3 == null)
						{
							PopupButtonCallback val3 = delegate
							{
								UnifiedPopup.Pop();
								SwitchServer(24956);
							};
							<>c.<>9__9_3 = val3;
							obj3 = (object)val3;
						}
						object obj4 = <>O.<0>__Pop;
						if (obj4 == null)
						{
							PopupButtonCallback val4 = UnifiedPopup.Pop;
							<>O.<0>__Pop = val4;
							obj4 = (object)val4;
						}
						UnifiedPopup.Push((PopupBase)new YesNoPopup("Confirmação de Viagem", "Tem certeza que deseja viajar?", (PopupButtonCallback)obj3, (PopupButtonCallback)obj4, true));
					};
					<>c.<>9__9_1 = val2;
					obj2 = (object)val2;
				}
				((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			}

			public static void Show()
			{
				Map_Image.sprite = Orig_Icon;
				int serverHostPort = ZNet.m_serverHostPort;
				((Selectable)ShadowWar).interactable = serverHostPort != 24856;
				((Selectable)Expedition).interactable = serverHostPort != 24956;
				UI.SetActive(true);
			}

			public static void Hide()
			{
				UI.SetActive(false);
			}
		}

		private const string ServerAddress = "177.54.147.114";

		private const string ServerPassword = "12457800";

		private const float EpicMessageDuration = 15f;

		private const float TravelSaveTimeout = 20f;

		private const string PrepareTravelRpc = "Crossroads PrepareTravel";

		private const string TravelReadyRpc = "Crossroads TravelReady";

		private const string TravelCapabilityRpc = "Crossroads TravelCapability";

		private const string DropBlockedMessage = "O mapa escolheu você. Seu destino não pode ser lançado ao chão.";

		private const string StorageBlockedMessage = "Nenhum cofre supera a guarda de seu portador. O lugar mais seguro para este mapa é sempre com você.";

		private static ServerChangeMap Instance;

		private Coroutine _epicMessageCoroutine;

		private const string GUID = "kg.ServerChangeMap";

		private const string NAME = "ServerChangeMap";

		private const string VERSION = "1.5.0";

		private static GameObject Map;

		private static AssetBundle Asset;

		private static int? _switching;

		private static bool _autoConnectInProgress;

		private static bool _switchInProgress;

		private static float _switchStartedAt;

		private static bool _waitingForTravelSave;

		private static bool _travelSaveAcknowledged;

		private static int _travelSaveNonce;

		private static bool _skipNextShutdownProfileSave;

		private static bool _serverSupportsTravelAck;

		private static void LogSwitchPhase(string phase)
		{
			float num = Time.realtimeSinceStartup - _switchStartedAt;
			long num2 = GC.GetTotalMemory(forceFullCollection: false) / 1048576;
			ServerChangeMap instance = Instance;
			if (instance != null)
			{
				((BaseUnityPlugin)instance).Logger.LogInfo((object)$"[Viagem +{num:0.00}s | memória gerenciada {num2} MB] {phase}");
			}
		}

		private static void ShowEpicMessage(string message)
		{
			if (!((Object)(object)Instance == (Object)null) && !((Object)(object)MessageHud.instance == (Object)null))
			{
				if (Instance._epicMessageCoroutine != null)
				{
					((MonoBehaviour)Instance).StopCoroutine(Instance._epicMessageCoroutine);
				}
				Instance._epicMessageCoroutine = ((MonoBehaviour)Instance).StartCoroutine(ShowEpicMessageCoroutine(message));
			}
		}

		private static IEnumerator ShowEpicMessageCoroutine(string message)
		{
			TMP_Text messageText = MessageHud.instance.m_messageCenterText;
			messageText.text = "<color=#55FF77>" + message + "</color>";
			((Graphic)messageText).CrossFadeAlpha(1f, 0f, true);
			yield return (object)new WaitForSecondsRealtime(15f);
			((Graphic)messageText).CrossFadeAlpha(0f, 1f, true);
			Instance._epicMessageCoroutine = null;
		}

		private static bool IsCrossroadsMap(ItemData item)
		{
			if ((Object)(object)item?.m_dropPrefab != (Object)null)
			{
				return ((Object)item.m_dropPrefab).name == "kg_ServerChangeMap";
			}
			return false;
		}

		private static AssetBundle GetAssetBundle(string filename)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(filename));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return AssetBundle.LoadFromMemory(memoryStream.ToArray());
		}

		private void Update()
		{
			if ((Input.GetKeyDown((KeyCode)27) || Input.GetKeyDown((KeyCode)9)) && MapUI.IsVisible)
			{
				MapUI.Hide();
			}
		}

		private void Awake()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Asset = GetAssetBundle("kg_serverchange");
			Item obj = new Item(Asset, "kg_ServerChangeMap")
			{
				Configurable = Configurability.Disabled
			};
			ConfigureRecoveredMapItem(obj);
			Map = obj.Prefab;
			MapUI.Init();
			new Harmony("kg.ServerChangeMap").PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Crossroads carregado: item e HUD inicializados.");
		}

		private static void ConfigureRecoveredMapItem(Item item)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			ItemDrop val = item.Prefab.GetComponent<ItemDrop>() ?? throw new InvalidOperationException("O prefab kg_ServerChangeMap não possui o componente ItemDrop.");
			ItemDrop val2 = val;
			if (val2.m_itemData == null)
			{
				val2.m_itemData = new ItemData();
			}
			ItemData itemData = val.m_itemData;
			if (itemData.m_shared == null)
			{
				itemData.m_shared = new SharedData();
			}
			SharedData shared = val.m_itemData.m_shared;
			shared.m_name = "Valheim Map";
			shared.m_description = "Right Click to open";
			shared.m_itemType = (ItemType)1;
			shared.m_maxStackSize = 1;
			shared.m_maxQuality = 1;
			shared.m_weight = 0.1f;
			shared.m_teleportable = true;
			shared.m_questItem = false;
			shared.m_attack = new Attack();
			shared.m_secondaryAttack = new Attack();
			Sprite sprite = ((Component)Asset.LoadAsset<GameObject>("ServerChangeMapUI").transform.Find("Canvas/UI/MapImage")).GetComponent<Image>().sprite;
			if ((Object)(object)sprite == (Object)null)
			{
				throw new InvalidOperationException("O MapImage do HUD não possui um sprite válido.");
			}
			shared.m_icons = (Sprite[])(object)new Sprite[1] { sprite };
			val.m_itemData.m_variant = 0;
			val.m_itemData.m_stack = 1;
			val.m_itemData.m_dropPrefab = item.Prefab;
			val.m_autoPickup = true;
			val.m_autoDestroy = true;
		}

		private static void SwitchServer(int port)
		{
			if (!_switchInProgress && !((Object)(object)Game.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)ZNet.instance == (Object)null))
			{
				_switchInProgress = true;
				_switchStartedAt = Time.realtimeSinceStartup;
				MessageHud.instance.ShowMessage((MessageType)2, "Glitnir é o sangue", 0, (Sprite)null, false);
				LogSwitchPhase($"Viagem solicitada para a porta {port}; salvando personagem");
				((MonoBehaviour)Instance).StartCoroutine(PrepareTravelAndLogout(port));
			}
		}

		private static IEnumerator PrepareTravelAndLogout(int port)
		{
			if (!_serverSupportsTravelAck)
			{
				ServerChangeMap instance = Instance;
				if (instance != null)
				{
					((BaseUnityPlugin)instance).Logger.LogWarning((object)"O servidor ainda não usa o protocolo Crossroads 1.5. O logout nativo será usado sem esperar confirmação.");
				}
				_switching = port;
				_autoConnectInProgress = true;
				Game.instance.Logout(true, true);
				yield break;
			}
			bool num = TrySaveServerCharacterSynchronously();
			ZNet instance2 = ZNet.instance;
			ZNetPeer serverPeer = ((instance2 != null) ? instance2.GetServerPeer() : null);
			if (num && serverPeer?.m_rpc != null && serverPeer.m_rpc.IsConnected())
			{
				_travelSaveNonce = Guid.NewGuid().GetHashCode();
				_travelSaveAcknowledged = false;
				_waitingForTravelSave = true;
				LogSwitchPhase("Perfil enviado; aguardando confirmação de gravação do servidor");
				serverPeer.m_rpc.Invoke("Crossroads PrepareTravel", new object[1] { _travelSaveNonce });
				float deadline = Time.realtimeSinceStartup + 20f;
				while (!_travelSaveAcknowledged && Time.realtimeSinceStartup < deadline && serverPeer.m_rpc.IsConnected())
				{
					yield return null;
				}
				_waitingForTravelSave = false;
				if (_travelSaveAcknowledged)
				{
					LogSwitchPhase("Servidor confirmou o personagem; iniciando troca de mundo");
					_skipNextShutdownProfileSave = true;
				}
				else
				{
					ServerChangeMap instance3 = Instance;
					if (instance3 != null)
					{
						((BaseUnityPlugin)instance3).Logger.LogWarning((object)"Confirmação de save não chegou. O logout nativo fará uma nova gravação segura.");
					}
				}
			}
			_switching = port;
			_autoConnectInProgress = true;
			Game.instance.Logout(true, true);
		}

		private static bool TrySaveServerCharacterSynchronously()
		{
			if ((Object)(object)Game.instance == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			Type type = AccessTools.TypeByName("ServerCharacters.ClientSide");
			FieldInfo obj = ((type == null) ? null : AccessTools.Field(type, "serverCharacter"));
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "currentlySaving"));
			FieldInfo fieldInfo2 = ((type == null) ? null : AccessTools.Field(type, "forceSynchronousSaving"));
			object obj2 = obj?.GetValue(null);
			bool flag = default(bool);
			int num;
			if (obj2 is bool)
			{
				flag = (bool)obj2;
				num = 1;
			}
			else
			{
				num = 0;
			}
			if (((uint)num & (flag ? 1u : 0u)) == 0)
			{
				Game.instance.SavePlayerProfile(true);
				return true;
			}
			obj2 = fieldInfo?.GetValue(null);
			bool flag2 = default(bool);
			int num2;
			if (obj2 is bool)
			{
				flag2 = (bool)obj2;
				num2 = 1;
			}
			else
			{
				num2 = 0;
			}
			if (((uint)num2 & (flag2 ? 1u : 0u)) != 0)
			{
				ServerChangeMap instance = Instance;
				if (instance != null)
				{
					((BaseUnityPlugin)instance).Logger.LogWarning((object)"ServerCharacters já está salvando. O logout nativo concluirá a gravação segura.");
				}
				return false;
			}
			if (fieldInfo2 == null)
			{
				ServerChangeMap instance2 = Instance;
				if (instance2 != null)
				{
					((BaseUnityPlugin)instance2).Logger.LogWarning((object)"Não foi possível ativar o save síncrono do ServerCharacters.");
				}
				return false;
			}
			try
			{
				fieldInfo2.SetValue(null, true);
				Game.instance.SavePlayerProfile(true);
				return true;
			}
			catch (Exception ex)
			{
				ServerChangeMap instance3 = Instance;
				if (instance3 != null)
				{
					((BaseUnityPlugin)instance3).Logger.LogWarning((object)("Falha no save de preparação da viagem: " + ex.Message));
				}
				return false;
			}
			finally
			{
				fieldInfo2.SetValue(null, false);
			}
		}
	}
}
namespace ItemManager
{
	[Flags]
	public enum Configurability
	{
		Disabled = 0,
		Recipe = 1,
		Stats = 2,
		Drop = 4,
		Trader = 8,
		Full = 0xF
	}
	[PublicAPI]
	public class Conversion
	{
		internal class ConversionConfig
		{
			public ConfigEntry<string> input;

			public string? activePiece;

			public ConfigEntry<ConversionPiece> piece;

			public ConfigEntry<string> customPiece;
		}

		public string Input;

		public ConversionPiece Piece;

		internal string? customPiece;

		internal ConversionConfig? config;

		public string? Custom
		{
			get
			{
				return customPiece;
			}
			set
			{
				customPiece = value;
				Piece = ConversionPiece.Custom;
			}
		}

		public Conversion(Item outputItem)
		{
			outputItem.Conversions.Add(this);
		}
	}
	[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 struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		public string? custom;
	}
	[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 enum CraftingTable
	{
		Disabled,
		Inventory,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		[InternalName("piece_preptable")]
		FoodPreparationTable,
		[InternalName("piece_MeadCauldron")]
		MeadKetill,
		Custom
	}
	public struct DropTarget
	{
		public string creature;

		public int min;

		public int max;

		public float chance;

		public bool levelMultiplier;
	}
	[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 class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[PublicAPI]
	public class Item
	{
		private class ItemConfig
		{
			public ConfigEntry<string>? craft;

			public ConfigEntry<string>? upgrade;

			public ConfigEntry<CraftingTable> table;

			public ConfigEntry<int> tableLevel;

			public ConfigEntry<string> customTable;

			public ConfigEntry<int>? maximumTableLevel;

			public ConfigEntry<Toggle> requireOneIngredient;

			public ConfigEntry<float> qualityResultAmountMultiplier;
		}

		private class TraderConfig
		{
			public ConfigEntry<Trader> trader;

			public ConfigEntry<uint> price;

			public ConfigEntry<uint> stack;

			public ConfigEntry<string> requiredGlobalKey;
		}

		private class RequirementQuality
		{
			public int quality;
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string? Category;

			[UsedImplicitly]
			public Action<ConfigEntryBase>? CustomDrawer;

			public Func<bool>? browsability;
		}

		[PublicAPI]
		public enum DamageModifier
		{
			Normal,
			Resistant,
			Weak,
			Immune,
			Ignore,
			VeryResistant,
			VeryWeak,
			None
		}

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

		private 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 obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)obj == (Object)null)
				{
					Debug.LogWarning((object)("The required item '" + name + "' does not exist."));
				}
				return obj;
			}

			public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade)
			{
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0179: Unknown result type (might be due to invalid IL or missing references)
				//IL_017e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0186: Unknown result type (might be due to invalid IL or missing references)
				//IL_018f: Expected O, but got Unknown
				//IL_011c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: 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_000b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0010: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0034: Unknown result type (might be due to invalid IL or missing references)
					//IL_003c: Expected O, but got Unknown
					ItemDrop val5 = ResItem(r);
					return (val5 != null) ? new Requirement
					{
						m_amount = (r.amountConfig?.Value ?? r.amount),
						m_resItem = val5,
						m_amountPerLevel = 0
					} : ((Requirement)null);
				});
				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
							};
							dictionary[itemName] = val4;
							value = val4;
							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 obj = ((prefab != null) ? prefab.GetComponent<Character>() : null);
				if ((Object)(object)obj == (Object)null)
				{
					Debug.LogWarning((object)("The drop target character '" + name + "' does not exist."));
				}
				return obj;
			}

			public Dictionary<Character, Drop> toCharacterDrops(ZNetScene netScene, GameObject item)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: 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 Dictionary<CharacterDrop, Drop> characterDrops = new Dictionary<CharacterDrop, Drop>();

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

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

		public static Configurability DefaultConfigurability = Configurability.Full;

		public Configurability? Configurable;

		private Configurability configurationVisible = Configurability.Full;

		private TraderConfig? traderConfig;

		public readonly GameObject Prefab;

		[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;

		[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();

		[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();

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

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

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

		private static object? configManager;

		private static Localization? _english;

		private static BaseUnityPlugin? _plugin;

		private static bool hasConfigSync = true;

		private static object? _configSync;

		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 var value))
				{
					return value;
				}
				return Recipes[name] = new ItemRecipe();
			}
		}

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

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: 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 var value))
			{
				Toggle((ConfigEntryBase)(object)value, Configurability.Drop);
			}
			if (itemCraftConfigs.TryGetValue(this, out var 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;
				for (int i = 0; i < tags.Length; i++)
				{
					if (tags[i] 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();
				for (int i = 0; i < fields.Length; i++)
				{
					object? value3 = fields[i].GetValue(obj);
					ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null);
					if (val != null)
					{
						Toggle(val, check);
					}
				}
			}
		}

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

		private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue)
		{
			if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out var value))
			{
				value.First().m_enabled = table != CraftingTable.Disabled;
				switch (table)
				{
				case CraftingTable.Disabled:
				case CraftingTable.Inventory:
					value.First().m_craftingStation = null;
					break;
				case CraftingTable.Custom:
				{
					Recipe obj = value.First();
					GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue);
					obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
					break;
				}
				default:
					value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent<CraftingStation>();
					break;
				}
			}
		}

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

		internal static void Patch_FejdStartup()
		{
			//IL_1008: Unknown result type (might be due to invalid IL or missing references)
			//IL_100d: Unknown result type (might be due to invalid IL or missing references)
			//IL_225f: Unknown result type (might be due to invalid IL or missing references)
			//IL_2269: Expected O, but got Unknown
			//IL_10cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_10d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_1128: Expected I4, but got Unknown
			//IL_0cc4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cce: Expected O, but got Unknown
			//IL_1259: Unknown result type (might be due to invalid IL or missing references)
			//IL_125c: Unknown result type (might be due to invalid IL or missing references)
			//IL_125e: Invalid comparison between Unknown and I4
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Expected O, but got Unknown
			//IL_1260: Unknown result type (might be due to invalid IL or missing references)
			//IL_1264: Invalid comparison between Unknown and I4
			//IL_0df8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e02: Expected O, but got Unknown
			//IL_0eb2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ebc: Expected O, but got Unknown
			//IL_1266: Unknown result type (might be due to invalid IL or missing references)
			//IL_126a: Invalid comparison between Unknown and I4
			//IL_0f75: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f7f: Expected O, but got Unknown
			//IL_145a: Unknown result type (might be due to invalid IL or missing references)
			//IL_145d: Unknown result type (might be due to invalid IL or missing references)
			//IL_145f: Invalid comparison between Unknown and I4
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Expected O, but got Unknown
			//IL_1461: Unknown result type (might be due to invalid IL or missing references)
			//IL_1465: Unknown result type (might be due to invalid IL or missing references)
			//IL_1467: Invalid comparison between Unknown and I4
			//IL_1469: Unknown result type (might be due to invalid IL or missing references)
			//IL_146d: Invalid comparison between Unknown and I4
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fb: Expected O, but got Unknown
			//IL_153a: Unknown result type (might be due to invalid IL or missing references)
			//IL_153f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1541: Unknown result type (might be due to invalid IL or missing references)
			//IL_1544: Invalid comparison between Unknown and I4
			//IL_1546: Unknown result type (might be due to invalid IL or missing references)
			//IL_154a: Invalid comparison between Unknown and I4
			//IL_0713: Unknown result type (might be due to invalid IL or missing references)
			//IL_071d: Expected O, but got Unknown
			//IL_15b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_15b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_15b7: Invalid comparison between Unknown and I4
			//IL_15b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_15bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_15bf: Invalid comparison between Unknown and I4
			//IL_080a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0814: Expected O, but got Unknown
			//IL_15c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_15c5: Invalid comparison between Unknown and I4
			//IL_16fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_16fe: Invalid comparison between Unknown and I4
			//IL_092c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0936: Expected O, but got Unknown
			//IL_18f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_18fd: Invalid comparison between Unknown and I4
			//IL_19c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_19c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_19cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_19cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_19d1: Invalid comparison between Unknown and I4
			//IL_1a33: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a36: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a38: Invalid comparison between Unknown and I4
			//IL_1a3a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a3e: Invalid comparison between Unknown and I4
			//IL_1a40: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a44: Invalid comparison between Unknown and I4
			//IL_1672: Unknown result type (might be due to invalid IL or missing references)
			//IL_1677: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e9d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ea0: 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;
				foreach (Item item3 in registeredItems.Where((Item i) => i.configurability != Configurability.Disabled))
				{
					Item item = item3;
					string name = item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
					string englishName = new Regex("['\\[\"\\]]").Replace(english.Localize(name), "").Trim();
					string localizedName = Localization.instance.Localize(name).Trim();
					int order = 0;
					if ((item.configurability & Configurability.Recipe) != Configurability.Disabled)
					{
						itemCraftConfigs[item] = new Dictionary<string, ItemConfig>();
						foreach (string item4 in item.Recipes.Keys.DefaultIfEmpty(""))
						{
							string configKey = item4;
							string text = ((configKey == "") ? "" : (" (" + configKey + ")"));
							if (configKey == "")
							{
								Configurability? configurable = item.Configurable;
								if (configurable.HasValue && item.Crafting.Stations.Count == 0)
								{
									item.Crafting.Add(CraftingTable.Disabled, 1);
								}
							}
							if (!item.Recipes.ContainsKey(configKey) || item.Recipes[configKey].Crafting.Stations.Count <= 0)
							{
								continue;
							}
							ItemConfig itemConfig = (itemCraftConfigs[item][configKey] = new ItemConfig());
							ItemConfig itemConfig3 = itemConfig;
							ItemConfig cfg = itemConfig3;
							List<ConfigurationManagerAttributes> hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
							cfg.table = config(englishName, "Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Browsable = ((item.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = CustomTableBrowsability,
								Browsable = (CustomTableBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							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 configurationManagerAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = TableLevelBrowsability,
								Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							hideWhenNoneAttributes.Add(configurationManagerAttributes);
							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] { configurationManagerAttributes }));
							cfg.tableLevel.SettingChanged += delegate
							{
								if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out var value))
								{
									value.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] { configurationManagerAttributes }));
							}
							cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									browsability = TableLevelBrowsability,
									Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = QualityResultBrowsability,
								Browsable = (QualityResultBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							cfg.requireOneIngredient.SettingChanged += delegate
							{
								if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out var value))
								{
									foreach (Recipe item5 in value)
									{
										item5.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 var value))
								{
									foreach (Recipe item6 in value)
									{
										item6.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 = itemConfig4("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 = itemConfig4("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 item7 in hideWhenNoneAttributes)
								{
									item7.Browsable = cfg.table.Value != CraftingTable.Disabled;
								}
								reloadConfigDisplay();
							}
							bool TableLevelBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							ConfigEntry<string> itemConfig4(string name2, string value, string desc, bool isUpgrade)
							{
								//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
								//IL_00c1: Expected O, but got Unknown
								ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes
								{
									CustomDrawer = drawRequirementsConfigTable(item, isUpgrade),
									Order = (order -= 1),
									browsability = ItemBrowsability,
									Browsable = (ItemBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								};
								hideWhenNoneAttributes.Add(configurationManagerAttributes2);
								return config(englishName, name2, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }));
							}
						}
						if ((item.configurability & Configurability.Drop) != Configurability.Disabled)
						{
							ConfigEntry<string> val = (itemDropConfigs[item] = config(englishName, "Drops 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)
								}
							})));
							val.SettingChanged += delegate
							{
								item.UpdateCharacterDrop();
							};
						}
						for (int num = 0; num < item.Conversions.Count; num++)
						{
							string text2 = ((item.Conversions.Count > 1) ? $"{num + 1}. " : "");
							Conversion conversion = item.Conversions[num];
							conversion.config = new Conversion.ConversionConfig();
							int index = num;
							conversion.config.input = config(englishName, text2 + "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 val3 = SerializedRequirements.fetchByName(instance, conversion.config.input.Value);
										item.conversions[index].m_from = val3;
										UpdatePiece();
									}
								}
							};
							conversion.config.piece = config(englishName, text2 + "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, text2 + "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 text3 = ((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)
									{
										int num4 = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent<Smelter>().m_conversion.IndexOf(item.conversions[index]);
										if (num4 >= 0)
										{
											Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val3 in array3)
											{
												if (Utils.GetPrefabName(((Component)val3).gameObject) == activePiece)
												{
													val3.m_conversion.RemoveAt(num4);
												}
											}
										}
										conversion.config.activePiece = null;
									}
									if (item.conversions[index].m_from != null && conversion.config.piece.Value != ConversionPiece.Disabled)
									{
										GameObject prefab = ZNetScene.instance.GetPrefab(text3);
										if (((prefab != null) ? prefab.GetComponent<Smelter>() : null) != null)
										{
											conversion.config.activePiece = text3;
											Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val4 in array3)
											{
												if (Utils.GetPrefabName(((Component)val4).gameObject) == text3)
												{
													val4.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 sharedData) => sharedData.m_weight, delegate(SharedData sharedData, float value)
						{
							sharedData.m_weight = value;
						});
						statcfg<int>("Trader Value", "Trader value of " + englishName + ".", (SharedData sharedData) => sharedData.m_value, delegate(SharedData sharedData, int value)
						{
							sharedData.m_value = value;
						});
						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 sharedData) => sharedData.m_maxDurability, delegate(SharedData sharedData, float value)
							{
								sharedData.m_maxDurability = value;
							});
							statcfg<float>("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData sharedData) => sharedData.m_durabilityPerLevel, delegate(SharedData sharedData, float value)
							{
								sharedData.m_durabilityPerLevel = value;
							});
							statcfg<float>("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData sharedData) => sharedData.m_movementModifier, delegate(SharedData sharedData, float value)
							{
								sharedData.m_movementModifier = value;
							});
						}
						if (itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22)
						{
							statcfg<float>("Block Armor", "Block armor of " + englishName + ".", (SharedData sharedData) => sharedData.m_blockPower, delegate(SharedData sharedData, float value)
							{
								sharedData.m_blockPower = value;
							});
							statcfg<float>("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData sharedData) => sharedData.m_blockPowerPerLevel, delegate(SharedData sharedData, float value)
							{
								sharedData.m_blockPowerPerLevel = value;
							});
							statcfg<float>("Block Force", "Block force of " + englishName + ".", (SharedData sharedData) => sharedData.m_deflectionForce, delegate(SharedData sharedData, float value)
							{
								sharedData.m_deflectionForce = value;
							});
							statcfg<float>("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData sharedData) => sharedData.m_deflectionForcePerLevel, delegate(SharedData sharedData, float value)
							{
								sharedData.m_deflectionForcePerLevel = value;
							});
							statcfg<float>("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData sharedData) => sharedData.m_timedBlockBonus, delegate(SharedData sharedData, float value)
							{
								sharedData.m_timedBlockBonus = value;
							});
						}
						else if (itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17)
						{
							statcfg<float>("Armor", "Armor of " + englishName + ".", (SharedData sharedData) => sharedData.m_armor, delegate(SharedData sharedData, float value)
							{
								sharedData.m_armor = value;
							});
							statcfg<float>("Armor per Level", "Armor per level for " + englishName + ".", (SharedData sharedData) => sharedData.m_armorPerLevel, delegate(SharedData sharedData, float value)
							{
								sharedData.m_armorPerLevel = value;
							});
						}
						SkillType skillType = shared.m_skillType;
						if ((int)skillType == 7 || (int)skillType == 12)
						{
							statcfg<int>("Tool tier", "Tool tier of " + englishName + ".", (SharedData sharedData) => sharedData.m_toolTier, delegate(SharedData sharedData, int value)
							{
								sharedData.m_toolTier = value;
							});
						}
						if (itemType - 5 <= 2 || itemType - 11 <= 1 || (int)itemType == 17)
						{
							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[] array = new DamageType[5];
							RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
							foreach (DamageType damageType in first.Except((IEnumerable<DamageType>)(object)array))
							{
								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 value) ? value : DamageModifier.None, delegate(SharedData sharedData, DamageModifier value)
								{
									//IL_0002: Unknown result type (might be due to invalid IL or missing references)
									//IL_000b: Unknown result type (might be due to invalid IL or missing references)
									//IL_0010: Unknown result type (might be due to invalid IL or missing references)
									//IL_0018: Unknown result type (might be due to invalid IL or missing references)
									//IL_001d: Unknown result type (might be due to invalid IL or missing references)
									//IL_001e: Unknown result type (might be due to invalid IL or missing references)
									//IL_002a: Unknown result type (might be due to invalid IL or missing references)
									//IL_002f: Unknown result type (might be due to invalid IL or missing references)
									//IL_0035: Unknown result type (might be due to invalid IL or missing references)
									//IL_0077: Unknown result type (might be due to invalid IL or missing references)
									//IL_0054: Unknown result type (might be due to invalid IL or missing references)
									DamageModPair val3 = new DamageModPair
									{
										m_type = damageType,
										m_modifier = (DamageModifier)value
									};
									for (int i = 0; i < sharedData.m_damageModifiers.Count; i++)
									{
										if (sharedData.m_damageModifiers[i].m_type == damageType)
										{
											if (value == DamageModifier.None)
											{
												sharedData.m_damageModifiers.RemoveAt(i);
											}
											else
											{
												sharedData.m_damageModifiers[i] = val3;
											}
											return;
										}
									}
									if (value != DamageModifier.None)
									{
										sharedData.m_damageModifiers.Add(val3);
									}
								});
							}
						}
						if ((int)itemType == 2 && shared.m_food > 0f)
						{
							statcfg<float>("Health", "Health value of " + englishName + ".", (SharedData sharedData) => sharedData.m_food, delegate(SharedData sharedData, float value)
							{
								sharedData.m_food = value;
							});
							statcfg<float>("Stamina", "Stamina value of " + englishName + ".", (SharedData sharedData) => sharedData.m_foodStamina, delegate(SharedData sharedData, float value)
							{
								sharedData.m_foodStamina = value;
							});
							statcfg<float>("Eitr", "Eitr value of " + englishName + ".", (SharedData sharedData) => sharedData.m_foodEitr, delegate(SharedData sharedData, float value)
							{
								sharedData.m_foodEitr = value;
							});
							statcfg<float>("Duration", "Duration of " + englishName + ".", (SharedData sharedData) => sharedData.m_foodBurnTime, delegate(SharedData sharedData, float value)
							{
								sharedData.m_foodBurnTime = value;
							});
							statcfg<float>("Health Regen", "Health regen value of " + englishName + ".", (SharedData sharedData) => sharedData.m_foodRegen, delegate(SharedData sharedData, float value)
							{
								sharedData.m_foodRegen = value;
							});
						}
						if ((int)shared.m_skillType == 10)
						{
							statcfg<float>("Health Cost", "Health cost of " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_attackHealth, delegate(SharedData sharedData, float value)
							{
								sharedData.m_attack.m_attackHealth = value;
							});
							statcfg<float>("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_attackHealthPercentage, delegate(SharedData sharedData, float value)
							{
								sharedData.m_attack.m_attackHealthPercentage = value;
							});
						}
						skillType = shared.m_skillType;
						if (skillType - 9 <= 1)
						{
							statcfg<float>("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_attackEitr, delegate(SharedData sharedData, float value)
							{
								sharedData.m_attack.m_attackEitr = value;
							});
						}
						if (itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22)
						{
							statcfg<float>("Knockback", "Knockback of " + englishName + ".", (SharedData sharedData) => sharedData.m_attackForce, delegate(SharedData sharedData, float value)
							{
								sharedData.m_attackForce = value;
							});
							statcfg<float>("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData sharedData) => sharedData.m_backstabBonus, delegate(SharedData sharedData, float value)
							{
								sharedData.m_backstabBonus = value;
							});
							statcfg<float>("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_attackStamina, delegate(SharedData sharedData, float value)
							{
								sharedData.m_attack.m_attackStamina = value;
							});
							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 sharedData) => sharedData.m_attack.m_projectileBursts, delegate(SharedData sharedData, int value)
								{
									sharedData.m_attack.m_projectileBursts = value;
								});
								statcfg<float>("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData sharedData) => sharedData.m_attack.m_burstInterval, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_burstInterval = value;
								});
								statcfg<float>("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_projectileAccuracyMin, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_projectileAccuracyMin = value;
								});
								statcfg<float>("Accuracy", "Accuracy for " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_projectileAccuracy, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_projectileAccuracy = value;
								});
								statcfg<float>("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_projectileVelMin, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_projectileVelMin = value;
								});
								statcfg<float>("Velocity", "Velocity for " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_projectileVel, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_projectileVel = value;
								});
								statcfg<float>("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData sharedData) => sharedData.m_attack.m_drawDurationMin, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_drawDurationMin = value;
								});
								statcfg<float>("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData sharedData) => sharedData.m_attack.m_drawStaminaDrain, delegate(SharedData sharedData, float value)
								{
									sharedData.m_attack.m_drawStaminaDrain = value;
								});
							}
						}
					}
					List<ConfigurationManagerAttributes> traderAttributes;
					if ((item.configurability & Configurability.Trader) != Configurability.Disabled)
					{
						traderAttributes = new List<ConfigurationManagerAttributes>();
						item.traderConfig = new TraderConfig
						{
							trader = config(englishName, "Trader Selling", item.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Browsable = ((item.configurationVisible & Configurability.Trader) != 0),
									Category = localizedName
								}
							}))
						};
						item.traderConfig.trader.SettingChanged += delegate
						{
							item.ReloadTraderConfiguration();
							foreach (ConfigurationManagerAttributes item8 in traderAttributes)
							{
								item8.Browsable = TraderBrowsability();
							}
							reloadConfigDisplay();
						};
						item.traderConfig.price = traderConfig<uint>("Trader Price", item.Trade.Price, "Price of " + englishName + " at the trader.");
						item.traderConfig.stack = traderConfig<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 = traderConfig<string>("Trader Required Global Key", item.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader.");
						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 sharedData) => readDmg(sharedData.m_damages), delegate(SharedData sharedData, float value)
						{
							setDmg(ref sharedData.m_damages, value);
						});
						statcfg<float>(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData sharedData) => readDmg(sharedData.m_damagesPerLevel), delegate(SharedData sharedData, float value)
						{
							setDmg(ref sharedData.m_damagesPerLevel, value);
						});
					}
					bool TraderBrowsability()
					{
						return item.traderConfig.trader.Value != Trader.None;
					}
					void statcfg<T>(string configName, string description, Func<SharedData, T> readDefault, Action<SharedData, T> setValue)
					{
						//IL_0076: Unknown result type (might be due to invalid IL or missing references)
						//IL_0080: 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 itemData)
							{
								setValue(itemData.m_shared, cfg2.Value);
							});
						}
					}
					ConfigEntry<T> traderConfig<T>(string name2, T value, string desc)
					{
						//IL_0086: Unknown result type (might be due to invalid IL or missing references)
						//IL_0090: Expected O, but got Unknown
						ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes
						{
							Order = (order -= 1),
							browsability = TraderBrowsability,
							Browsable = (TraderBrowsability() && (item.configurationVisible & Configurability.Trader) != 0),
							Category = localizedName
						};
						traderAttributes.Add(configurationManagerAttributes2);
						ConfigEntry<T> obj = config(englishName, name2, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }));
						obj.SettingChanged += delegate
						{
							item.ReloadTraderConfiguration();
						};
						return obj;
					}
				}
				if (saveOnConfigSet)
				{
					plugin.Config.SaveOnConfigSet = true;
					plugin.Config.Save();
				}
			}
			configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type));
			foreach (Item registeredItem in registeredItems)
			{
				Item item2 = registeredItem;
				foreach (KeyValuePair<string, ItemRecipe> recipe in item2.Recipes)
				{
					KeyValuePair<string, ItemRecipe> kv = recipe;
					RequiredResourceList[] array2 = new RequiredResourceList[2]
					{
						kv.Value.RequiredItems,
						kv.Value.RequiredUpgradeItems
					};
					foreach (RequiredResourceList requiredResourceList in array2)
					{
						for (int num3 = 0; num3 < requiredResourceList.Requirements.Count; num3++)
						{
							ConfigEntry<int> amountCfg;
							int resourceIndex;
							if ((item2.configurability & Configurability.Recipe) != Configurability.Disabled)
							{
								amountCfg = requiredResourceList.Requirements[num3].amountConfig;
								if (amountCfg != null)
								{
									resourceIndex = num3;
									amountCfg.SettingChanged += ConfigChanged2;
								}
							}
							void ConfigChanged2(object o, EventArgs e)
							{
								if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out var value))
								{
									foreach (Recipe item9 in value)
									{
										item9.m_resources[resourceIndex].m_amount = amountCfg.Value;
									}
								}
							}
						}
					}
				}
				item2.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 var value))
					{
						foreach (Recipe item in value)
						{
							item.m_enabled = (int)enabledCfg.BoxedValue != 0;
						}
					}
				}
			}
		}

		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);
				ZNetScene.instance.m_prefabs.Add(Prefab);
				ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab);
			}
			foreach (string item in Recipes.Keys.DefaultIfEmpty(""))
			{
				if (Recipes.TryGetValue(item, out var 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));
				}
			}
		}

		private 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.FindObjectsOfType<Container>()
					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_0452: Unknown result type (might be due to invalid IL or missing references)
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a0: Expected O, but got Unknown
			activeRecipes[this] = new Dictionary<string, List<Recipe>>();
			itemCraftConfigs.TryGetValue(this, out var 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;
					ConfigEntryBase? recipeIsActive = recipe.Value.RecipeIsActive;
					val.m_enabled = (int)(((recipeIsActive != null) ? recipeIsActive.BoxedValue : null) ?? ((object)1)) != 0 && (itemConfig == null || itemConfig.table.Value != CraftingTable.Disabled);
					val.m_item = Prefab.GetComponent<ItemDrop>();
					val.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value));
					table = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value);
					if ((uint)table <= 1u)
					{
						val.m_craftingStation = null;
					}
					else if (((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value) == CraftingTable.Custom)
					{
						GameObject prefab = ZNetScene.instance.GetPrefab((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value);
						if (prefab != null)
						{
							val.m_craftingStation = prefab.GetComponent<CraftingStation>();
						}
						else
						{
							Debug.LogWarning((object)("Custom crafting station '" + ((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value) + "' does not exist"));
						}
					}
					else
					{
						val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent<CraftingStation>();
					}
					val.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value);
					val.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On));
					val.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe.Value.QualityResultAmountMultiplier;
					list.Add(val);
					RequiredResourceList requiredItems;
					if (station.Table != CraftingTable.Disabled)
					{
						requiredItems = recipe.Value.RequiredItems;
						if (requiredItems != null && !requiredItems.Free)
						{
							List<Requirement> requirements = requiredItems.Requirements;
							if (requirements != null && requirements.Count == 0)
							{
								hiddenCraftRecipes.Add(val, recipe.Value.RecipeIsActive);
							}
						}
					}
					requiredItems = recipe.Value.RequiredUpgradeItems;
					if (requiredItems != null && !requiredItems.Free)
					{
						List<Requirement> requirements2 = requiredItems.Requirements;
						if (requirements2 != null && requirements2.Count == 0)
						{
							hiddenUpgradeRecipes.Add(val, recipe.Value.RecipeIsActive);
						}
					}
				}
				activeRecipes[this].Add(recipe.Key, list);
				objectDB.m_recipes.AddRange(list);
			}
			conversions = new List<ItemConversion>();
			for (int i = 0; i < Conversions.Count; i++)
			{
				Conversion conversion = Conversions[i];
				conversions.Add(new ItemConversion
				{
					m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input),
					m_to = Prefab.GetComponent<ItemDrop>()
				});
				ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece;
				string text = null;
				if (conversionPiece != ConversionPiece.Disabled && conversions[i].m_from != null)
				{
					text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece));
					GameObject prefab2 = ZNetScene.instance.GetPrefab(text);
					Smelter val2 = ((prefab2 != null) ? prefab2.GetComponent<Smelter>() : null);
					if (val2 != null)
					{
						val2.m_conversion.Add(conversions[i]);
					}
					else
					{
						text = null;
					}
				}
				if (conversion.config != null)
				{
					conversion.config.activePiece = text;
				}
			}
		}

		[HarmonyPriority(0)]
		internal static void Patch_ObjectDBInit(ObjectDB __instance)
		{
			if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null)
			{
				return;
			}
			hiddenCraftRecipes.Clear();
			hiddenUpgradeRecipes.Clear();
			foreach (Item registeredItem in registeredItems)
			{
				registeredItem.registerRecipesInObjectDB(__instance);
			}
		}

		internal static void Patch_TraderGetAvailableItems(Trader __instance, ref List<TradeItem> __result)
		{
			string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
			Trader trader = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None));
			Trader trader2 = trader;
			__result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values
				where (tuple.Item1 & trader2) != 0
				select tuple.Item2 into tradeItem
				where string.IsNullOrEmpty(tradeItem.m_requiredGlobalKey) || ZoneSystem.instance.GetGlobalKey(tradeItem.m_requiredGlobalKey)
				select tradeItem);
		}

		internal static void Patch_OnAddSmelterInput(ItemData item, bool __result)
		{
			if (__result)
			{
				((Humanoid)Player.m_localPlayer).UnequipItem(item, true);
			}
		}

		internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality)
		{
			if (!itemDropMap.TryGetValue(__instance.m_item, out var value))
			{
				return;
			}
			IEnumerable<ItemConfig> source;
			if (!itemCraftConfigs.TryGetValue(value, out var value2))
			{
				source = Enumerable.Empty<ItemConfig>();
			}
			else
			{
				CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation();
				if (currentCraftingStation != null)
				{
					string stationName = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject);
					source = value2.Where(delegate(KeyValuePair<string, ItemConfig> c)
					{
						switch (c.Value.table.Value)
						{
						case CraftingTable.Disabled:
						case CraftingTable.Inventory:
							return false;
						case CraftingTable.Custom:
							return c.Value.customTable.Value == stationName;
						default:
							return getInternalName(c.Value.table.Value) == stationName;
						}
					}).Select(delegate(KeyValuePair<string, ItemConfig> c)
					{
						KeyValuePair<string, ItemConfig> keyValuePair = c;
						return keyValuePair.Value;
					});
				}
				else
				{
					source = value2.Values;
				}
			}
			__result = Mathf.Min(Mathf.Max(1, __instance.m_minStationLevel) + (quality - 1), (from cfg in source
				where cfg.maximumTableLevel != null
				select cfg.maximumTableLevel.Value).DefaultIfEmpty(value.MaximumRequiredStationLevel).Max());
		}

		internal static void Patch_GetAvailableRecipesPrefix(ref Dictionary<Assembly, List<Recipe>>? __state)
		{
			if (__state == null)
			{
				__state = new Dictionary<Assembly, List<Recipe>>();
			}
			Dictionary<Recipe, ConfigEntryBase> source;
			if (InventoryGui.instance.InCraftTab())
			{
				source = hiddenCraftRecipes;
			}
			else
			{
				if (!InventoryGui.instance.InUpradeTab())
				{
					return;
				}
				source = hiddenUpgradeRecipes;
			}
			List<Recipe> list = (from r in source.Select(delegate(KeyValuePair<Recipe, ConfigEntryBase> kv)
				{
					KeyValuePair<Recipe, ConfigEntryBase> keyValuePair = kv;
					return keyValuePair.Key;
				})
				where r.m_enabled
				select r).ToList();
			__state[Assembly.GetExecutingAssembly()] = list;
			foreach (Recipe item in list)
			{
				item.m_enabled = false;
			}
		}

		internal static void Patch_GetAvailableRecipesFinalizer(Dictionary<Assembly, List<Recipe>> __state)
		{
			if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out var value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_enabled = true;
			}
		}

		internal static IEnumerable<CodeInstruction> Transpile_SetupRequirementList(IEnum