Decompiled source of Forge of Potential Repairable Failure v0.3.0

ForgeOfPotentialRepair.dll

Decompiled 6 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ForgeOfPotentialRepair")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Repairable gear failures, bad-luck protection, and idol exchanges for Valheim's Forge of Potential.")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0+0b29bb373a0eb9858eb9afd752019dd9f8837d55")]
[assembly: AssemblyProduct("Forge of Potential – Repairable Failure")]
[assembly: AssemblyTitle("ForgeOfPotentialRepair")]
[assembly: AssemblyVersion("0.3.0.0")]
[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 ForgeOfPotentialRepair
{
	internal sealed class ExchangePlan
	{
		internal enum Problem
		{
			None,
			MissingIdol,
			MissingCatalyst,
			NoSpace
		}

		private readonly List<(ItemData Item, int Amount)> debits = new List<(ItemData, int)>();

		private readonly ItemData product;

		private ItemData? destination;

		internal bool Cheated => product.m_cheated;

		private ExchangePlan(ItemData product)
		{
			this.product = product;
		}

		internal static ExchangePlan? Create(Inventory inventory, ItemData idol, int idolCost, ItemData catalyst, int catalystCost, ItemData product, out Problem problem)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			List<ItemData> allItems = inventory.GetAllItems();
			ExchangePlan exchangePlan = new ExchangePlan(product);
			if (!exchangePlan.Debit(allItems, idol, idolCost))
			{
				problem = Problem.MissingIdol;
				return null;
			}
			if (!exchangePlan.Debit(allItems, catalyst, catalystCost))
			{
				problem = Problem.MissingCatalyst;
				return null;
			}
			exchangePlan.destination = allItems.Find((ItemData item) => Matches(item, product) && item.IsSameType(product) && item.m_cheated == product.m_cheated && item.m_stack > 0 && item.m_stack < item.m_shared.m_maxStackSize);
			if (exchangePlan.destination == null)
			{
				(ItemData, int) tuple = exchangePlan.debits.Find(((ItemData Item, int Amount) debit) => debit.Item.m_stack == debit.Amount);
				if (tuple.Item1 != null)
				{
					product.m_gridPos = tuple.Item1.m_gridPos;
				}
				else if (!FindFreeSlot(inventory, out product.m_gridPos))
				{
					problem = Problem.NoSpace;
					return null;
				}
			}
			problem = Problem.None;
			return exchangePlan;
		}

		private bool Debit(List<ItemData> items, ItemData resource, int remaining)
		{
			foreach (ItemData item in items)
			{
				if (Matches(item, resource) && item.m_worldLevel >= product.m_worldLevel && item.m_stack > 0)
				{
					int num = Math.Min(item.m_stack, remaining);
					debits.Add((item, num));
					ItemData obj = product;
					obj.m_cheated |= item.m_cheated;
					remaining -= num;
					if (remaining == 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool Matches(ItemData item, ItemData template)
		{
			if (item.m_shared != template.m_shared)
			{
				if (template.m_dropPrefab != null)
				{
					return item.m_dropPrefab == template.m_dropPrefab;
				}
				return false;
			}
			return true;
		}

		private static bool FindFreeSlot(Inventory inventory, out Vector2i slot)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < inventory.GetHeight(); i++)
			{
				for (int j = 0; j < inventory.GetWidth(); j++)
				{
					if (inventory.GetItemAt(j, i) == null)
					{
						slot = new Vector2i(j, i);
						return true;
					}
				}
			}
			slot = default(Vector2i);
			return false;
		}

		internal void Commit(Inventory inventory)
		{
			List<ItemData> allItems = inventory.GetAllItems();
			foreach (var debit in debits)
			{
				ItemData item = debit.Item;
				item.m_stack -= debit.Amount;
				if (debit.Item.m_stack == 0)
				{
					allItems.Remove(debit.Item);
				}
			}
			if (destination == null)
			{
				allItems.Add(product);
				return;
			}
			ItemData? obj = destination;
			obj.m_stack++;
		}
	}
	internal sealed class ExchangeTabBar
	{
		private readonly Button nativeCraft;

		private readonly Button nativeUpgrade;

		private readonly RectTransform parent;

		private readonly RectTransform bar;

		private readonly Button upgrade;

		private readonly Button promote;

		private readonly Button convert;

		private readonly CanvasGroup craftVisibility;

		private readonly CanvasGroup upgradeVisibility;

		private readonly Vector3[] corners = (Vector3[])(object)new Vector3[4];

		internal ExchangeTabBar(Button craft, Button refine, RectTransform parent, Action<bool?> select)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			nativeCraft = craft;
			nativeUpgrade = refine;
			this.parent = parent;
			GameObject val = new GameObject("Forge Exchange Tabs", new Type[2]
			{
				typeof(RectTransform),
				typeof(LayoutElement)
			});
			val.SetActive(false);
			bar = (RectTransform)val.transform;
			((Transform)bar).SetParent((Transform)(object)parent, false);
			val.GetComponent<LayoutElement>().ignoreLayout = true;
			upgrade = CreateButton(refine, "Forge Upgrade Tab", delegate
			{
				select(null);
			});
			promote = CreateButton(craft, "Forge Promote Tab", delegate
			{
				select(true);
			});
			convert = CreateButton(craft, "Forge Convert Tab", delegate
			{
				select(false);
			});
			craftVisibility = ((Component)craft).gameObject.AddComponent<CanvasGroup>();
			upgradeVisibility = ((Component)refine).gameObject.AddComponent<CanvasGroup>();
		}

		private Button CreateButton(Button source, string objectName, Action click)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			Button obj = Object.Instantiate<Button>(source, (Transform)(object)bar, false);
			((Object)((Component)obj).gameObject).name = objectName;
			obj.onClick = new ButtonClickedEvent();
			((UnityEvent)obj.onClick).AddListener((UnityAction)delegate
			{
				click();
			});
			return obj;
		}

		internal bool Matches(Button craft, Button refine)
		{
			if ((Object)(object)nativeCraft == (Object)(object)craft && (Object)(object)nativeUpgrade == (Object)(object)refine)
			{
				return Object.op_Implicit((Object)(object)bar);
			}
			return false;
		}

		internal void Show(bool showPromotion, bool showConversion, bool? selected)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			Vector2 min = default(Vector2);
			((Vector2)(ref min))..ctor(float.PositiveInfinity, float.PositiveInfinity);
			Vector2 max = default(Vector2);
			((Vector2)(ref max))..ctor(float.NegativeInfinity, float.NegativeInfinity);
			IncludeRect((RectTransform)((Component)nativeCraft).transform, ref min, ref max);
			IncludeRect((RectTransform)((Component)nativeUpgrade).transform, ref min, ref max);
			bar.anchorMin = Vector2.zero;
			bar.anchorMax = Vector2.zero;
			bar.pivot = Vector2.zero;
			RectTransform obj = bar;
			Vector2 val = min;
			Rect rect = parent.rect;
			obj.anchoredPosition = val - ((Rect)(ref rect)).min;
			bar.sizeDelta = max - min;
			int count = 1 + (showPromotion ? 1 : 0) + (showConversion ? 1 : 0);
			TMP_Text componentInChildren = ((Component)nativeUpgrade).GetComponentInChildren<TMP_Text>(true);
			Place(upgrade, Object.op_Implicit((Object)(object)componentInChildren) ? componentInChildren.text : "Upgrade", 0, count, !selected.HasValue);
			if (showPromotion)
			{
				Place(promote, "Promote", 1, count, selected == true);
			}
			if (showConversion)
			{
				Place(convert, "Convert", (!showPromotion) ? 1 : 2, count, selected == false);
			}
			((Component)promote).gameObject.SetActive(showPromotion);
			((Component)convert).gameObject.SetActive(showConversion);
			SetNativeVisibility(craftVisibility, visible: false);
			SetNativeVisibility(upgradeVisibility, visible: false);
			((Component)bar).gameObject.SetActive(true);
		}

		private void IncludeRect(RectTransform button, ref Vector2 min, ref Vector2 max)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			button.GetWorldCorners(corners);
			Vector3[] array = corners;
			foreach (Vector3 val in array)
			{
				Vector2 val2 = Vector2.op_Implicit(((Transform)parent).InverseTransformPoint(val));
				min = Vector2.Min(min, val2);
				max = Vector2.Max(max, val2);
			}
		}

		private static void Place(Button button, string label, int index, int count, bool selected)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)((Component)button).transform;
			val.anchorMin = new Vector2((float)index / (float)count, 0f);
			val.anchorMax = new Vector2((float)(index + 1) / (float)count, 1f);
			val.offsetMin = new Vector2(2f, 0f);
			val.offsetMax = new Vector2(-2f, 0f);
			TMP_Text componentInChildren = ((Component)button).GetComponentInChildren<TMP_Text>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				componentInChildren.text = label;
			}
			((Selectable)button).interactable = !selected;
		}

		internal void Hide()
		{
			if (Object.op_Implicit((Object)(object)bar))
			{
				((Component)bar).gameObject.SetActive(false);
			}
			SetNativeVisibility(craftVisibility, visible: true);
			SetNativeVisibility(upgradeVisibility, visible: true);
		}

		private static void SetNativeVisibility(CanvasGroup group, bool visible)
		{
			if (Object.op_Implicit((Object)(object)group))
			{
				group.alpha = (visible ? 1f : 0f);
				group.blocksRaycasts = visible;
				group.interactable = visible;
			}
		}

		internal void Destroy()
		{
			Hide();
			if (Object.op_Implicit((Object)(object)bar))
			{
				Object.Destroy((Object)(object)((Component)bar).gameObject);
			}
			if (Object.op_Implicit((Object)(object)craftVisibility))
			{
				Object.Destroy((Object)(object)craftVisibility);
			}
			if (Object.op_Implicit((Object)(object)upgradeVisibility))
			{
				Object.Destroy((Object)(object)upgradeVisibility);
			}
		}
	}
	internal static class FailureTranspiler
	{
		internal static bool TryPatch(IList<CodeInstruction> original, FieldInfo? upgradeItemField, MethodInfo? restoreItemMethod, out List<CodeInstruction> patched, out string error)
		{
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Expected O, but got Unknown
			//IL_039f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Expected O, but got Unknown
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Expected O, but got Unknown
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c1: Expected O, but got Unknown
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Expected O, but got Unknown
			patched = ((IEnumerable<CodeInstruction>)original).Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction instruction) => new CodeInstruction(instruction))).ToList();
			error = "Could not locate the Forge outcome markers or restoration method.";
			int num = FindUniqueLog(original, "Upgrader <color=yellow>succeeded</color>");
			int num2 = FindUniqueLog(original, "Upgrader <color=red>BROKE</color>");
			int num3 = FindUniqueLog(original, "Upgrader <color=orange>FAILED</orange>");
			if (num < 0 || num2 <= num || num3 <= num2 || upgradeItemField == null || restoreItemMethod == null)
			{
				return false;
			}
			List<int> list = (from i in Enumerable.Range(num + 1, num2 - num - 1)
				where LoadsField(original[i], "m_breakChance")
				select i).ToList();
			error = "Could not locate the Forge break check or destruction exit.";
			if (list.Count != 1 || !IsBranch(original[num3 - 1], out var target))
			{
				return false;
			}
			int num4 = list[0] - 1;
			while (num4 > num && !IsUnconditionalBranch(original[num4]))
			{
				num4--;
			}
			error = "The Forge success and destruction branches do not reach the same completion instruction.";
			if (!IsBranch(original[num4], out var target2))
			{
				return false;
			}
			int num5 = FindUniqueTarget(original, target);
			if (num5 <= num3 || num5 != FindUniqueTarget(original, target2))
			{
				return false;
			}
			error = "Could not locate the material refund inside the Forge destruction branch.";
			if (!original.Skip(num2).Take(num3 - num2).Any((CodeInstruction i) => LoadsField(i, "m_breakReturnIngreientsAmount")))
			{
				return false;
			}
			error = "The Forge break check does not lead to the expected downgrade branch.";
			CodeInstruction comparison = original[num2 - 1];
			if (comparison.opcode.FlowControl != FlowControl.Cond_Branch || !(comparison.operand is Label item) || !original[num3].labels.Contains(item))
			{
				return false;
			}
			if (original.Skip(num4 + 1).Take(num2 - num4 - 1).Any((CodeInstruction i) => i.opcode.FlowControl == FlowControl.Branch || (i.opcode.FlowControl == FlowControl.Cond_Branch && i != comparison)))
			{
				return false;
			}
			error = "The Forge destruction branch has an exception boundary or an unexpected incoming jump.";
			if (original.Skip(num2).Take(num3 - num2).Any((CodeInstruction i) => i.blocks.Count != 0))
			{
				return false;
			}
			HashSet<Label> hashSet = new HashSet<Label>(original.Skip(num2 + 1).Take(num3 - num2 - 1).SelectMany((CodeInstruction i) => i.labels));
			for (int num6 = 0; num6 < original.Count; num6++)
			{
				if (num6 < num2 || num6 >= num3)
				{
					if (original[num6].operand is Label item2 && hashSet.Contains(item2))
					{
						return false;
					}
					if (original[num6].operand is Label[] source && source.Any(hashSet.Contains))
					{
						return false;
					}
				}
			}
			CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			val.labels.AddRange(patched[num2].labels);
			patched[num2].labels.Clear();
			patched.InsertRange(num2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[5]
			{
				val,
				new CodeInstruction(OpCodes.Ldfld, (object)upgradeItemField),
				new CodeInstruction(OpCodes.Ldarg_1, (object)null),
				new CodeInstruction(OpCodes.Call, (object)restoreItemMethod),
				new CodeInstruction(OpCodes.Brtrue, (object)target)
			});
			error = string.Empty;
			return true;
		}

		private static int FindUniqueLog(IList<CodeInstruction> instructions, string marker)
		{
			int num = -1;
			for (int i = 0; i < instructions.Count; i++)
			{
				if (!(instructions[i].opcode != OpCodes.Ldstr) && instructions[i].operand is string text && text.StartsWith(marker, StringComparison.Ordinal))
				{
					if (num >= 0)
					{
						return -1;
					}
					num = i;
				}
			}
			return num;
		}

		private static bool LoadsField(CodeInstruction instruction, string name)
		{
			if (instruction.opcode == OpCodes.Ldfld && instruction.operand is FieldInfo fieldInfo)
			{
				return fieldInfo.Name == name;
			}
			return false;
		}

		private static bool IsUnconditionalBranch(CodeInstruction instruction)
		{
			if (!(instruction.opcode == OpCodes.Br))
			{
				return instruction.opcode == OpCodes.Br_S;
			}
			return true;
		}

		private static bool IsBranch(CodeInstruction instruction, out Label target)
		{
			target = default(Label);
			if (!IsUnconditionalBranch(instruction) || !(instruction.operand is Label label))
			{
				return false;
			}
			target = label;
			return true;
		}

		private static int FindUniqueTarget(IList<CodeInstruction> instructions, Label target)
		{
			int num = -1;
			for (int i = 0; i < instructions.Count; i++)
			{
				if (instructions[i].labels.Contains(target))
				{
					if (num >= 0)
					{
						return -1;
					}
					num = i;
				}
			}
			return num;
		}
	}
	internal static class ForgeNetwork
	{
		private const string RequestRpc = "local.forgeofpotentialrepair.RequestSettings.v1";

		private const string SettingsRpc = "local.forgeofpotentialrepair.Settings.v1";

		private static readonly HashSet<ZNetPeer> Subscribers = new HashSet<ZNetPeer>();

		internal static readonly ForgeSession Session = new ForgeSession();

		private static ZNet? world;

		private static ForgeRules? lastBroadcast;

		private static float checkAgainAt;

		private static int requestsSent;

		private static bool loggedMissingHost;

		internal static ForgeRules? EffectiveRules
		{
			get
			{
				if (!Session.IsHost)
				{
					return Session.RemoteRules;
				}
				return Plugin.Settings.GetRules();
			}
		}

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "Awake", Type.EmptyTypes, (Type[])null), new HarmonyMethod(typeof(ForgeNetwork), "OnWorldStarting", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "OnDestroy", Type.EmptyTypes, (Type[])null), new HarmonyMethod(typeof(ForgeNetwork), "OnWorldEnding", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "OnNewConnection", new Type[1] { typeof(ZNetPeer) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ForgeNetwork), "RegisterPeer", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void OnWorldStarting(ZNet __instance)
		{
			SwitchWorld(__instance);
		}

		private static void OnWorldEnding(ZNet __instance)
		{
			if (world == __instance)
			{
				SwitchWorld(null);
			}
		}

		internal static void Stop()
		{
			SwitchWorld(null);
		}

		private static void SwitchWorld(ZNet? net)
		{
			world = net;
			Session.SetContext(isHost: false, null);
			Subscribers.Clear();
			lastBroadcast = null;
			ResetRequestTimer();
		}

		private static void ResetRequestTimer()
		{
			checkAgainAt = 0f;
			requestsSent = 0;
			loggedMissingHost = false;
		}

		private static void RegisterPeer(ZNet __instance, ZNetPeer __0)
		{
			if (__instance.IsServer())
			{
				__0.m_rpc.Register<int>("local.forgeofpotentialrepair.RequestSettings.v1", (Action<ZRpc, int>)delegate(ZRpc rpc, int protocol)
				{
					if (world == __instance && __instance.IsServer() && protocol == 1 && __0.m_rpc == rpc && __0.IsReady() && rpc.IsConnected())
					{
						Subscribers.Add(__0);
						SendSettings(rpc, Plugin.Settings.GetRules());
					}
				});
			}
			else
			{
				if (!__0.m_server)
				{
					return;
				}
				__0.m_rpc.Register<int, int, int>("local.forgeofpotentialrepair.Settings.v1", (Action<ZRpc, int, int, int>)delegate(ZRpc rpc, int protocol, int features, int extraLevels)
				{
					if (world == __instance && !__instance.IsServer() && __instance.GetServerPeer() == __0 && __0.m_rpc == rpc)
					{
						bool flag = !Session.RemoteRules.HasValue;
						if (Session.TryApply(rpc, protocol, features, extraLevels) && flag)
						{
							Plugin.Log.LogInfo((object)"Forge host settings received. Multiplayer Forge features are active.");
						}
					}
				});
			}
		}

		internal static void Update()
		{
			ZNet val = ZNet.instance;
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = null;
			}
			if (val != world)
			{
				SwitchWorld(val);
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (val.IsServer())
			{
				Session.SetContext(isHost: true, null);
				if (unscaledTime < checkAgainAt)
				{
					return;
				}
				checkAgainAt = unscaledTime + 1f;
				Subscribers.RemoveWhere((ZNetPeer peer) => !peer.IsReady() || !peer.m_rpc.IsConnected());
				ForgeRules rules = Plugin.Settings.GetRules();
				if (lastBroadcast.HasValue && lastBroadcast.Value.SameAs(rules))
				{
					return;
				}
				lastBroadcast = rules;
				{
					foreach (ZNetPeer subscriber in Subscribers)
					{
						SendSettings(subscriber.m_rpc, rules);
					}
					return;
				}
			}
			ZNetPeer serverPeer = val.GetServerPeer();
			ZRpc val2 = ((serverPeer != null && serverPeer.m_server && serverPeer.m_rpc.IsConnected()) ? serverPeer.m_rpc : null);
			if (Session.SetContext(isHost: false, val2))
			{
				ResetRequestTimer();
			}
			if (val2 != null && !Session.RemoteRules.HasValue && !(unscaledTime < checkAgainAt))
			{
				if (requestsSent < 2)
				{
					requestsSent++;
					checkAgainAt = unscaledTime + 2f;
					val2.Invoke("local.forgeofpotentialrepair.RequestSettings.v1", new object[1] { 1 });
				}
				else if (!loggedMissingHost)
				{
					loggedMissingHost = true;
					Plugin.Log.LogInfo((object)"Forge features are inactive. This host has not supplied compatible Forge settings.");
				}
			}
		}

		private static void SendSettings(ZRpc connection, ForgeRules rules)
		{
			connection.Invoke("local.forgeofpotentialrepair.Settings.v1", new object[3]
			{
				1,
				(int)rules.Features,
				rules.ExtraLevels
			});
		}
	}
	[Flags]
	internal enum ForgeFeature
	{
		BadLuckProtection = 1,
		IdolPromotion = 2,
		IdolConversion = 4,
		RefinementCap = 8,
		HideForgeGlow = 0x10
	}
	internal readonly struct ForgeRules
	{
		internal const int Protocol = 1;

		internal const int MaximumExtraLevels = 100;

		private const ForgeFeature KnownFeatures = ForgeFeature.BadLuckProtection | ForgeFeature.IdolPromotion | ForgeFeature.IdolConversion | ForgeFeature.RefinementCap | ForgeFeature.HideForgeGlow;

		internal readonly ForgeFeature Features;

		internal readonly int ExtraLevels;

		internal ForgeRules(ForgeFeature features, int extraLevels)
		{
			Features = features;
			ExtraLevels = extraLevels;
		}

		internal bool Has(ForgeFeature feature)
		{
			return (Features & feature) != 0;
		}

		internal bool SameAs(ForgeRules other)
		{
			if (Features == other.Features)
			{
				return ExtraLevels == other.ExtraLevels;
			}
			return false;
		}

		internal static ForgeRules? Decode(int protocol, int flags, int extraLevels)
		{
			if (protocol != 1 || (flags & -32) != 0 || extraLevels < 0 || extraLevels > 100)
			{
				return null;
			}
			return new ForgeRules((ForgeFeature)flags, extraLevels);
		}
	}
	internal sealed class ForgeSession
	{
		private object? hostConnection;

		internal bool IsHost { get; private set; }

		internal ForgeRules? RemoteRules { get; private set; }

		internal bool SetContext(bool isHost, object? connection)
		{
			if (IsHost == isHost && hostConnection == connection)
			{
				return false;
			}
			IsHost = isHost;
			hostConnection = connection;
			RemoteRules = null;
			return true;
		}

		internal bool TryApply(object from, int protocol, int features, int extraLevels)
		{
			if (IsHost || hostConnection == null || from != hostConnection)
			{
				return false;
			}
			ForgeRules? remoteRules = ForgeRules.Decode(protocol, features, extraLevels);
			if (!remoteRules.HasValue)
			{
				return false;
			}
			RemoteRules = remoteRules;
			return true;
		}
	}
	internal sealed class ForgeSettings
	{
		internal readonly ConfigEntry<bool> BadLuckProtection;

		internal readonly ConfigEntry<bool> IdolPromotion;

		internal readonly ConfigEntry<bool> IdolConversion;

		internal readonly ConfigEntry<bool> RefinementCap;

		internal readonly ConfigEntry<int> ExtraQualityLevels;

		internal readonly ConfigEntry<bool> HideForgeGlow;

		internal ForgeSettings(ConfigFile config)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			BadLuckProtection = config.Bind<bool>("Refinement", "BadLuckProtection", true, "Guarantee the next refinement after this item breaks twice at the same quality.");
			RefinementCap = config.Bind<bool>("Refinement", "EnableRefinementCap", false, "Limit how many levels the Forge can add above an item's normal maximum quality.");
			ExtraQualityLevels = config.Bind<int>("Refinement", "MaxExtraQualityLevels", 3, new ConfigDescription("Extra quality levels allowed when the cap is enabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			IdolPromotion = config.Bind<bool>("Idol Exchange", "EnableIdolPromotion", true, "Exchange two identical idols and one unit of the next tier's material for one idol of that tier.");
			IdolConversion = config.Bind<bool>("Idol Exchange", "EnableIdolConversion", true, "Exchange one idol and ten coins for the opposite type in the same tier.");
			HideForgeGlow = config.Bind<bool>("Appearance", "HideForgeGlow", false, "Hide the visual effects from refining equipment. Changes apply when visuals are recreated, such as on re-equip or reload.");
		}

		internal ForgeRules GetRules()
		{
			ForgeFeature forgeFeature = (ForgeFeature)0;
			if (BadLuckProtection.Value)
			{
				forgeFeature |= ForgeFeature.BadLuckProtection;
			}
			if (IdolPromotion.Value)
			{
				forgeFeature |= ForgeFeature.IdolPromotion;
			}
			if (IdolConversion.Value)
			{
				forgeFeature |= ForgeFeature.IdolConversion;
			}
			if (RefinementCap.Value)
			{
				forgeFeature |= ForgeFeature.RefinementCap;
			}
			if (HideForgeGlow.Value)
			{
				forgeFeature |= ForgeFeature.HideForgeGlow;
			}
			return new ForgeRules(forgeFeature, ExtraQualityLevels.Value);
		}
	}
	internal static class IdolExchange
	{
		private const int ConversionFee = 10;

		private static readonly string[] PromotionMaterials = new string[7] { "Bronze", "Iron", "Silver", "BlackMetal", "BlackMarble", "FlametalNew", "Gold" };

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

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

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

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

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

		private static readonly FieldInfo Rows = AccessTools.Field(typeof(InventoryGui), "m_availableRecipes");

		private static readonly MethodInfo RowObject = AccessTools.PropertyGetter(ForgePatches.SelectedRecipeType, "InterfaceElement");

		private static readonly MethodInfo IsCheated = AccessTools.Method(typeof(Player).Assembly.GetType("CheatUtils"), "IsCheated", new Type[1] { typeof(ZDO) }, (Type[])null);

		private static readonly Dictionary<Recipe, bool> Recipes = new Dictionary<Recipe, bool>();

		private static ObjectDB? recipeDatabase;

		private static ExchangeTabBar? tabBar;

		private static bool promotionSelected;

		internal static bool Ready;

		private static bool TabEnabled
		{
			get
			{
				if (!Enabled(promotion: true))
				{
					return Enabled(promotion: false);
				}
				return true;
			}
		}

		internal static void ApplyPatches(Harmony harmony)
		{
			if (IsCheated == null || InventoryChanged == null)
			{
				throw new InvalidOperationException("The game inventory or item provenance API changed.");
			}
			harmony.Patch((MethodBase)RefreshPanel, Method("BeforeRefreshPanel"), (HarmonyMethod)null, (HarmonyMethod)null, Method("AfterRefreshPanel"), (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "SetupCrafting", (Type[])null, (Type[])null), Method("SelectRefinementOnOpen"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "Hide", (Type[])null, (Type[])null), (HarmonyMethod)null, Method("HideExchangeTabs"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "UpdateRecipeList", (Type[])null, (Type[])null), Method("UseExchangeRecipes"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "AddRecipeToList", (Type[])null, (Type[])null), (HarmonyMethod)null, Method("NameExchangeRow"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "OnCraftPressed", (Type[])null, (Type[])null), Method("BeforeExchangePressed"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "HaveRequirements", new Type[4]
			{
				typeof(Recipe),
				typeof(bool),
				typeof(int),
				typeof(int)
			}, (Type[])null), Method("CheckExchangeRequirements"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Ready = true;
		}

		private static HarmonyMethod Method(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(IdolExchange), name, (Type[])null);
		}

		private static CraftingStation? CurrentForge(Player? player)
		{
			CraftingStation val = (Object.op_Implicit((Object)(object)player) ? player.GetCurrentCraftingStation() : null);
			if (!Object.op_Implicit((Object)(object)val) || !val.m_upgrader || !(val.m_name == "$piece_upgradestation"))
			{
				return null;
			}
			return val;
		}

		internal static void RefreshOpenForge()
		{
			if (!Ready || !InventoryGui.IsVisible() || !Object.op_Implicit((Object)(object)CurrentForge(Player.m_localPlayer)))
			{
				return;
			}
			InventoryGui instance = InventoryGui.instance;
			if (Object.op_Implicit((Object)(object)instance))
			{
				if (!TabEnabled && (bool)InCraftTab.Invoke(instance, null))
				{
					OpenUpgradeTab.Invoke(instance, null);
					return;
				}
				RefreshPanel.Invoke(instance, new object[1] { false });
			}
		}

		internal static bool IsExchangeTab(InventoryGui gui, Player player)
		{
			if (TabEnabled && Object.op_Implicit((Object)(object)CurrentForge(player)))
			{
				return (bool)InCraftTab.Invoke(gui, null);
			}
			return false;
		}

		private static void SelectRefinementOnOpen(Button ___m_tabCraft, Button ___m_tabUpgrade)
		{
			if (TabEnabled && Object.op_Implicit((Object)(object)CurrentForge(Player.m_localPlayer)))
			{
				promotionSelected = Enabled(promotion: true);
				((Selectable)___m_tabCraft).interactable = true;
				((Selectable)___m_tabUpgrade).interactable = false;
			}
		}

		private static void BeforeRefreshPanel(out CraftingStation? __state)
		{
			__state = null;
			CraftingStation val = CurrentForge(Player.m_localPlayer);
			if (TabEnabled && Object.op_Implicit((Object)(object)val))
			{
				if (!Enabled(promotionSelected))
				{
					promotionSelected = Enabled(promotion: true);
				}
				if (!val.m_hasCraftTab)
				{
					val.m_hasCraftTab = true;
					__state = val;
				}
			}
		}

		private static void AfterRefreshPanel(InventoryGui __instance, Button ___m_tabCraft, Button ___m_tabUpgrade, CraftingStation? __state, Exception? __exception)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			if (Object.op_Implicit((Object)(object)__state))
			{
				__state.m_hasCraftTab = false;
			}
			Player localPlayer = Player.m_localPlayer;
			if (__exception != null || !TabEnabled || !Object.op_Implicit((Object)(object)CurrentForge(localPlayer)))
			{
				HideExchangeTabs();
				return;
			}
			if (tabBar == null || !tabBar.Matches(___m_tabCraft, ___m_tabUpgrade))
			{
				tabBar?.Destroy();
				Canvas.ForceUpdateCanvases();
				tabBar = new ExchangeTabBar(___m_tabCraft, ___m_tabUpgrade, (RectTransform)((Component)___m_tabUpgrade).transform.parent, delegate(bool? mode)
				{
					SelectTab(__instance, mode);
				});
			}
			tabBar.Show(Enabled(promotion: true), Enabled(promotion: false), IsExchangeTab(__instance, localPlayer) ? new bool?(promotionSelected) : ((bool?)null));
		}

		private static void HideExchangeTabs()
		{
			tabBar?.Hide();
		}

		private static void SelectTab(InventoryGui gui, bool? promotion)
		{
			if (TabEnabled && Object.op_Implicit((Object)(object)CurrentForge(Player.m_localPlayer)))
			{
				if (!promotion.HasValue)
				{
					OpenUpgradeTab.Invoke(gui, null);
				}
				else if (Enabled(promotion.Value))
				{
					promotionSelected = promotion.Value;
					OpenCraftTab.Invoke(gui, null);
				}
			}
		}

		private static void UseExchangeRecipes(InventoryGui __instance, ref List<Recipe> __0)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!IsExchangeTab(__instance, localPlayer))
			{
				return;
			}
			PrepareRecipes();
			CraftingStation craftingStation = CurrentForge(localPlayer);
			List<Recipe> list = new List<Recipe>();
			foreach (KeyValuePair<Recipe, bool> recipe in Recipes)
			{
				if (IsSelectedCategory(recipe.Value))
				{
					recipe.Key.m_craftingStation = craftingStation;
					list.Add(recipe.Key);
				}
			}
			__0 = list;
		}

		private static void PrepareRecipes()
		{
			ObjectDB instance = ObjectDB.instance;
			if (!Object.op_Implicit((Object)(object)instance) || recipeDatabase == instance)
			{
				return;
			}
			DestroyRecipes();
			recipeDatabase = instance;
			for (int i = 0; i <= PromotionMaterials.Length; i++)
			{
				ItemDrop val = FindItem(instance, $"Upgrader{i}Weapon");
				ItemDrop val2 = FindItem(instance, $"Upgrader{i}Armor");
				ItemDrop catalyst = FindItem(instance, "Coins");
				AddRecipe(val, val2, catalyst, promotion: false);
				AddRecipe(val2, val, catalyst, promotion: false);
				if (i < PromotionMaterials.Length)
				{
					ItemDrop catalyst2 = FindItem(instance, PromotionMaterials[i]);
					AddRecipe(val, FindItem(instance, $"Upgrader{i + 1}Weapon"), catalyst2, promotion: true);
					AddRecipe(val2, FindItem(instance, $"Upgrader{i + 1}Armor"), catalyst2, promotion: true);
				}
			}
			Plugin.Log.LogInfo((object)$"Prepared {Recipes.Count} idol exchange recipes.");
		}

		private static ItemDrop? FindItem(ObjectDB database, string name)
		{
			GameObject itemPrefab = database.GetItemPrefab(name);
			ItemDrop result = default(ItemDrop);
			if (Object.op_Implicit((Object)(object)itemPrefab) && itemPrefab.TryGetComponent<ItemDrop>(ref result))
			{
				return result;
			}
			Plugin.Log.LogWarning((object)("Idol exchange ingredient or result '" + name + "' is unavailable."));
			return null;
		}

		private static void AddRecipe(ItemDrop? input, ItemDrop? output, ItemDrop? catalyst, bool promotion)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			if (Object.op_Implicit((Object)(object)input) && Object.op_Implicit((Object)(object)output) && Object.op_Implicit((Object)(object)catalyst))
			{
				Recipe val = ScriptableObject.CreateInstance<Recipe>();
				((Object)val).name = "local.forgeofpotentialrepair." + ((Object)input).name + "." + ((Object)output).name;
				val.m_item = output;
				val.m_amount = 1;
				val.m_minStationLevel = 1;
				val.m_enabled = true;
				val.m_resources = (Requirement[])(object)new Requirement[2]
				{
					new Requirement
					{
						m_resItem = input,
						m_amount = ((!promotion) ? 1 : 2),
						m_upgraderResource = true
					},
					new Requirement
					{
						m_resItem = catalyst,
						m_amount = (promotion ? 1 : 10),
						m_upgraderResource = true
					}
				};
				Recipes.Add(val, promotion);
			}
		}

		private static bool Enabled(bool promotion)
		{
			if (Ready)
			{
				return ForgeNetwork.EffectiveRules?.Has(promotion ? ForgeFeature.IdolPromotion : ForgeFeature.IdolConversion) ?? false;
			}
			return false;
		}

		private static bool IsSelectedCategory(bool promotion)
		{
			if (promotionSelected == promotion)
			{
				return Enabled(promotion);
			}
			return false;
		}

		internal static bool IsExchange(Recipe? recipe)
		{
			if (Object.op_Implicit((Object)(object)recipe))
			{
				return Recipes.ContainsKey(recipe);
			}
			return false;
		}

		private static void NameExchangeRow(InventoryGui __instance, Recipe __1)
		{
			if (IsExchange(__1) && Rows?.GetValue(__instance) is IList { Count: not 0 } list)
			{
				object? obj = RowObject?.Invoke(list[list.Count - 1], null);
				GameObject val = (GameObject)((obj is GameObject) ? obj : null);
				object obj2;
				if (!Object.op_Implicit((Object)(object)val))
				{
					obj2 = null;
				}
				else
				{
					Transform obj3 = val.transform.Find("name");
					obj2 = ((obj3 != null) ? ((Component)obj3).GetComponent<TMP_Text>() : null);
				}
				TMP_Text val2 = (TMP_Text)obj2;
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.text = Action(__1) + ": " + val2.text;
				}
			}
		}

		private static string Action(Recipe recipe)
		{
			if (!Recipes[recipe])
			{
				return "Convert";
			}
			return "Promote";
		}

		internal static void ShowExchange(Player player, Recipe recipe, TMP_Text title, TMP_Text description, TMP_Text notice, Button button, float craftTimer)
		{
			string text = Action(recipe);
			if (Object.op_Implicit((Object)(object)title))
			{
				title.text = text + ": " + Name(recipe.m_item);
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (Object.op_Implicit((Object)(object)description))
			{
				Requirement val = recipe.m_resources[0];
				Requirement val2 = recipe.m_resources[1];
				description.text = $"{val.m_amount} × {Name(val.m_resItem)} + {val2.m_amount} × {Name(val2.m_resItem)}" + "\n→ 1 × " + Name(recipe.m_item);
			}
			if (Object.op_Implicit((Object)(object)notice))
			{
				((Component)notice).gameObject.SetActive(true);
				notice.text = "Guaranteed exchange";
			}
			if (Object.op_Implicit((Object)(object)button))
			{
				TMP_Text componentInChildren = ((Component)button).GetComponentInChildren<TMP_Text>();
				if (Object.op_Implicit((Object)(object)componentInChildren))
				{
					componentInChildren.text = text;
				}
				CraftingStation val3 = CurrentForge(player);
				ExchangePlan plan;
				string error;
				string text2 = ((!Enabled(Recipes[recipe])) ? "This exchange is disabled." : ((craftTimer >= 0f) ? "Finish the current refinement first." : ((!Object.op_Implicit((Object)(object)val3) || !val3.CheckUsable(player, false)) ? "Use the Forge of Potential to exchange idols." : ((!TryPlan(inventory, recipe, val3, out plan, out error)) ? error : null))));
				((Selectable)button).interactable = text2 == null;
				UITooltip component = ((Component)button).GetComponent<UITooltip>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.m_text = text2 ?? string.Empty;
				}
			}
		}

		private static string Name(ItemDrop item)
		{
			return Localization.instance.Localize(item.m_itemData.m_shared.m_name);
		}

		private static bool CheckExchangeRequirements(Player __instance, Recipe __0, ref bool __result)
		{
			if (!IsExchange(__0))
			{
				return true;
			}
			CraftingStation val = CurrentForge(__instance);
			__result = Enabled(Recipes[__0]) && Object.op_Implicit((Object)(object)val) && TryPlan(((Humanoid)__instance).GetInventory(), __0, val, out ExchangePlan _, out string _);
			return false;
		}

		private static bool BeforeExchangePressed(InventoryGui __instance, float ___m_craftTimer)
		{
			Recipe selectedRecipe = ForgePatches.GetSelectedRecipe(__instance);
			if (!IsExchange(selectedRecipe))
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			CraftingStation val = CurrentForge(localPlayer);
			if (!Object.op_Implicit((Object)(object)localPlayer) || !Object.op_Implicit((Object)(object)val) || !IsExchangeTab(__instance, localPlayer) || !IsSelectedCategory(Recipes[selectedRecipe]) || ___m_craftTimer >= 0f || !val.CheckUsable(localPlayer, true))
			{
				return false;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			if (!TryPlan(inventory, selectedRecipe, val, out ExchangePlan plan, out string error))
			{
				((Character)localPlayer).Message((MessageType)2, error, 0, (Sprite)null, false);
				return false;
			}
			plan.Commit(inventory);
			try
			{
				InventoryChanged.Invoke(inventory, new object[2]
				{
					true,
					plan.Cheated && !Achievements.IsCheatedAtAll()
				});
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("An inventory callback threw after the idol exchange completed. " + ex));
			}
			((Character)localPlayer).Message((MessageType)2, Action(selectedRecipe) + " complete: " + Name(selectedRecipe.m_item), 0, (Sprite)null, false);
			RefreshPanel.Invoke(__instance, new object[1] { false });
			return false;
		}

		private static bool TryPlan(Inventory inventory, Recipe recipe, CraftingStation station, out ExchangePlan? plan, out string? error)
		{
			Requirement val = recipe.m_resources[0];
			Requirement val2 = recipe.m_resources[1];
			ItemData val3 = recipe.m_item.m_itemData.Clone();
			val3.m_stack = 1;
			val3.m_dropPrefab = ((Component)recipe.m_item).gameObject;
			val3.m_worldLevel = Game.m_worldLevel;
			ZNetView component = ((Component)station).GetComponent<ZNetView>();
			ZDO val4 = ((component != null) ? component.GetZDO() : null);
			val3.m_cheated |= val4 != null && (bool)IsCheated.Invoke(null, new object[1] { val4 });
			plan = ExchangePlan.Create(inventory, val.m_resItem.m_itemData, val.m_amount, val2.m_resItem.m_itemData, val2.m_amount, val3, out var problem);
			error = problem switch
			{
				ExchangePlan.Problem.MissingIdol => $"Requires {val.m_amount} × {Name(val.m_resItem)}.", 
				ExchangePlan.Problem.MissingCatalyst => $"Requires {val2.m_amount} × {Name(val2.m_resItem)}.", 
				ExchangePlan.Problem.NoSpace => "Make room in your inventory for the exchanged idol.", 
				_ => null, 
			};
			return plan != null;
		}

		internal static void CleanUp()
		{
			Ready = false;
			tabBar?.Destroy();
			tabBar = null;
			DestroyRecipes();
		}

		private static void DestroyRecipes()
		{
			foreach (Recipe key in Recipes.Keys)
			{
				Object.Destroy((Object)(object)key);
			}
			Recipes.Clear();
			recipeDatabase = null;
		}
	}
	[BepInPlugin("local.forgeofpotentialrepair", "Forge of Potential – Repairable Failure", "0.3.0")]
	[BepInProcess("valheim.exe")]
	[BepInProcess("valheim_server.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "local.forgeofpotentialrepair";

		public const string PluginName = "Forge of Potential – Repairable Failure";

		public const string PluginVersion = "0.3.0";

		private Harmony? harmony;

		private bool dedicated;

		private ForgeFeature? previousFeatures;

		internal static bool ProtectionReady;

		internal static ManualLogSource Log { get; private set; }

		internal static ForgeSettings Settings { get; private set; }

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Settings = new ForgeSettings(((BaseUnityPlugin)this).Config);
			harmony = new Harmony("local.forgeofpotentialrepair");
			dedicated = string.Equals(Paths.ProcessName, "valheim_server", StringComparison.OrdinalIgnoreCase);
			try
			{
				ForgeNetwork.ApplyPatches(harmony);
				if (dedicated)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Forge of Potential – Repairable Failure loaded. Serving Forge settings to compatible clients.");
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not initialize multiplayer Forge settings. " + ex));
			}
			if (dedicated)
			{
				return;
			}
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(InventoryGui), "DoCrafting", new Type[1] { typeof(Player) }, (Type[])null);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ForgePatches), "BeforeCraft", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ForgePatches), "TranspileCraft", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "UpdateRecipe", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ForgePatches), "AfterUpdateRecipe", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(InventoryGui), "CanRepair", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ForgePatches), "AfterCanRepair", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)(ProtectionReady ? "Forge of Potential – Repairable Failure loaded. Repairable failure is available in worlds using Forge settings." : "The Forge compatibility check failed. Refinement is blocked in worlds using Forge settings."));
			}
			catch (Exception ex2)
			{
				ProtectionReady = false;
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not initialize Forge protection. Do not use the Forge until this is resolved. " + ex2));
			}
			try
			{
				IdolExchange.ApplyPatches(harmony);
			}
			catch (Exception ex3)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Idol exchanges could not be initialized. " + ex3));
			}
			try
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(ParticleIntensityScaler), "SetQuality", new Type[1] { typeof(int) }, (Type[])null), new HarmonyMethod(typeof(ForgeGlow), "BeforeSetQuality", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex4)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("The Forge glow setting could not be initialized. " + ex4));
			}
		}

		private void Update()
		{
			ForgeNetwork.Update();
			if (!dedicated)
			{
				ForgeFeature? forgeFeature = ForgeNetwork.EffectiveRules?.Features;
				if (forgeFeature != previousFeatures)
				{
					previousFeatures = forgeFeature;
					IdolExchange.RefreshOpenForge();
				}
			}
		}

		private void OnDestroy()
		{
			ProtectionReady = false;
			ForgeNetwork.Stop();
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if (!dedicated)
			{
				IdolExchange.CleanUp();
			}
		}
	}
	internal static class ForgePatches
	{
		private static readonly FieldInfo? UpgradeItem = AccessTools.Field(typeof(InventoryGui), "m_craftUpgradeItem");

		private static readonly FieldInfo? CraftRecipe = AccessTools.Field(typeof(InventoryGui), "m_craftRecipe");

		private static readonly FieldInfo? SelectedRecipe = AccessTools.Field(typeof(InventoryGui), "m_selectedRecipe");

		internal static readonly Type? SelectedRecipeType = SelectedRecipe?.FieldType;

		private static readonly MethodInfo? SelectedItemGetter = ((SelectedRecipeType == null) ? null : AccessTools.PropertyGetter(SelectedRecipeType, "ItemData"));

		private static readonly MethodInfo? SelectedRecipeGetter = ((SelectedRecipeType == null) ? null : AccessTools.PropertyGetter(SelectedRecipeType, "Recipe"));

		internal static Recipe? GetSelectedRecipe(InventoryGui gui)
		{
			object obj = SelectedRecipe?.GetValue(gui);
			if (obj != null)
			{
				object? obj2 = SelectedRecipeGetter?.Invoke(obj, null);
				return (Recipe?)((obj2 is Recipe) ? obj2 : null);
			}
			return null;
		}

		internal static bool BeforeCraft(InventoryGui __instance, Player __0)
		{
			object? obj = CraftRecipe?.GetValue(__instance);
			if (IdolExchange.IsExchange((Recipe?)((obj is Recipe) ? obj : null)))
			{
				return false;
			}
			if (!AtPotentialForge(__0))
			{
				return true;
			}
			object? obj2 = UpgradeItem?.GetValue(__instance);
			string rejection = GetRejection((ItemData?)((obj2 is ItemData) ? obj2 : null));
			if (rejection == null)
			{
				return true;
			}
			((Character)__0).Message((MessageType)2, rejection, 0, (Sprite)null, false);
			return false;
		}

		internal static IEnumerable<CodeInstruction> TranspileCraft(IEnumerable<CodeInstruction> instructions)
		{
			Plugin.ProtectionReady = false;
			Refinement.BadLuckReady = false;
			if (!(Plugin.ProtectionReady = FailureTranspiler.TryPatch(instructions.ToList(), UpgradeItem, AccessTools.Method(typeof(ForgePatches), "TryRestoreBrokenItem", (Type[])null, (Type[])null), out List<CodeInstruction> patched, out string error)))
			{
				Plugin.Log.LogError((object)(error + " Forge refinement will be blocked in worlds using Forge settings."));
			}
			else
			{
				Refinement.BadLuckReady = Refinement.TryPatchChance(patched, UpgradeItem);
				if (!Refinement.BadLuckReady)
				{
					Plugin.Log.LogWarning((object)"Bad-luck protection is unavailable because the refinement chance comparison changed.");
				}
			}
			return patched;
		}

		internal static bool TryRestoreBrokenItem(ItemData item, Player player)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (!ForgeNetwork.EffectiveRules.HasValue)
			{
				return false;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			item.m_durability = 0f;
			Refinement.RecordBreak(item);
			if (!inventory.ContainsItem(item) && !TryRestoreToInventory(inventory, item, useOriginalSlot: true) && !TryRestoreToInventory(inventory, item, useOriginalSlot: false))
			{
				if (!Object.op_Implicit((Object)(object)ItemDrop.DropItem(item, item.m_stack, ((Component)player).transform.position + Vector3.up, Quaternion.identity)))
				{
					throw new InvalidOperationException("Could not restore the broken Forge item.");
				}
				Plugin.Log.LogWarning((object)"Inventory filled during refinement; the broken item was dropped at the player.");
				((Character)player).Message((MessageType)2, "Refinement failed. Your equipment broke and was dropped at your feet. Repair it at its usual crafting station.", 0, (Sprite)null, false);
				return true;
			}
			((Character)player).Message((MessageType)2, "Refinement failed. Your equipment is at zero durability. Repair it at its usual crafting station.", 0, (Sprite)null, false);
			return true;
		}

		private static bool TryRestoreToInventory(Inventory inventory, ItemData item, bool useOriginalSlot)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return useOriginalSlot ? inventory.AddItem(item, item.m_gridPos) : inventory.AddItem(item);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("An inventory hook threw while restoring the broken item. " + ex));
				return inventory.ContainsItem(item);
			}
		}

		internal static void AfterUpdateRecipe(InventoryGui __instance, Player __0, TMP_Text ___m_itemCraftType, TMP_Text ___m_recipeName, TMP_Text ___m_recipeDecription, Button ___m_craftButton, float ___m_craftTimer)
		{
			if (!ForgeNetwork.EffectiveRules.HasValue || !AtPotentialForge(__0))
			{
				return;
			}
			object obj = SelectedRecipe?.GetValue(__instance);
			if (obj == null || SelectedItemGetter == null)
			{
				return;
			}
			object? obj2 = SelectedRecipeGetter?.Invoke(obj, null);
			Recipe recipe = (Recipe)((obj2 is Recipe) ? obj2 : null);
			if (IdolExchange.IsExchange(recipe))
			{
				IdolExchange.ShowExchange(__0, recipe, ___m_recipeName, ___m_recipeDecription, ___m_itemCraftType, ___m_craftButton, ___m_craftTimer);
				return;
			}
			object? obj3 = SelectedItemGetter.Invoke(obj, null);
			string rejection = GetRejection((ItemData?)((obj3 is ItemData) ? obj3 : null));
			if (Object.op_Implicit((Object)(object)___m_itemCraftType))
			{
				___m_itemCraftType.text = rejection ?? "A destruction roll leaves the equipment at zero durability. Repair it at its usual crafting station before trying again.";
			}
			if (rejection != null && Object.op_Implicit((Object)(object)___m_craftButton))
			{
				((Selectable)___m_craftButton).interactable = false;
				UITooltip component = ((Component)___m_craftButton).GetComponent<UITooltip>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.m_text = rejection;
				}
			}
		}

		internal static void AfterCanRepair(ref bool __result)
		{
			if (ForgeNetwork.EffectiveRules.HasValue && AtPotentialForge(Player.m_localPlayer))
			{
				__result = false;
			}
		}

		private static bool AtPotentialForge(Player player)
		{
			if (!Object.op_Implicit((Object)(object)player))
			{
				return false;
			}
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			if (Object.op_Implicit((Object)(object)currentCraftingStation))
			{
				return currentCraftingStation.m_upgrader;
			}
			return false;
		}

		private static string? GetRejection(ItemData? item)
		{
			ForgeRules? effectiveRules = ForgeNetwork.EffectiveRules;
			if (!effectiveRules.HasValue)
			{
				return null;
			}
			if (!Plugin.ProtectionReady)
			{
				return "Forge refinement is blocked. Check the BepInEx log for details.";
			}
			if (item?.m_shared == null)
			{
				return "Select equipment to refine.";
			}
			if (!item.m_shared.m_useDurability || !item.m_shared.m_canBeReparied || item.m_shared.m_maxStackSize != 1 || item.m_stack != 1)
			{
				return "This equipment does not support safe break-and-repair refinement.";
			}
			if (item.m_durability <= 0f)
			{
				return "Repair this equipment at its usual crafting station before refining it again.";
			}
			if (item.m_quality == int.MaxValue)
			{
				return "This item cannot gain another quality level.";
			}
			if (effectiveRules.Value.Has(ForgeFeature.RefinementCap))
			{
				long num = (long)item.m_shared.m_maxQuality + (long)effectiveRules.Value.ExtraLevels;
				if (item.m_quality >= num)
				{
					return $"This item has reached the refinement cap (quality {num}).";
				}
			}
			return null;
		}
	}
	internal static class Refinement
	{
		private const string FailureKey = "local.forgeofpotentialrepair.failures";

		private const int FailuresForGuarantee = 2;

		internal static bool BadLuckReady;

		internal static bool TryPatchChance(List<CodeInstruction> instructions, FieldInfo? upgradeItem)
		{
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(Refinement), "SuccessChance", (Type[])null, (Type[])null);
			FieldInfo chance = AccessTools.Field(typeof(SharedData), "m_upgradeChance");
			int num = instructions.FindIndex((CodeInstruction i) => i.opcode == OpCodes.Ldfld && object.Equals(i.operand, chance));
			if (!(upgradeItem == null) && !(chance == null) && num >= 0 && num + 3 < instructions.Count && instructions.Count((CodeInstruction i) => i.opcode == OpCodes.Ldfld && object.Equals(i.operand, chance)) == 1)
			{
				string? name = instructions[num + 1].opcode.Name;
				if (name != null && name.StartsWith("ldloc", StringComparison.Ordinal) && (!(instructions[num + 2].opcode != OpCodes.Blt_Un) || !(instructions[num + 2].opcode != OpCodes.Blt_Un_S)) && instructions[num + 3].operand is string text && text.StartsWith("Upgrader <color=yellow>succeeded</color>", StringComparison.Ordinal) && instructions[num + 1].labels.Count == 0 && instructions[num + 1].blocks.Count == 0)
				{
					instructions.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
					{
						new CodeInstruction(OpCodes.Ldarg_0, (object)null),
						new CodeInstruction(OpCodes.Ldfld, (object)upgradeItem),
						new CodeInstruction(OpCodes.Call, (object)methodInfo)
					});
					return true;
				}
			}
			return false;
		}

		internal static float SuccessChance(float baseChance, ItemData item)
		{
			if (BadLuckReady)
			{
				ForgeRules? effectiveRules = ForgeNetwork.EffectiveRules;
				if (effectiveRules.HasValue && effectiveRules.GetValueOrDefault().Has(ForgeFeature.BadLuckProtection) && FailuresAtCurrentQuality(item) >= 2)
				{
					return 1f;
				}
			}
			return baseChance;
		}

		internal static void RecordBreak(ItemData item)
		{
			if (BadLuckReady)
			{
				ForgeRules? effectiveRules = ForgeNetwork.EffectiveRules;
				if (effectiveRules.HasValue && effectiveRules.GetValueOrDefault().Has(ForgeFeature.BadLuckProtection))
				{
					int num = Math.Min(FailuresAtCurrentQuality(item) + 1, 2);
					item.m_customData["local.forgeofpotentialrepair.failures"] = item.m_quality.ToString(CultureInfo.InvariantCulture) + ":" + num.ToString(CultureInfo.InvariantCulture);
				}
			}
		}

		private static int FailuresAtCurrentQuality(ItemData item)
		{
			if (item == null || !item.m_customData.TryGetValue("local.forgeofpotentialrepair.failures", out var value))
			{
				return 0;
			}
			int num = value.IndexOf(':');
			if (num <= 0 || !int.TryParse(value.Substring(0, num), NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result != item.m_quality || !int.TryParse(value.Substring(num + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var result2))
			{
				return 0;
			}
			return Math.Min(result2, 2);
		}
	}
	internal static class ForgeGlow
	{
		internal static void BeforeSetQuality(ref int __0, int ___maxQuality)
		{
			if (__0 > ___maxQuality)
			{
				ForgeRules? effectiveRules = ForgeNetwork.EffectiveRules;
				if (effectiveRules.HasValue && effectiveRules.GetValueOrDefault().Has(ForgeFeature.HideForgeGlow))
				{
					__0 = ___maxQuality;
				}
			}
		}
	}
}