Decompiled source of CursedRelics v0.2.12

plugins/CursedRelics.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
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.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Clickable;
using SuperFantasyKingdom.Status;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CursedRelics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.12.0")]
[assembly: AssemblyInformationalVersion("0.2.12+15303624d873ba3045fb642e3bc1a1a48cd7c14a")]
[assembly: AssemblyProduct("CursedRelics")]
[assembly: AssemblyTitle("CursedRelics")]
[assembly: AssemblyVersion("0.2.12.0")]
namespace CursedRelics;

[HarmonyPatch]
internal static class BurnHooks
{
	private sealed class Contribution
	{
		internal float Share;
	}

	private static readonly ConditionalWeakTable<BurnStatus, Contribution> Sources = new ConditionalWeakTable<BurnStatus, Contribution>();

	[ThreadStatic]
	private static bool playerRefresh;

	[HarmonyPostfix]
	[HarmonyPatch(typeof(StatusManager), "AddStatusInternally")]
	private static void Applied(Status status, Entity origin)
	{
		BurnStatus val = (BurnStatus)(object)((status is BurnStatus) ? status : null);
		if (val != null && origin is UnitBase && Catalog.Held("gkj_CR_CinderGospel"))
		{
			Sources.GetOrCreateValue(val).Share = 1f;
			if (((Status)val).duration > 0f)
			{
				((Status)val).duration = ((Status)val).duration * 2f;
			}
			Extend(val);
		}
	}

	private static void Extend(BurnStatus burn)
	{
		float num = ((Status)burn).expiration - Time.time;
		if (num > 0f)
		{
			((Status)burn).expiration = ((Status)burn).expiration + num;
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(StatusManager), "CanAddStatus")]
	private static void Source(Entity origin, out bool __state)
	{
		__state = playerRefresh;
		playerRefresh = origin is UnitBase && Catalog.Held("gkj_CR_CinderGospel");
	}

	[HarmonyFinalizer]
	[HarmonyPatch(typeof(StatusManager), "CanAddStatus")]
	private static void Restore(bool __state)
	{
		playerRefresh = __state;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(BurnStatus), "Stack")]
	private static void BeforeStack(BurnStatus __instance, out float __state)
	{
		__state = ((Status)__instance).amount;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(BurnStatus), "Stack")]
	private static void AfterStack(BurnStatus __instance, float __state, StatusScriptableObject newStatus, float modifier, Stats stats)
	{
		Contribution value;
		bool flag = Sources.TryGetValue(__instance, out value);
		if (playerRefresh || flag)
		{
			if (playerRefresh && ((Status)__instance).duration > 0f && newStatus.GetDuration() > 0f)
			{
				Extend(__instance);
			}
			if (value == null)
			{
				value = Sources.GetOrCreateValue(__instance);
			}
			float num = newStatus.GetAmount() * modifier;
			float num2 = (playerRefresh ? 1f : 0f);
			if (stats is MonsterStats && CombatManager.Instance.CanBurnStack() && ((Status)__instance).amount > 0f)
			{
				value.Share = Mathf.Clamp01((__state * value.Share + num * num2) / ((Status)__instance).amount);
			}
			else if (num > __state)
			{
				value.Share = num2;
			}
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(BurnStatus), "OnTick", new Type[]
	{
		typeof(Entity),
		typeof(Stats)
	})]
	private static IEnumerable<CodeInstruction> Tick(IEnumerable<CodeInstruction> instructions)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		FieldInfo field = AccessTools.Field(typeof(Damage), "damageAmount");
		int num = list.FindIndex((CodeInstruction i) => CodeInstructionExtensions.StoresField(i, field));
		if (num < 0 || list.Count((CodeInstruction i) => CodeInstructionExtensions.StoresField(i, field)) != 1)
		{
			throw new InvalidOperationException("Unknown Burn tick layout.");
		}
		list.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), list[num]),
			CodeInstruction.Call(typeof(BurnHooks), "TickDamage", (Type[])null, (Type[])null)
		});
		return list;
	}

	private static float TickDamage(float damage, BurnStatus burn)
	{
		if (!Sources.TryGetValue(burn, out var value))
		{
			return damage;
		}
		return damage * (1f - 0.3f * value.Share);
	}
}
[HarmonyPatch(typeof(UICardRelic), "Init")]
internal static class CardFrames
{
	private const string TrimName = "Cursed Relic Trim";

	private const string SigilName = "Cursed Relic Sigil";

	private const string FieldName = "Cursed Relic Icon Field";

	private const string BannerName = "Cursed Relic Banner";

	private static readonly Regex SignedPercent = new Regex("[+-][0-9]+%");

	private static Sprite trim;

	private static Sprite sigil;

	private static Sprite iconField;

	private static Sprite ribbon;

	[HarmonyPostfix]
	private static void SetFrame(Relic __0, Image ___card, TextMeshProUGUI ___title, TextMeshProUGUI ___description)
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: 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_00ad: 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)
		if (!Object.op_Implicit((Object)(object)___card))
		{
			return;
		}
		RectTransform rectTransform = ((Graphic)___card).rectTransform;
		Transform obj = ((Transform)rectTransform).Find("BG");
		RectTransform val = (RectTransform)(object)((obj is RectTransform) ? obj : null);
		object banner = (object)(Object.op_Implicit((Object)(object)___title) ? /*isinst with value type is only supported in some contexts*/: null);
		bool flag = RewardIntegration.IsCursed(((Item)__0).GetIdentifier());
		if (flag)
		{
			((Component)SetLayer(rectTransform, "Cursed Relic Trim", trim ?? (trim = ReadSprite("frame.relic.png")), Vector2.zero, Vector2.one)).transform.SetAsFirstSibling();
			if (Object.op_Implicit((Object)(object)val))
			{
				SetLayer(val, "Cursed Relic Icon Field", iconField ?? (iconField = ReadSprite("frame.relic-icon-field.png")), Vector2.zero, Vector2.one);
			}
			SetLayer(rectTransform, "Cursed Relic Sigil", sigil ?? (sigil = ReadSprite("frame.relic-sigil.png")), new Vector2(0.81f, 0.76f), new Vector2(0.9f, 0.85f));
		}
		else
		{
			HideLayer(rectTransform, "Cursed Relic Trim");
			HideLayer(rectTransform, "Cursed Relic Sigil");
			HideLayer(val, "Cursed Relic Icon Field");
		}
		SetRibbon((RectTransform)banner, flag);
		SetDescriptionPadding(rectTransform, ___description, flag);
	}

	private static void SetDescriptionPadding(RectTransform face, TextMeshProUGUI description, bool cursed)
	{
		if (!Object.op_Implicit((Object)(object)description))
		{
			return;
		}
		RelicDescriptionPadding relicDescriptionPadding = default(RelicDescriptionPadding);
		((Component)description).TryGetComponent<RelicDescriptionPadding>(ref relicDescriptionPadding);
		if (cursed)
		{
			if (!Object.op_Implicit((Object)(object)relicDescriptionPadding))
			{
				relicDescriptionPadding = ((Component)description).gameObject.AddComponent<RelicDescriptionPadding>();
			}
			relicDescriptionPadding.Apply(face, description);
			((TMP_Text)description).text = SignedPercent.Replace(((TMP_Text)description).text, "<nobr>$0</nobr>");
		}
		else if (Object.op_Implicit((Object)(object)relicDescriptionPadding))
		{
			relicDescriptionPadding.Restore(description);
		}
	}

	private static void SetRibbon(RectTransform banner, bool cursed)
	{
		//IL_006d: 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)
		Image backing = default(Image);
		if (!Object.op_Implicit((Object)(object)banner) || !((Component)banner).TryGetComponent<Image>(ref backing))
		{
			return;
		}
		Transform val = ((Transform)banner).Find("Cursed Relic Banner");
		if (!cursed)
		{
			if (Object.op_Implicit((Object)(object)val))
			{
				((Component)val).GetComponent<RelicBannerTint>().Restore(backing);
				((Component)val).gameObject.SetActive(false);
			}
		}
		else
		{
			Image val2 = SetLayer(banner, "Cursed Relic Banner", ribbon ?? (ribbon = ReadSprite("frame.relic-banner.png")), new Vector2(0.025f, 0.355f), new Vector2(0.975f, 0.786f));
			((Component)val2).transform.SetAsFirstSibling();
			(Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<RelicBannerTint>() : ((Component)val2).gameObject.AddComponent<RelicBannerTint>()).Apply(backing);
		}
	}

	private static void HideLayer(RectTransform parent, string name)
	{
		if (Object.op_Implicit((Object)(object)parent))
		{
			Transform val = ((Transform)parent).Find(name);
			if (Object.op_Implicit((Object)(object)val))
			{
				((Component)val).gameObject.SetActive(false);
			}
		}
	}

	private static Image SetLayer(RectTransform parent, string name, Sprite sprite, Vector2 from, Vector2 to)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: 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)
		//IL_005c: 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_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: 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_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		Transform val = ((Transform)parent).Find(name);
		if (Object.op_Implicit((Object)(object)val))
		{
			((Component)val).gameObject.SetActive(true);
			return ((Component)val).GetComponent<Image>();
		}
		GameObject val2 = new GameObject(name, new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		});
		RectTransform val3 = (RectTransform)val2.transform;
		((Transform)val3).SetParent((Transform)(object)parent, false);
		val3.anchorMin = from;
		val3.anchorMax = to;
		Vector2 offsetMin = (val3.offsetMax = Vector2.zero);
		val3.offsetMin = offsetMin;
		Image component = val2.GetComponent<Image>();
		component.sprite = sprite;
		((Graphic)component).raycastTarget = false;
		return component;
	}

	private static Sprite ReadSprite(string resource)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: 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)
		//IL_005d: Expected O, but got Unknown
		//IL_008b: 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)
		using Stream stream = typeof(CardFrames).Assembly.GetManifestResourceStream(resource) ?? throw new InvalidOperationException("Missing embedded card art " + resource);
		using MemoryStream memoryStream = new MemoryStream();
		stream.CopyTo(memoryStream);
		Texture2D val = new Texture2D(2, 2)
		{
			name = resource,
			filterMode = (FilterMode)0,
			wrapMode = (TextureWrapMode)1,
			hideFlags = (HideFlags)61
		};
		if (!ImageConversion.LoadImage(val, memoryStream.ToArray()))
		{
			throw new InvalidDataException(resource);
		}
		Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 32f, 0u, (SpriteMeshType)0);
		((Object)obj).name = resource;
		((Object)obj).hideFlags = (HideFlags)61;
		return obj;
	}
}
internal sealed class RelicDescriptionPadding : MonoBehaviour
{
	private Vector4 original;

	private bool applied;

	internal void Apply(RectTransform face, TextMeshProUGUI description)
	{
		//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_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_0035: 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_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: 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)
		if (!applied)
		{
			original = ((TMP_Text)description).margin;
			Vector3 val = ((Transform)((TMP_Text)description).rectTransform).InverseTransformVector(((Transform)face).TransformVector(new Vector3(1f, 1f, 0f)));
			((TMP_Text)description).margin = original + new Vector4(8f * val.x, 2f * val.y, 12f * val.x, 6f * val.y);
			applied = true;
		}
	}

	internal void Restore(TextMeshProUGUI description)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		if (applied)
		{
			((TMP_Text)description).margin = original;
			applied = false;
		}
	}
}
internal sealed class RelicBannerTint : MonoBehaviour
{
	private Color original;

	private bool applied;

	internal void Apply(Image backing)
	{
		//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_0017: 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_0035: Unknown result type (might be due to invalid IL or missing references)
		if (!applied)
		{
			original = ((Graphic)backing).color;
			((Graphic)backing).color = original * new Color(0.67f, 0.68f, 0.92f, 1f);
			applied = true;
		}
	}

	internal void Restore(Image backing)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		if (applied)
		{
			((Graphic)backing).color = original;
			applied = false;
		}
	}
}
[HarmonyPatch]
internal static class Catalog
{
	internal const string Crown = "gkj_CR_PaupersCrown";

	internal const string Bell = "gkj_CR_LastWatch";

	internal const string Gospel = "gkj_CR_CinderGospel";

	internal const string Hourglass = "gkj_CR_HourglassOfAsh";

	internal const string Glass = "gkj_CR_GlassCrown";

	internal const string Hollow = "gkj_CR_HollowBulwark";

	internal const string Ledger = "gkj_CR_FerrymansLedger";

	internal const string Vulture = "gkj_CR_VulturesCovenant";

	internal const string Rampart = "gkj_CR_GildedRampart";

	internal const string Mercy = "gkj_CR_RedMercy";

	private static readonly (string Id, string Title, string Gift, string Curse)[] Entries = new(string, string, string, string)[10]
	{
		("gkj_CR_PaupersCrown", "Pauper's Crown", "At dusk, 5 coins or fewer grant +25% Power.", "With 6+, lose 10% Power that night."),
		("gkj_CR_LastWatch", "Bell of the Last Watch", "First wall hit grants +40% Power for 12s.", "Start each night with 20% less wall health capacity."),
		("gkj_CR_CinderGospel", "Cinder Gospel", "Your Burns last twice as long.", "Each tick deals 30% less damage."),
		("gkj_CR_HourglassOfAsh", "Hourglass of Ash", "+35% Power from dusk to midnight.", "-20% Power from midnight to the end of battle."),
		("gkj_CR_GlassCrown", "Glass Crown", "+30% Power at night.", "Units have 25% less max HP that night."),
		("gkj_CR_HollowBulwark", "Hollow Bulwark", "+50% Shield capacity at night.", "Empty Shields cannot regenerate on their own that night."),
		("gkj_CR_FerrymansLedger", "Ferryman's Ledger", "The first ally to fall each night earns 3 coins.", "Then allies lose 20% Power that night."),
		("gkj_CR_VulturesCovenant", "Vulture's Covenant", "Hits deal +35% damage below 25% enemy HP.", "Hits deal -15% above 75% enemy HP."),
		("gkj_CR_GildedRampart", "Gilded Rampart", "+25% wall health capacity at night.", "Units lose 15% Power that night."),
		("gkj_CR_RedMercy", "Red Mercy", "Units receive 30% more HP healing at night.", "Units lose 20% Power that night.")
	};

	internal static readonly string[] Ids = Entries.Select(((string Id, string Title, string Gift, string Curse) entry) => entry.Id).ToArray();

	private static readonly Dictionary<string, Relic> Prototypes = new Dictionary<string, Relic>();

	private static AddressablesManager registered;

	[HarmonyPostfix]
	[HarmonyPatch(typeof(AddressablesManager), "LoadCatalog")]
	private static IEnumerator Loaded(IEnumerator __result, AddressablesManager __instance)
	{
		while (__result.MoveNext())
		{
			yield return __result.Current;
		}
		if (__instance.IsLoaded())
		{
			Register(__instance);
		}
	}

	private static void Register(AddressablesManager __instance)
	{
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Expected O, but got Unknown
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0244: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Expected O, but got Unknown
		//IL_0280: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)registered == (Object)(object)__instance)
		{
			return;
		}
		registered = __instance;
		Prototypes.Clear();
		Relic val = __instance.GetRelic("GreenHouse") ?? __instance.GetRelic("BetterBerries");
		if (!Object.op_Implicit((Object)(object)val))
		{
			throw new InvalidOperationException("Missing base relic prefab.");
		}
		string[] ids = Ids;
		foreach (string text in ids)
		{
			if (__instance.GetAllRelics().ContainsKey(text))
			{
				continue;
			}
			Relic val2 = Object.Instantiate<Relic>(val);
			((Component)val2).gameObject.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)((Component)val2).gameObject);
			((Object)val2).name = text;
			Traverse val3 = Traverse.Create((object)val2);
			val3.Field("identifier").SetValue((object)text);
			val3.Field("kingdom").SetValue((object)(Races)11);
			val3.Field("relatedUnit").SetValue((object)"");
			val3.Field("requiredBuilding").SetValue((object)(BuildingType)666);
			val3.Field("requiredKingdomLevel").SetValue((object)0);
			val3.Field("upgrade").SetValue((object)null);
			val3.Field("rarity").SetValue((object)(Rarity)2);
			string[] array = new string[9] { "law", "generic", "racial", "soldAtCartographer1", "soldAtCartographer2", "soldAtCartographer3", "soldAtCartographer4", "triggerOnLoad", "triggerLater" };
			foreach (string text2 in array)
			{
				val3.Field(text2).SetValue((object)false);
			}
			val3.Field("keywords").SetValue((object)Array.Empty<EffectKeywordType>());
			val3.Field("attack").SetValue((object)new Attack());
			val3.Field("cooldown").SetValue((object)1E+09f);
			using Stream stream = typeof(Catalog).Assembly.GetManifestResourceStream(text + ".png");
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			Texture2D val4 = new Texture2D(2, 2)
			{
				filterMode = (FilterMode)0,
				hideFlags = (HideFlags)61
			};
			ImageConversion.LoadImage(val4, memoryStream.ToArray());
			Rect val5 = new Rect(0f, 0f, (float)((Texture)val4).width, (float)((Texture)val4).height);
			Vector2 val6 = new Vector2(0.5f, 0.5f);
			float num = ((Item)val).GetIcon().pixelsPerUnit * (float)((Texture)val4).width;
			Rect rect = ((Item)val).GetIcon().rect;
			Sprite val7 = Sprite.Create(val4, val5, val6, num / ((Rect)(ref rect)).width);
			((Object)val7).hideFlags = (HideFlags)61;
			val3.Field("icon").SetValue((object)val7);
			Image component = ((Component)val2).GetComponent<Image>();
			if ((Object)(object)component != (Object)null)
			{
				component.sprite = val7;
			}
			Prototypes.Add(text, val2);
		}
		Plugin.Log.LogInfo((object)("Registered " + Prototypes.Count + " cursed relics."));
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(AddressablesManager), "GetRelic")]
	private static void Resolve(string prefabName, ref Relic __result)
	{
		if (!Object.op_Implicit((Object)(object)__result) && prefabName != null && Prototypes.TryGetValue(prefabName, out var value))
		{
			__result = value;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(RelicManager), "IsUnlocked")]
	private static void Unlock(string relic, ref bool __result)
	{
		__result |= relic != null && Prototypes.ContainsKey(relic);
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(RelicManager), "SpawnRelic", new Type[] { typeof(Relic) })]
	private static void ShowInstance(Relic __result)
	{
		if (Object.op_Implicit((Object)(object)__result) && Prototypes.ContainsKey(((Object)__result).name))
		{
			((Component)__result).gameObject.SetActive(true);
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Item), "GetTitle")]
	private static bool Title(Item __instance, ref string __result)
	{
		return Text(__instance, title: true, ref __result);
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Item), "GetDescription")]
	private static bool Description(Item __instance, ref string __result)
	{
		return Text(__instance, title: false, ref __result);
	}

	private static bool Text(Item item, bool title, ref string result)
	{
		int num = Array.IndexOf(Ids, item.GetIdentifier());
		if (num < 0 || !Prototypes.ContainsKey(Ids[num]))
		{
			return true;
		}
		(string, string, string, string) tuple = Entries[num];
		result = (title ? tuple.Item2 : ("Gift: " + tuple.Item3 + "\n<color=#991F29>Curse: " + tuple.Item4 + "</color>"));
		return false;
	}

	internal static bool Available(string id)
	{
		if (Prototypes.ContainsKey(id) && RelicManager.Instance.IsUnlocked(id) && RelicManager.Instance.CanAddRelic(id))
		{
			if (!(id != "gkj_CR_LastWatch") || !(id != "gkj_CR_GildedRampart"))
			{
				if (Object.op_Implicit((Object)(object)WallManager.Instance))
				{
					return WallManager.Instance.HasWall();
				}
				return false;
			}
			return true;
		}
		return false;
	}

	internal static bool Held(string id)
	{
		if (Object.op_Implicit((Object)(object)RelicManager.Instance))
		{
			return RelicManager.Instance.HasRelic(id);
		}
		return false;
	}
}
[HarmonyPatch]
internal static class CombatRelics
{
	[HarmonyPrefix]
	[HarmonyPatch(typeof(Health), "ReceiveDamage")]
	private static void Covenant(Health __instance, ref Damage __0)
	{
		if (!__0.isStatus && !(__0.damageAmount <= 0f) && __0.origin is UnitBase && __instance.GetEntity() is MonsterBase && Catalog.Held("gkj_CR_VulturesCovenant"))
		{
			float healthPercentageAbs = __instance.GetHealthPercentageAbs();
			if (healthPercentageAbs < 0.25f)
			{
				__0.damageAmount *= 1.35f;
			}
			else if (healthPercentageAbs > 0.75f)
			{
				__0.damageAmount *= 0.85f;
			}
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Health), "ReceiveHeal")]
	private static void Mercy(Health __instance, ref Heal __0)
	{
		//IL_0022: 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_0030: Invalid comparison between Unknown and I4
		if (Night.Mercy && __instance.GetEntity() is UnitBase && __0.healAmount > 0f && ((int)__0.healType == 0 || (int)__0.healType == 1))
		{
			__0.healAmount *= 1.3f;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UnitHealth), "GetShieldRegenAmount")]
	private static void EmptyShield(UnitHealth __instance, ref float __result)
	{
		if (Night.Hollow && ((Health)__instance).GetShieldAmountAbs() <= 0f)
		{
			__result = 0f;
		}
	}
}
[HarmonyPatch]
internal static class Night
{
	private const int Origin = -18430672;

	private static readonly FieldRef<WallManager, float> Hp = AccessTools.FieldRefAccess<WallManager, float>("m_Hitpoints");

	private static readonly FieldRef<WallManager, float> Max = AccessTools.FieldRefAccess<WallManager, float>("m_MaxHitpoints");

	private static int day = -1;

	private static float crown;

	private static float bellUntil;

	private static bool rang;

	private static bool bell;

	private static bool rampart;

	private static bool glass;

	private static bool hourglass;

	private static bool afterMidnight;

	private static bool ledger;

	private static bool paidFerryman;

	private static WallManager wall;

	private static float withheld;

	private static float wallScale;

	internal static bool Hollow { get; private set; }

	internal static bool Mercy { get; private set; }

	internal static void Dusk(int currentDay)
	{
		if (day == currentDay)
		{
			return;
		}
		End();
		day = currentDay;
		glass = Catalog.Held("gkj_CR_GlassCrown");
		hourglass = Catalog.Held("gkj_CR_HourglassOfAsh");
		ledger = Catalog.Held("gkj_CR_FerrymansLedger");
		Hollow = Catalog.Held("gkj_CR_HollowBulwark");
		Mercy = Catalog.Held("gkj_CR_RedMercy");
		string text = "";
		if (Catalog.Held("gkj_CR_PaupersCrown"))
		{
			int coins = ResourceManager.Instance.GetCoins();
			crown = ((coins <= 5) ? 0.25f : (-0.1f));
			text = ((coins == 1) ? "1 coin" : (coins + " coins")) + " at dusk. Unit Power " + ((crown > 0f) ? "+25%" : "−10%") + " tonight.";
		}
		WallManager instance = WallManager.Instance;
		if (Object.op_Implicit((Object)(object)instance) && instance.HasWall() && Max.Invoke(instance) > 0f)
		{
			bell = Catalog.Held("gkj_CR_LastWatch");
			rampart = Catalog.Held("gkj_CR_GildedRampart");
			if (bell || rampart)
			{
				wall = instance;
				wallScale = (bell ? 0.8f : 1f) * (rampart ? 1.25f : 1f);
				SetWallCapacity();
				if (text.Length > 0)
				{
					text += "\n";
				}
				text += $"Wall capacity {Max.Invoke(wall) + withheld:0.##} → {Max.Invoke(wall):0.##} tonight.";
			}
		}
		Refresh();
		if (text.Length > 0)
		{
			AlertManager.Instance.DisplayMessage("Cursed Relics", text);
		}
	}

	internal static void Hit(float before, float after)
	{
		if (Object.op_Implicit((Object)(object)wall) && bell && !rang && before > after)
		{
			rang = true;
			bellUntil = Time.time + 12f;
			Refresh();
		}
	}

	[HarmonyPrefix]
	[HarmonyPriority(800)]
	[HarmonyPatch(typeof(DaytimeManager), "SwitchState")]
	private static void AtMidnight(DaytimeManager __instance)
	{
		if (hourglass && !afterMidnight && __instance.IsEvening() && __instance.CurrentDay() == day)
		{
			afterMidnight = true;
			Refresh();
			AlertManager.Instance.DisplayMessage("Hourglass of Ash", "Midnight. Units lose 20% Power for the rest of battle.");
		}
	}

	internal static void UnitDied(UnitBase unit)
	{
		if (Object.op_Implicit((Object)(object)unit) && ledger && !paidFerryman)
		{
			paidFerryman = true;
			ResourceManager instance = ResourceManager.Instance;
			instance.AddToCoins(3);
			instance.ResourceAmountChanged((ResourceType)12);
			Refresh();
			AlertManager.Instance.DisplayMessage("Ferryman’s Ledger", "First ally lost. Gain 3 coins and lose 20% Power tonight.");
		}
	}

	internal static void Update()
	{
		if (bellUntil > 0f && Time.time >= bellUntil)
		{
			bellUntil = 0f;
			Refresh();
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(WallManager), "AddToHitpointMultiplier")]
	private static void BeforeScale(WallManager __instance, out float __state)
	{
		__state = (((Object)(object)wall == (Object)(object)__instance) ? Max.Invoke(__instance) : 0f);
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(WallManager), "AddToHitpointMultiplier")]
	private static void AfterScale(WallManager __instance, float __state)
	{
		if (__state > 0f && (Object)(object)wall == (Object)(object)__instance)
		{
			withheld *= Max.Invoke(wall) / __state;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(WallManager), "SetAdditionalHitpoints")]
	private static void ReplacementCapacity(WallManager __instance, int val)
	{
		if (val > 0 && !((Object)(object)wall != (Object)(object)__instance))
		{
			SetWallCapacity();
		}
	}

	private static void SetWallCapacity()
	{
		withheld = Max.Invoke(wall) * (1f - wallScale);
		Max.Invoke(wall) *= wallScale;
		Hp.Invoke(wall) *= wallScale;
	}

	internal static void End()
	{
		if (day >= 0)
		{
			if (Object.op_Implicit((Object)(object)wall) && Max.Invoke(wall) > 0f)
			{
				float num = Hp.Invoke(wall) / Max.Invoke(wall);
				Max.Invoke(wall) += withheld;
				Hp.Invoke(wall) = Max.Invoke(wall) * num;
			}
			wall = null;
			day = -1;
			crown = (bellUntil = (withheld = 0f));
			rang = (bell = (rampart = (glass = (hourglass = (afterMidnight = (ledger = (paidFerryman = false)))))));
			Hollow = (Mercy = false);
			Refresh();
		}
	}

	private static void Refresh()
	{
		if (!Object.op_Implicit((Object)(object)UnitManager.Instance))
		{
			return;
		}
		UnitBase[] allUnits = UnitManager.Instance.GetAllUnits();
		foreach (UnitBase val in allUnits)
		{
			Stat val2 = ((!Object.op_Implicit((Object)(object)val)) ? null : ((StatContainer)(val.GetUnitStats()?)).damage);
			if (val2 == null)
			{
				continue;
			}
			float value = val2.Value;
			ApplyPower(val);
			if (!Mathf.Approximately(value, val2.Value))
			{
				Ability combatAbility = ((Entity)val).GetCombatAbility();
				if (combatAbility != null)
				{
					((AbilityBase)combatAbility).GetStats();
				}
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UnitBase), "AfterGridChange")]
	internal static void ApplyPower(UnitBase __instance)
	{
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)__instance))
		{
			return;
		}
		UnitStats unitStats = __instance.GetUnitStats();
		if (unitStats == null)
		{
			return;
		}
		Stat damage = ((StatContainer)unitStats).damage;
		damage.RemoveAllModifiersFromOrigin(-18430672);
		AddPower(damage, crown);
		if (bellUntil > Time.time)
		{
			AddPower(damage, 0.4f);
		}
		if (hourglass)
		{
			AddPower(damage, afterMidnight ? (-0.2f) : 0.35f);
		}
		if (glass)
		{
			AddPower(damage, 0.3f);
		}
		if (rampart)
		{
			AddPower(damage, -0.15f);
		}
		if (Mercy)
		{
			AddPower(damage, -0.2f);
		}
		if (paidFerryman)
		{
			AddPower(damage, -0.2f);
		}
		IHealth health = ((Entity)__instance).GetHealth();
		if (health != null)
		{
			float value = ((StatContainer)unitStats).maxHealth.Value;
			float value2 = ((StatContainer)unitStats).maxShield.Value;
			float healthPercentage = health.GetHealthPercentage() * Mathf.Sign(value);
			((StatContainer)unitStats).maxHealth.RemoveAllModifiersFromOrigin(-18430672);
			((StatContainer)unitStats).maxShield.RemoveAllModifiersFromOrigin(-18430672);
			if (glass)
			{
				((StatContainer)unitStats).maxHealth.AddModifier(new StatModifier(-0.25f, (StatModifierType)300, -18430672));
			}
			if (Hollow)
			{
				((StatContainer)unitStats).maxShield.AddModifier(new StatModifier(0.5f, (StatModifierType)300, -18430672));
			}
			if (!Mathf.Approximately(value, ((StatContainer)unitStats).maxHealth.Value) && value != 0f)
			{
				health.SetHealthPercentage(healthPercentage);
				health.SetCurrentHealth();
			}
			if (!Mathf.Approximately(value2, ((StatContainer)unitStats).maxShield.Value) && value2 > 0f)
			{
				health.SetShieldPercentage(health.GetShieldAmountAbs() / value2);
				health.SetCurrentShield();
			}
		}
	}

	private static void AddPower(Stat damage, float factor)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		if (factor != 0f)
		{
			damage.AddModifier(new StatModifier(factor, (StatModifierType)300, -18430672));
		}
	}
}
[BepInPlugin("gkj.cursedrelics", "Cursed Relics", "0.2.12")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	internal static ConfigEntry<int> Chance;

	internal static ConfigEntry<bool> Paid;

	internal static ManualLogSource Log;

	private Harmony patches;

	private void Awake()
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Expected O, but got Unknown
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected O, but got Unknown
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c7: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Chance = ((BaseUnityPlugin)this).Config.Bind<int>("Rewards", "CursedChancePercent", 35, new ConfigDescription("Chance for one cursed option in an eligible three-relic reward.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
		Paid = ((BaseUnityPlugin)this).Config.Bind<bool>("Rewards", "AllowPaidWager", false, "Allow a cooperating Hold the Line relic wager to offer one cursed choice.");
		patches = new Harmony("gkj.cursedrelics");
		try
		{
			patches.PatchAll(typeof(Plugin).Assembly);
		}
		catch
		{
			patches.UnpatchSelf();
			throw;
		}
		if (Chainloader.PluginInfos.TryGetValue("sfk.weeklycontracts", out var value))
		{
			Type type = ((object)value.Instance).GetType().Assembly.GetType("WeeklyContracts.Kingdom");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Choices", Type.EmptyTypes, (Type[])null));
			if (methodInfo?.ReturnType == typeof(string[]))
			{
				patches.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Rewards), "Weekly", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		if (Chainloader.PluginInfos.TryGetValue("gkj.holdtheline", out var value2))
		{
			Type type2 = ((object)value2.Instance).GetType().Assembly.GetType("HoldTheLine.RelicRewards");
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "Draw", (Type[])null, (Type[])null));
			if (methodInfo2?.ReturnType == typeof(string[]) && methodInfo2.GetParameters().Length == 1)
			{
				patches.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(Rewards), "Wager", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		GameManager.OnGameInit += Night.End;
		GameManager.OnGameInit += Rewards.ResetOpenings;
		DaytimeManager.OnSunsetStart += Night.Dusk;
		DaytimeManager.BeforeMorningStart += Morning;
		GameManager.BeforeStateChange += StateChange;
		UnitManager.OnUnitSpawn += Night.ApplyPower;
		UnitManager.OnUnitDeath += Night.UnitDied;
	}

	private static void Morning(int _)
	{
		Night.End();
	}

	private static void StateChange(GameState state)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Invalid comparison between Unknown and I4
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		if ((int)state == 4 || (int)state == 6 || (int)state == 5 || (int)state == 7)
		{
			Night.End();
		}
	}

	private void Update()
	{
		Night.Update();
		Rewards.KeyboardFocus();
	}

	private void OnDestroy()
	{
		GameManager.OnGameInit -= Night.End;
		GameManager.OnGameInit -= Rewards.ResetOpenings;
		DaytimeManager.OnSunsetStart -= Night.Dusk;
		DaytimeManager.BeforeMorningStart -= Morning;
		GameManager.BeforeStateChange -= StateChange;
		UnitManager.OnUnitSpawn -= Night.ApplyPower;
		UnitManager.OnUnitDeath -= Night.UnitDied;
		Night.End();
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}
}
public static class RewardIntegration
{
	public static bool IsCursed(string id)
	{
		return Array.IndexOf(Catalog.Ids, id) >= 0;
	}

	public static string[] PaidWagerChoices(string[] ordinary, string rewardKey)
	{
		if (!Plugin.Paid.Value)
		{
			return ordinary;
		}
		return Rewards.Mix(ordinary, rewardKey);
	}
}
[HarmonyPatch]
internal static class Rewards
{
	private sealed class Visit
	{
		internal string Key;

		internal int Roll;
	}

	private sealed class Offer
	{
		public string Key;

		public int Roll;

		public string[] Choices;
	}

	private static readonly FieldRef<UIOverlayMerchant, Func<Relic>> Generator = AccessTools.FieldRefAccess<UIOverlayMerchant, Func<Relic>>("m_GetRelicCallback");

	private static readonly FieldRef<DropBossChest, List<string>> Pool = AccessTools.FieldRefAccess<DropBossChest, List<string>>("RelicPool");

	private static readonly ConditionalWeakTable<DropBossChest, Visit> Visits = new ConditionalWeakTable<DropBossChest, Visit>();

	private static readonly Dictionary<string, int> Openings = new Dictionary<string, int>();

	private static readonly FieldRef<UICardRelic, string> CardId = AccessTools.FieldRefAccess<UICardRelic, string>("m_RelicIdentifier");

	internal static void ResetOpenings()
	{
		Openings.Clear();
	}

	internal static void KeyboardFocus()
	{
		Keyboard current = Keyboard.current;
		if (current == null || !((ButtonControl)current.tabKey).wasPressedThisFrame)
		{
			return;
		}
		OverlayManager instance = OverlayManager.Instance;
		EventSystem events = EventSystem.current;
		if (!Object.op_Implicit((Object)(object)events) || !Object.op_Implicit((Object)(object)instance) || !instance.IsOpen() || !Object.op_Implicit((Object)(object)GamepadManager.Instance) || GamepadManager.Instance.IsGamepadInUse())
		{
			return;
		}
		UIOverlayMerchant merchant = instance.GetMerchant();
		if (!Object.op_Implicit((Object)(object)merchant) || !((Behaviour)merchant).isActiveAndEnabled)
		{
			return;
		}
		UICardRelic[] componentsInChildren = ((Component)merchant).GetComponentsInChildren<UICardRelic>();
		if (componentsInChildren.Length != 3 || !componentsInChildren.Any((UICardRelic card) => RewardIntegration.IsCursed(CardId.Invoke(card))))
		{
			return;
		}
		Button[] array = (from card in componentsInChildren
			select ((UICard)card).GetCardButton() into button
			where Object.op_Implicit((Object)(object)button) && ((Behaviour)button).isActiveAndEnabled && ((Selectable)button).IsInteractable()
			select button).ToArray();
		if (array.Length != 0)
		{
			int num = Array.FindIndex(array, (Button button) => (Object)(object)((Component)button).gameObject == (Object)(object)events.currentSelectedGameObject);
			bool flag = ((ButtonControl)current.leftShiftKey).isPressed || ((ButtonControl)current.rightShiftKey).isPressed;
			int num2 = ((num >= 0) ? ((num + ((!flag) ? 1 : (-1)) + array.Length) % array.Length) : (flag ? (array.Length - 1) : 0));
			events.SetSelectedGameObject(((Component)array[num2]).gameObject);
		}
	}

	private static uint Hash(string key)
	{
		uint num = 2166136261u;
		foreach (char c in key)
		{
			num = (num ^ c) * 16777619;
		}
		return num;
	}

	internal static string[] Mix(string[] ordinary, string key, HashSet<string> reserved = null)
	{
		if (ordinary == null || ordinary.Length != 3 || ordinary.Any(string.IsNullOrEmpty) || ordinary.Any(RewardIntegration.IsCursed) || ordinary.Distinct().Count() != 3)
		{
			return ordinary;
		}
		if (Hash(key + "/chance") % 100 >= Plugin.Chance.Value)
		{
			return ordinary;
		}
		string[] array = Catalog.Ids.Where(delegate(string id)
		{
			if (Catalog.Available(id))
			{
				HashSet<string> hashSet = reserved;
				if (hashSet == null)
				{
					return true;
				}
				return !hashSet.Contains(id);
			}
			return false;
		}).ToArray();
		if (array.Length == 0)
		{
			return ordinary;
		}
		string[] obj = (string[])ordinary.Clone();
		obj[Hash(key + "/slot") % 3] = array[Hash(key + "/item") % array.Length];
		return obj;
	}

	internal static void Weekly(ref string[] __result)
	{
		__result = Mix(__result, GameDataManager.Instance.GetRunID() + "/weekly/" + DaytimeManager.Instance.CurrentDay());
	}

	internal static void Wager(object __0, ref string[] __result)
	{
		if (!Plugin.Paid.Value)
		{
			return;
		}
		Traverse val = Traverse.Create(__0);
		if (!(val.Property("Unclaimed", (object[])null).GetValue() is IEnumerable enumerable))
		{
			return;
		}
		HashSet<string> hashSet = new HashSet<string>();
		foreach (object item in enumerable)
		{
			string[] value = Traverse.Create(item).Property("Choices", (object[])null).GetValue<string[]>();
			if (value == null)
			{
				return;
			}
			hashSet.UnionWith(value);
		}
		string key = val.Property("Run", (object[])null).GetValue<string>() + "/wager/" + val.Property("Day", (object[])null).GetValue<int>();
		__result = Mix(__result, key, hashSet);
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(UIOverlayMerchant), "GenerateRelics")]
	private static IEnumerable<CodeInstruction> Cards(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Expected O, but got Unknown
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Expected O, but got Unknown
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		MethodInfo enumerator = AccessTools.Method(typeof(List<string>), "GetEnumerator", (Type[])null, (Type[])null);
		int num = list.FindIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, enumerator));
		if (num < 0 || list.Count((CodeInstruction c) => CodeInstructionExtensions.Calls(c, enumerator)) != 1)
		{
			throw new InvalidOperationException("Unknown reward renderer.");
		}
		list.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
		{
			CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Dup, (object)null), list[num]),
			new CodeInstruction(OpCodes.Ldarg_0, (object)null),
			new CodeInstruction(OpCodes.Ldarg_1, (object)null),
			CodeInstruction.Call(typeof(Rewards), "Prepare", (Type[])null, (Type[])null)
		});
		return list;
	}

	private static void Prepare(List<string> choices, UIOverlayMerchant picker, bool reroll)
	{
		if (!reroll || choices.Count != 3)
		{
			return;
		}
		object? obj = Generator.Invoke(picker)?.Target;
		DropBossChest val = (DropBossChest)((obj is DropBossChest) ? obj : null);
		if (val == null)
		{
			return;
		}
		Type kind = ((object)val).GetType();
		if ((kind != typeof(DropBossChest) && kind != typeof(DropKingdomChest) && kind != typeof(DropWorkerChest)) || !Guid.TryParse(GameDataManager.Instance.GetRunID(), out var run))
		{
			return;
		}
		Visit value = Visits.GetValue(val, delegate(DropBossChest c)
		{
			//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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)c).transform.position;
			string text3 = FormattableString.Invariant($"{run:N}/{DaytimeManager.Instance.CurrentDay()}/{kind.Name}");
			if (kind != typeof(DropBossChest))
			{
				text3 += FormattableString.Invariant($"/{position.x:R}/{position.y:R}");
			}
			Openings.TryGetValue(text3, out var value2);
			Openings[text3] = value2 + 1;
			if (value2 > 0)
			{
				text3 = text3 + "/" + value2.ToString(CultureInfo.InvariantCulture);
			}
			return new Visit
			{
				Key = text3
			};
		});
		string text = Path.Combine(Application.persistentDataPath, "CursedRelics", run.ToString("N"), Hash(value.Key).ToString("x8", CultureInfo.InvariantCulture) + ".json");
		List<string> pool = Pool.Invoke(val);
		string[] array = null;
		try
		{
			if (value.Roll == 0 && File.Exists(text))
			{
				Offer offer = JsonConvert.DeserializeObject<Offer>(File.ReadAllText(text));
				if (offer?.Key == value.Key && offer.Roll > 0 && Valid(offer.Choices, pool))
				{
					array = offer.Choices;
					value.Roll = offer.Roll;
				}
			}
			if (array == null)
			{
				array = Mix(choices.ToArray(), value.Key + "/" + value.Roll++);
				Directory.CreateDirectory(Path.GetDirectoryName(text));
				string text2 = text + "." + Guid.NewGuid().ToString("N") + ".tmp";
				File.WriteAllText(text2, JsonConvert.SerializeObject((object)new Offer
				{
					Key = value.Key,
					Roll = value.Roll,
					Choices = array
				}));
				if (File.Exists(text))
				{
					File.Replace(text2, text, null);
				}
				else
				{
					File.Move(text2, text);
				}
			}
		}
		catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is JsonException)
		{
			Plugin.Log.LogWarning((object)("Could not read or write the chest checkpoint: " + ex.Message));
		}
		if (array != null)
		{
			for (int num = 0; num < 3; num++)
			{
				choices[num] = array[num];
			}
		}
	}

	private static bool Valid(string[] row, List<string> pool)
	{
		if (row != null && row.Length == 3 && row.Distinct().Count() == 3 && row.Count(RewardIntegration.IsCursed) <= 1)
		{
			return row.All((string id) => !string.IsNullOrEmpty(id) && ((!RewardIntegration.IsCursed(id)) ? (pool.Contains(id) && RelicManager.Instance.IsUnlocked(id) && RelicManager.Instance.CanAddRelic(id)) : Catalog.Available(id)));
		}
		return false;
	}
}
[HarmonyPatch(typeof(WallManager), "WallGetsHit")]
internal static class WallHit
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Expected O, but got Unknown
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		FieldInfo hp = typeof(WallManager).GetField("m_Hitpoints", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new MissingFieldException(typeof(WallManager).FullName, "m_Hitpoints");
		List<CodeInstruction> list2 = list.FindAll((CodeInstruction i) => CodeInstructionExtensions.StoresField(i, hp));
		if (list2.Count != 1)
		{
			throw new InvalidOperationException("Expected one HP write in WallGetsHit. Bell hook unavailable.");
		}
		CodeInstruction val = list2[0];
		CodeInstruction val2 = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), val);
		list.InsertRange(list.IndexOf(val), (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			val2,
			new CodeInstruction(OpCodes.Call, (object)new Func<float, WallManager, float>(Observe).Method)
		});
		return list;
	}

	private static float Observe(float remaining, WallManager wall)
	{
		Night.Hit(wall.GetWallHitpoints(), remaining);
		return remaining;
	}
}