Decompiled source of EtchedRunes v1.0.7

Orgetorix.EtchedRunes.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("1.0.7")]
[assembly: AssemblyTitle("Orgetorix.EtchedRunes")]
[assembly: AssemblyDescription("Haldor etched runestones for Epic Loot / Valheim 1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Orgetorix")]
[assembly: AssemblyProduct("Orgetorix.EtchedRunes")]
[assembly: AssemblyCopyright("Copyright © Orgetorix")]
[assembly: ComVisible(false)]
[assembly: Guid("a1b2c3d4-e5f6-7890-abcd-ef1234567890")]
[assembly: AssemblyVersion("1.0.7.0")]
namespace Orgetorix.EtchedRunes
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Orgetorix.EtchedRunes", "Orgetorix Etched Runes", "1.0.7")]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class EtchedRunesPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "Orgetorix.EtchedRunes";

		public const string PluginName = "Orgetorix Etched Runes";

		public const string PluginVersion = "1.0.7";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("Orgetorix.EtchedRunes");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			PrefabManager.OnVanillaPrefabsAvailable += OnVanillaPrefabsAvailable;
			Log.LogInfo((object)"Orgetorix Etched Runes v1.0.7 loaded (Valheim 1.0 / Epic Loot 0.15).");
		}

		private void OnVanillaPrefabsAvailable()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= OnVanillaPrefabsAvailable;
			if (!ModConfig.Enabled.Value)
			{
				Log.LogInfo((object)"Mod disabled in config – skipping registration.");
				return;
			}
			RichesRuneManager.RegisterAll();
			LegendaryRuneManager.RegisterAll();
			Log.LogInfo((object)"Etched Runes registration finished.");
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}
	}
	public class RichesItemConfig
	{
		public string Label;

		public ConfigEntry<bool> Enabled;

		public ConfigEntry<string> Prefab;

		public ConfigEntry<string> Enchantment;

		public ConfigEntry<float> EnchantmentValue;

		public ConfigEntry<string> Rarity;

		public ConfigEntry<int> Price;

		public ConfigEntry<int> Stack;
	}
	public class LegendaryRuneDef
	{
		public string Key;

		public string PrefabName;

		public ConfigEntry<bool> Enabled;

		public ConfigEntry<string> DisplayName;

		public ConfigEntry<string> LegendaryID;

		public ConfigEntry<string> BasePrefab;

		public ConfigEntry<string> AllowedItemTypes;

		public ConfigEntry<string> AllowedSkillTypes;

		public ConfigEntry<bool> RequireNoParryPower;

		public ConfigEntry<int> Price;

		public ConfigEntry<int> Stack;

		public string SetFamily;
	}
	public static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<bool> SellRichesAtHaldor;

		public static ConfigEntry<bool> SellSetRunesAtHaldor;

		public static readonly List<RichesItemConfig> RichesItems = new List<RichesItemConfig>();

		public static readonly List<LegendaryRuneDef> LegendaryRunes = new List<LegendaryRuneDef>();

		public static void Bind(ConfigFile cfg)
		{
			Enabled = cfg.Bind<bool>("0 - General", "Enabled", true, "Master switch for Orgetorix Etched Runes.");
			SellRichesAtHaldor = cfg.Bind<bool>("0 - General", "SellRichesAtHaldor", true, "Offer pre-etched Riches / utility runestones in Haldor's shop.");
			SellSetRunesAtHaldor = cfg.Bind<bool>("0 - General", "SellSetRunesAtHaldor", true, "Offer legendary set identity runes in Haldor's shop.");
			BindRiches(cfg);
			BindLegendary(cfg);
		}

		public static bool IsRichesEnabled(RichesItemConfig cfg)
		{
			if (Enabled.Value && cfg != null && cfg.Enabled != null)
			{
				return cfg.Enabled.Value;
			}
			return false;
		}

		public static bool IsLegendaryEnabled(LegendaryRuneDef def)
		{
			if (Enabled.Value && def != null && def.Enabled != null)
			{
				return def.Enabled.Value;
			}
			return false;
		}

		private static void BindRiches(ConfigFile cfg)
		{
			AddRiches(cfg, "Magic", "EtchedRunestoneMagic", "Riches", 2f, "Magic", 350, 1);
			AddRiches(cfg, "Rare", "EtchedRunestoneRare", "Riches", 8f, "Rare", 700, 1);
			AddRiches(cfg, "Epic", "EtchedRunestoneEpic", "Riches", 14f, "Epic", 1400, 1);
			AddRiches(cfg, "Legendary", "EtchedRunestoneLegendary", "Riches", 20f, "Legendary", 2400, 1);
			AddRiches(cfg, "Mythic", "EtchedRunestoneMythic", "Riches", 25f, "Mythic", 4000, 1);
			AddRiches(cfg, "FeatherFall_Epic", "EtchedRunestoneEpic", "Feather Fall", 1f, "Epic", 1800, 1);
			AddRiches(cfg, "AirJump_Epic", "EtchedRunestoneEpic", "Air Jump", 1f, "Epic", 2200, 1);
		}

		private static void AddRiches(ConfigFile cfg, string label, string prefab, string enchant, float value, string rarity, int price, int stack)
		{
			string text = "1 - Riches / " + label;
			RichesItemConfig richesItemConfig = new RichesItemConfig();
			richesItemConfig.Label = label;
			richesItemConfig.Enabled = cfg.Bind<bool>(text, "Enabled", true, "Sell this etched runestone at Haldor.");
			richesItemConfig.Prefab = cfg.Bind<string>(text, "Prefab", prefab, "Base Epic Loot etched-runestone prefab to clone.");
			richesItemConfig.Enchantment = cfg.Bind<string>(text, "Enchantment", enchant, "Epic Loot effect type (Riches, Feather Fall, Air Jump, …).");
			richesItemConfig.EnchantmentValue = cfg.Bind<float>(text, "EnchantmentValue", value, "Fixed effect value. Riches is percent gold-on-kill.");
			richesItemConfig.Rarity = cfg.Bind<string>(text, "Rarity", rarity, "Displayed / stored rarity: Magic, Rare, Epic, Legendary, Mythic.");
			richesItemConfig.Price = cfg.Bind<int>(text, "Price", price, "Haldor coin price.");
			richesItemConfig.Stack = cfg.Bind<int>(text, "Stack", stack, "Stack size offered per purchase.");
			RichesItems.Add(richesItemConfig);
		}

		private static void BindLegendary(ConfigFile cfg)
		{
			AddSet(cfg, "Heimdall_TowerShield", "Orgetorix_LegRune_Heimdall_TowerShield", "Etched Rune: Heimdall Tower Shield", "HeimdallTowerShield", "Shield", "", requireNoParry: true, 3000, "Heimdall");
			AddSet(cfg, "Heimdall_Helmet", "Orgetorix_LegRune_Heimdall_Helmet", "Etched Rune: Heimdall Helmet", "HeimdallHelmet", "Helmet", "", requireNoParry: false, 3000, "Heimdall");
			AddSet(cfg, "Heimdall_Chest", "Orgetorix_LegRune_Heimdall_Chest", "Etched Rune: Heimdall Chest", "HeimdallChest", "Chest", "", requireNoParry: false, 3000, "Heimdall");
			AddSet(cfg, "Heimdall_Legs", "Orgetorix_LegRune_Heimdall_Legs", "Etched Rune: Heimdall Legs", "HeimdallLegs", "Legs", "", requireNoParry: false, 3000, "Heimdall");
			AddSet(cfg, "Ragnar_BattleAxe", "Orgetorix_LegRune_Ragnar_BattleAxe", "Etched Rune: Ragnar Battleaxe", "RagnarBattleAxe", "TwoHandedWeapon", "Axes", requireNoParry: false, 3000, "Ragnar");
			AddSet(cfg, "Ragnar_Cape", "Orgetorix_LegRune_Ragnar_Cape", "Etched Rune: Ragnar Cape", "RagnarCape", "Shoulder", "", requireNoParry: false, 3000, "Ragnar");
			AddSet(cfg, "Ragnar_Chest", "Orgetorix_LegRune_Ragnar_Chest", "Etched Rune: Ragnar Chest", "RagnarChest", "Chest", "", requireNoParry: false, 3000, "Ragnar");
			AddSet(cfg, "Ragnar_Legs", "Orgetorix_LegRune_Ragnar_Legs", "Etched Rune: Ragnar Legs", "RagnarLegs", "Legs", "", requireNoParry: false, 3000, "Ragnar");
			AddSet(cfg, "Thor_Maul", "Orgetorix_LegRune_Thor_Maul", "Etched Rune: Thor Maul", "ThorMaul", "TwoHandedWeapon", "Clubs", requireNoParry: false, 3200, "Thor");
			AddSet(cfg, "Thor_Helm", "Orgetorix_LegRune_Thor_Helm", "Etched Rune: Thor Helm", "ThorHelm", "Helmet", "", requireNoParry: false, 3200, "Thor");
			AddSet(cfg, "Thor_Chest", "Orgetorix_LegRune_Thor_Chest", "Etched Rune: Thor Chest", "ThorChest", "Chest", "", requireNoParry: false, 3200, "Thor");
			AddSet(cfg, "Thor_Legs", "Orgetorix_LegRune_Thor_Legs", "Etched Rune: Thor Legs", "ThorLegs", "Legs", "", requireNoParry: false, 3200, "Thor");
			AddSet(cfg, "Dverger_Crossbow", "Orgetorix_LegRune_Dverger_Crossbow", "Etched Rune: Dverger Arsenal Crossbow", "DvergerArsenalCrossbow", "Bow", "Crossbows", requireNoParry: false, 3200, "DvergerArsenal");
			AddSet(cfg, "Dverger_Helm", "Orgetorix_LegRune_Dverger_Helm", "Etched Rune: Dverger Arsenal Helm", "DvergerArsenalHelm", "Helmet", "", requireNoParry: false, 3200, "DvergerArsenal");
			AddSet(cfg, "Dverger_Cloak", "Orgetorix_LegRune_Dverger_Cloak", "Etched Rune: Dverger Arsenal Cloak", "DvergerArsenalCloak", "Shoulder", "", requireNoParry: false, 3200, "DvergerArsenal");
			AddSet(cfg, "Dverger_Chest", "Orgetorix_LegRune_Dverger_Chest", "Etched Rune: Dverger Arsenal Chest", "DvergerArsenalChest", "Chest", "", requireNoParry: false, 3200, "DvergerArsenal");
			AddSet(cfg, "Loki_Knife", "Orgetorix_LegRune_Loki_Knife", "Etched Rune: Loki Knife", "LokiKnife", "OneHandedWeapon", "Knives", requireNoParry: false, 3200, "Loki");
			AddSet(cfg, "Loki_Hood", "Orgetorix_LegRune_Loki_Hood", "Etched Rune: Loki Hood", "LokiHood", "Helmet", "", requireNoParry: false, 3200, "Loki");
			AddSet(cfg, "Loki_Chest", "Orgetorix_LegRune_Loki_Chest", "Etched Rune: Loki Chest", "LokiChest", "Chest", "", requireNoParry: false, 3200, "Loki");
			AddSet(cfg, "Loki_Legs", "Orgetorix_LegRune_Loki_Legs", "Etched Rune: Loki Legs", "LokiLegs", "Legs", "", requireNoParry: false, 3200, "Loki");
			AddSet(cfg, "Egil_Bow", "Orgetorix_LegRune_Egil_Bow", "Etched Rune: Egil Bow", "EgilBow", "Bow", "Bows", requireNoParry: false, 3200, "Egil");
			AddSet(cfg, "Egil_Hood", "Orgetorix_LegRune_Egil_Hood", "Etched Rune: Egil Hood", "EgilHood", "Helmet", "", requireNoParry: false, 3200, "Egil");
			AddSet(cfg, "Egil_Cloak", "Orgetorix_LegRune_Egil_Cloak", "Etched Rune: Egil Cloak", "EgilCloak", "Shoulder", "", requireNoParry: false, 3200, "Egil");
			AddSet(cfg, "Egil_Legs", "Orgetorix_LegRune_Egil_Legs", "Etched Rune: Egil Legs", "EgilLegs", "Legs", "", requireNoParry: false, 3200, "Egil");
			AddSet(cfg, "Elivagar_Hood", "Orgetorix_LegRune_Elivagar_Hood", "Etched Rune: Elivagar Hood", "ElivagarHood", "Helmet", "", requireNoParry: false, 3200, "Elivagar");
			AddSet(cfg, "Elivagar_Robe", "Orgetorix_LegRune_Elivagar_Robe", "Etched Rune: Elivagar Robe", "ElivagarRobe", "Chest", "", requireNoParry: false, 3200, "Elivagar");
			AddSet(cfg, "Elivagar_Legs", "Orgetorix_LegRune_Elivagar_Legs", "Etched Rune: Elivagar Legs", "ElivagarLegs", "Legs", "", requireNoParry: false, 3200, "Elivagar");
			AddSet(cfg, "Elivagar_Cape", "Orgetorix_LegRune_Elivagar_Cape", "Etched Rune: Elivagar Cape", "ElivagarCape", "Shoulder", "", requireNoParry: false, 3200, "Elivagar");
			AddSet(cfg, "Fylgja_Bow", "Orgetorix_LegRune_Fylgja_Bow", "Etched Rune: Fylgja Bow", "FylgjaBow", "Bow", "Bows", requireNoParry: false, 3200, "Fylgja");
			AddSet(cfg, "Fylgja_Weapon", "Orgetorix_LegRune_Fylgja_Weapon", "Etched Rune: Fylgja Weapon", "FylgjaWeapon", "", "Swords,Knives,Axes,Clubs,Spears,Polearms,Sledges,TwoHandAxes,Fists", requireNoParry: false, 3200, "Fylgja");
			AddSet(cfg, "Fylgja_Hood", "Orgetorix_LegRune_Fylgja_Hood", "Etched Rune: Fylgja Hood", "FylgjaHood", "Helmet", "", requireNoParry: false, 3200, "Fylgja");
			AddSet(cfg, "Fylgja_Jerkin", "Orgetorix_LegRune_Fylgja_Jerkin", "Etched Rune: Fylgja Jerkin", "FylgjaJerkin", "Chest", "", requireNoParry: false, 3200, "Fylgja");
			AddSet(cfg, "Fylgja_Cape", "Orgetorix_LegRune_Fylgja_Cape", "Etched Rune: Fylgja Cape", "FylgjaCape", "Shoulder", "", requireNoParry: false, 3200, "Fylgja");
			AddSet(cfg, "Freyja_Spear", "Orgetorix_LegRune_Freyja_Spear", "Etched Rune: Freyja Spear", "FreyjaSpear", "", "Spears", requireNoParry: false, 3200, "Freyja");
			AddSet(cfg, "Freyja_Helm", "Orgetorix_LegRune_Freyja_Helm", "Etched Rune: Freyja Helm", "FreyjaHelm", "Helmet", "", requireNoParry: false, 3200, "Freyja");
			AddSet(cfg, "Freyja_Chest", "Orgetorix_LegRune_Freyja_Chest", "Etched Rune: Freyja Chest", "FreyjaChest", "Chest", "", requireNoParry: false, 3200, "Freyja");
			AddSet(cfg, "Freyja_Cloak", "Orgetorix_LegRune_Freyja_Cloak", "Etched Rune: Freyja Cloak", "FreyjaCloak", "Shoulder", "", requireNoParry: false, 3200, "Freyja");
			AddSet(cfg, "Bolthorn_Crossbow", "Orgetorix_LegRune_Bolthorn_Crossbow", "Etched Rune: Bolthorn Crossbow", "BolthornCrossbow", "Bow", "Crossbows", requireNoParry: false, 3200, "Bolthorn");
			AddSet(cfg, "Bolthorn_Helm", "Orgetorix_LegRune_Bolthorn_Helm", "Etched Rune: Bolthorn Helm", "BolthornHelm", "Helmet", "", requireNoParry: false, 3200, "Bolthorn");
			AddSet(cfg, "Bolthorn_Chest", "Orgetorix_LegRune_Bolthorn_Chest", "Etched Rune: Bolthorn Chest", "BolthornChest", "Chest", "", requireNoParry: false, 3200, "Bolthorn");
			AddSet(cfg, "Bolthorn_Legs", "Orgetorix_LegRune_Bolthorn_Legs", "Etched Rune: Bolthorn Legs", "BolthornLegs", "Legs", "", requireNoParry: false, 3200, "Bolthorn");
			AddSet(cfg, "Heidr_Bow", "Orgetorix_LegRune_Heidr_Bow", "Etched Rune: Heidr Bow", "HeidrBow", "Bow", "Bows", requireNoParry: false, 3200, "Heidr");
			AddSet(cfg, "Heidr_Hood", "Orgetorix_LegRune_Heidr_Hood", "Etched Rune: Heidr Hood", "HeidrHood", "Helmet", "", requireNoParry: false, 3200, "Heidr");
			AddSet(cfg, "Heidr_Robe", "Orgetorix_LegRune_Heidr_Robe", "Etched Rune: Heidr Robe", "HeidrRobe", "Chest", "", requireNoParry: false, 3200, "Heidr");
			AddSet(cfg, "Heidr_Mantle", "Orgetorix_LegRune_Heidr_Mantle", "Etched Rune: Heidr Mantle", "HeidrMantle", "Shoulder", "", requireNoParry: false, 3200, "Heidr");
			AddSet(cfg, "Mimir_Hood", "Orgetorix_LegRune_Mimir_Hood", "Etched Rune: Mimir Hood", "MimirHood", "Helmet", "", requireNoParry: false, 3200, "Mimir");
			AddSet(cfg, "Mimir_Robe", "Orgetorix_LegRune_Mimir_Robe", "Etched Rune: Mimir Robe", "MimirRobe", "Chest", "", requireNoParry: false, 3200, "Mimir");
			AddSet(cfg, "Mimir_Legs", "Orgetorix_LegRune_Mimir_Legs", "Etched Rune: Mimir Legs", "MimirLegs", "Legs", "", requireNoParry: false, 3200, "Mimir");
			AddSet(cfg, "Mimir_Cape", "Orgetorix_LegRune_Mimir_Cape", "Etched Rune: Mimir Cape", "MimirCape", "Shoulder", "", requireNoParry: false, 3200, "Mimir");
			AddSet(cfg, "Einherjar_Sword", "Orgetorix_LegRune_Einherjar_Sword", "Etched Rune: Einherjar Sword", "EinherjarSword", "OneHandedWeapon,TwoHandedWeapon", "Swords", requireNoParry: false, 3200, "Einherjar");
			AddSet(cfg, "Einherjar_Helm", "Orgetorix_LegRune_Einherjar_Helm", "Etched Rune: Einherjar Helm", "EinherjarHelm", "Helmet", "", requireNoParry: false, 3200, "Einherjar");
			AddSet(cfg, "Einherjar_Chest", "Orgetorix_LegRune_Einherjar_Chest", "Etched Rune: Einherjar Chest", "EinherjarChest", "Chest", "", requireNoParry: false, 3200, "Einherjar");
			AddSet(cfg, "Einherjar_Legs", "Orgetorix_LegRune_Einherjar_Legs", "Etched Rune: Einherjar Legs", "EinherjarLegs", "Legs", "", requireNoParry: false, 3200, "Einherjar");
			AddSet(cfg, "Ullr_HuntBow", "Orgetorix_LegRune_Ullr_HuntBow", "Etched Rune: Ullr Hunt Bow", "UllrHuntBow", "Bow", "Bows", requireNoParry: false, 3200, "Ullr");
			AddSet(cfg, "Ullr_Hood", "Orgetorix_LegRune_Ullr_Hood", "Etched Rune: Ullr Hood", "UllrHood", "Helmet", "", requireNoParry: false, 3200, "Ullr");
			AddSet(cfg, "Ullr_Chest", "Orgetorix_LegRune_Ullr_Chest", "Etched Rune: Ullr Chest", "UllrChest", "Chest", "", requireNoParry: false, 3200, "Ullr");
			AddSet(cfg, "Ullr_Legs", "Orgetorix_LegRune_Ullr_Legs", "Etched Rune: Ullr Legs", "UllrLegs", "Legs", "", requireNoParry: false, 3200, "Ullr");
			AddSet(cfg, "Hel_Staff", "Orgetorix_LegRune_Hel_Staff", "Etched Rune: Hel Staff", "HelStaff", "Staff", "BloodMagic", requireNoParry: false, 3200, "Hel");
			AddSet(cfg, "Hel_Hood", "Orgetorix_LegRune_Hel_Hood", "Etched Rune: Hel Hood", "HelHood", "Helmet", "", requireNoParry: false, 3200, "Hel");
			AddSet(cfg, "Hel_Robe", "Orgetorix_LegRune_Hel_Robe", "Etched Rune: Hel Robe", "HelRobe", "Chest", "", requireNoParry: false, 3200, "Hel");
			AddSet(cfg, "Hel_Mantle", "Orgetorix_LegRune_Hel_Mantle", "Etched Rune: Hel Mantle", "HelMantle", "Shoulder", "", requireNoParry: false, 3200, "Hel");
			AddSet(cfg, "Huldra_Knife", "Orgetorix_LegRune_Huldra_Knife", "Etched Rune: Huldra Knife", "HuldraKnife", "OneHandedWeapon", "Knives", requireNoParry: false, 3200, "Huldra");
			AddSet(cfg, "Huldra_Hood", "Orgetorix_LegRune_Huldra_Hood", "Etched Rune: Huldra Hood", "HuldraHood", "Helmet", "", requireNoParry: false, 3200, "Huldra");
			AddSet(cfg, "Huldra_Chest", "Orgetorix_LegRune_Huldra_Chest", "Etched Rune: Huldra Chest", "HuldraChest", "Chest", "", requireNoParry: false, 3200, "Huldra");
			AddSet(cfg, "Huldra_Cape", "Orgetorix_LegRune_Huldra_Cape", "Etched Rune: Huldra Cape", "HuldraCape", "Shoulder", "", requireNoParry: false, 3200, "Huldra");
			AddSet(cfg, "Surtr_Weapon", "Orgetorix_LegRune_Surtr_Weapon", "Etched Rune: Surtr Weapon", "SurtrWeapon", "TwoHandedWeapon", "Axes,Swords", requireNoParry: false, 3200, "Surtr");
			AddSet(cfg, "Surtr_Helm", "Orgetorix_LegRune_Surtr_Helm", "Etched Rune: Surtr Helm", "SurtrHelm", "Helmet", "", requireNoParry: false, 3200, "Surtr");
			AddSet(cfg, "Surtr_Chest", "Orgetorix_LegRune_Surtr_Chest", "Etched Rune: Surtr Chest", "SurtrChest", "Chest", "", requireNoParry: false, 3200, "Surtr");
			AddSet(cfg, "Surtr_Legs", "Orgetorix_LegRune_Surtr_Legs", "Etched Rune: Surtr Legs", "SurtrLegs", "Legs", "", requireNoParry: false, 3200, "Surtr");
			AddSet(cfg, "HelCourt_Helm", "Orgetorix_LegRune_HelCourt_Helm", "Etched Rune: Hel Court Helm", "HelCourtHelm", "Helmet", "", requireNoParry: false, 3200, "HelCourt");
			AddSet(cfg, "HelCourt_Chest", "Orgetorix_LegRune_HelCourt_Chest", "Etched Rune: Hel Court Chest", "HelCourtChest", "Chest", "", requireNoParry: false, 3200, "HelCourt");
			AddSet(cfg, "HelCourt_Legs", "Orgetorix_LegRune_HelCourt_Legs", "Etched Rune: Hel Court Legs", "HelCourtLegs", "Legs", "", requireNoParry: false, 3200, "HelCourt");
			AddSet(cfg, "HelCourt_Cape", "Orgetorix_LegRune_HelCourt_Cape", "Etched Rune: Hel Court Cape", "HelCourtCape", "Shoulder", "", requireNoParry: false, 3200, "HelCourt");
			AddSet(cfg, "Hrungnir_Shield", "Orgetorix_LegRune_Hrungnir_Shield", "Etched Rune: Hrungnir Shield", "HrungnirShield", "Shield", "", requireNoParry: true, 3200, "Hrungnir");
			AddSet(cfg, "Hrungnir_Helm", "Orgetorix_LegRune_Hrungnir_Helm", "Etched Rune: Hrungnir Helm", "HrungnirHelm", "Helmet", "", requireNoParry: false, 3200, "Hrungnir");
			AddSet(cfg, "Hrungnir_Chest", "Orgetorix_LegRune_Hrungnir_Chest", "Etched Rune: Hrungnir Chest", "HrungnirChest", "Chest", "", requireNoParry: false, 3200, "Hrungnir");
			AddSet(cfg, "Hrungnir_Legs", "Orgetorix_LegRune_Hrungnir_Legs", "Etched Rune: Hrungnir Legs", "HrungnirLegs", "Legs", "", requireNoParry: false, 3200, "Hrungnir");
			AddSet(cfg, "Svalinn_Shield", "Orgetorix_LegRune_Svalinn_Shield", "Etched Rune: Svalinn Shield", "SvalinnShield", "Shield", "", requireNoParry: false, 3200, "Svalinn");
			AddSet(cfg, "Svalinn_Helm", "Orgetorix_LegRune_Svalinn_Helm", "Etched Rune: Svalinn Helm", "SvalinnHelm", "Helmet", "", requireNoParry: false, 3200, "Svalinn");
			AddSet(cfg, "Svalinn_Chest", "Orgetorix_LegRune_Svalinn_Chest", "Etched Rune: Svalinn Chest", "SvalinnChest", "Chest", "", requireNoParry: false, 3200, "Svalinn");
			AddSet(cfg, "Svalinn_Legs", "Orgetorix_LegRune_Svalinn_Legs", "Etched Rune: Svalinn Legs", "SvalinnLegs", "Legs", "", requireNoParry: false, 3200, "Svalinn");
			AddSet(cfg, "Jormungandr_Spear", "Orgetorix_LegRune_Jormungandr_Spear", "Etched Rune: Jormungandr Spear", "JormungandrSpear", "OneHandedWeapon", "Spears", requireNoParry: false, 3200, "Jormungandr");
			AddSet(cfg, "Jormungandr_Helm", "Orgetorix_LegRune_Jormungandr_Helm", "Etched Rune: Jormungandr Helm", "JormungandrHelm", "Helmet", "", requireNoParry: false, 3200, "Jormungandr");
			AddSet(cfg, "Jormungandr_Chest", "Orgetorix_LegRune_Jormungandr_Chest", "Etched Rune: Jormungandr Chest", "JormungandrChest", "Chest", "", requireNoParry: false, 3200, "Jormungandr");
			AddSet(cfg, "Jormungandr_Legs", "Orgetorix_LegRune_Jormungandr_Legs", "Etched Rune: Jormungandr Legs", "JormungandrLegs", "Legs", "", requireNoParry: false, 3200, "Jormungandr");
			AddSet(cfg, "Gullveig_Staff", "Orgetorix_LegRune_Gullveig_Staff", "Etched Rune: Gullveig Staff", "GullveigStaff", "Staff", "ElementalMagic", requireNoParry: false, 3200, "Gullveig");
			AddSet(cfg, "Gullveig_Hood", "Orgetorix_LegRune_Gullveig_Hood", "Etched Rune: Gullveig Hood", "GullveigHood", "Helmet", "", requireNoParry: false, 3200, "Gullveig");
			AddSet(cfg, "Gullveig_Robe", "Orgetorix_LegRune_Gullveig_Robe", "Etched Rune: Gullveig Robe", "GullveigRobe", "Chest", "", requireNoParry: false, 3200, "Gullveig");
			AddSet(cfg, "Gullveig_Cape", "Orgetorix_LegRune_Gullveig_Cape", "Etched Rune: Gullveig Cape", "GullveigCape", "Shoulder", "", requireNoParry: false, 3200, "Gullveig");
			AddSet(cfg, "GiantsBlood_TwoHanded", "Orgetorix_LegRune_GiantsBlood_TwoHanded", "Etched Rune: Giants Blood Weapon", "GiantsBloodTwoHandedWeapon", "TwoHandedWeapon", "Axes,Clubs,Swords,Polearms", requireNoParry: false, 3200, "GiantsBlood");
			AddSet(cfg, "GiantsBlood_Helm", "Orgetorix_LegRune_GiantsBlood_Helm", "Etched Rune: Giants Blood Helm", "GiantsBloodHelm", "Helmet", "", requireNoParry: false, 3200, "GiantsBlood");
			AddSet(cfg, "GiantsBlood_Chest", "Orgetorix_LegRune_GiantsBlood_Chest", "Etched Rune: Giants Blood Chest", "GiantsBloodChest", "Chest", "", requireNoParry: false, 3200, "GiantsBlood");
			AddSet(cfg, "GiantsBlood_Legs", "Orgetorix_LegRune_GiantsBlood_Legs", "Etched Rune: Giants Blood Legs", "GiantsBloodLegs", "Legs", "", requireNoParry: false, 3200, "GiantsBlood");
		}

		private static void AddSet(ConfigFile cfg, string key, string prefabName, string displayName, string legendaryId, string itemTypes, string skillTypes, bool requireNoParry, int price, string family)
		{
			string text = "2 - Set Runes / " + key;
			LegendaryRuneDef legendaryRuneDef = new LegendaryRuneDef();
			legendaryRuneDef.Key = key;
			legendaryRuneDef.PrefabName = prefabName;
			legendaryRuneDef.SetFamily = family;
			legendaryRuneDef.Enabled = cfg.Bind<bool>(text, "Enabled", true, "Register this set rune.");
			legendaryRuneDef.DisplayName = cfg.Bind<string>(text, "DisplayName", displayName, "Inventory name.");
			legendaryRuneDef.LegendaryID = cfg.Bind<string>(text, "LegendaryID", legendaryId, "Epic Loot legendary / set piece id.");
			legendaryRuneDef.BasePrefab = cfg.Bind<string>(text, "BasePrefab", "EtchedRunestoneLegendary", "Visual/base prefab.");
			legendaryRuneDef.AllowedItemTypes = cfg.Bind<string>(text, "AllowedItemTypes", itemTypes, "Comma-separated ItemDrop.ItemData.ItemType values.");
			legendaryRuneDef.AllowedSkillTypes = cfg.Bind<string>(text, "AllowedSkillTypes", skillTypes, "Optional comma-separated Skills.SkillType filter.");
			legendaryRuneDef.RequireNoParryPower = cfg.Bind<bool>(text, "RequireNoParryPower", requireNoParry, "If true, refuse bucklers (timed-block bonus).");
			legendaryRuneDef.Price = cfg.Bind<int>(text, "Price", price, "Haldor coin price.");
			legendaryRuneDef.Stack = cfg.Bind<int>(text, "Stack", 1, "Stack size offered per purchase.");
			LegendaryRunes.Add(legendaryRuneDef);
		}
	}
	public static class RichesRuneManager
	{
		public static readonly Dictionary<string, RichesItemConfig> Registered = new Dictionary<string, RichesItemConfig>();

		private static ManualLogSource Logger => EtchedRunesPlugin.Log;

		public static void RegisterAll()
		{
			int num = 0;
			foreach (RichesItemConfig richesItem in ModConfig.RichesItems)
			{
				if (ModConfig.IsRichesEnabled(richesItem))
				{
					num++;
					try
					{
						RegisterOne(richesItem, num);
					}
					catch (Exception ex)
					{
						Logger.LogError((object)("Riches rune register failed (" + richesItem.Label + "): " + ex));
					}
				}
			}
		}

		private static void RegisterOne(RichesItemConfig cfg, int index)
		{
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			string text = cfg.Prefab.Value;
			GameObject prefab = PrefabManager.Instance.GetPrefab(text);
			if ((Object)(object)prefab == (Object)null)
			{
				string[] array = new string[5] { "EtchedRunestoneMagic", "EtchedRunestoneRare", "EtchedRunestoneEpic", "EtchedRunestoneLegendary", "EtchedRunestoneMythic" };
				for (int i = 0; i < array.Length; i++)
				{
					prefab = PrefabManager.Instance.GetPrefab(array[i]);
					if ((Object)(object)prefab != (Object)null)
					{
						Logger.LogWarning((object)("Riches base prefab '" + text + "' missing, fallback: " + array[i]));
						text = array[i];
						break;
					}
				}
			}
			if ((Object)(object)prefab == (Object)null)
			{
				Logger.LogError((object)("No base prefab for Riches item " + cfg.Label + " – skipped."));
				return;
			}
			string text2 = text + "_Orge_" + index;
			string text3 = DisplayEffectName(cfg.Enchantment.Value);
			ItemConfig val = new ItemConfig();
			val.Description = "Pre-etched: " + text3 + (IsNumericEffect(cfg.Enchantment.Value) ? (" " + cfg.EnchantmentValue.Value) : "") + " [" + cfg.Rarity.Value + "]. Use at the Enchanting Table.";
			CustomItem val2 = new CustomItem(text2, text, val);
			ItemManager.Instance.AddItem(val2);
			Registered[text2] = cfg;
			Logger.LogInfo((object)("Registered etched runestone: " + text2 + " -> " + text3 + " " + cfg.EnchantmentValue.Value));
			GameObject prefab2 = PrefabManager.Instance.GetPrefab(text2);
			if ((Object)(object)prefab2 != (Object)null)
			{
				ItemDrop component = prefab2.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null && component.m_itemData != null)
				{
					component.m_itemData.m_dropPrefab = prefab2;
					ApplyEtchedMagic(component.m_itemData, cfg);
				}
			}
		}

		public static void TryApplyMagicData(ItemData item)
		{
			if (item == null)
			{
				return;
			}
			if (ShouldStripIllegalMagic(item))
			{
				StripMagic(item);
			}
			else if (IsOurShopRune(item))
			{
				RichesItemConfig richesItemConfig = FindConfig(item);
				if (richesItemConfig != null && !AlreadyHasEtchedEffect(item, richesItemConfig))
				{
					ApplyEtchedMagic(item, richesItemConfig);
				}
			}
		}

		public static bool IsOurShopRune(ItemData item)
		{
			string prefabName = GetPrefabName(item);
			if (string.IsNullOrEmpty(prefabName))
			{
				return false;
			}
			if (prefabName.IndexOf("_Orge_", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return false;
			}
			return Registered.ContainsKey(prefabName);
		}

		private static string GetPrefabName(ItemData item)
		{
			if (item == null)
			{
				return null;
			}
			string text = null;
			if ((Object)(object)item.m_dropPrefab != (Object)null)
			{
				text = ((Object)item.m_dropPrefab).name;
			}
			if (string.IsNullOrEmpty(text) && item.m_shared != null)
			{
				text = item.m_shared.m_name;
			}
			if (string.IsNullOrEmpty(text))
			{
				return null;
			}
			return text.Replace("(Clone)", "").Trim();
		}

		private static bool ShouldStripIllegalMagic(ItemData item)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Invalid comparison between Unknown and I4
			string prefabName = GetPrefabName(item);
			if (string.IsNullOrEmpty(prefabName))
			{
				return false;
			}
			if (prefabName.IndexOf("_Orge_", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			if (prefabName.IndexOf("Orgetorix_LegRune", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			if (prefabName.IndexOf("Runestone", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			if (prefabName.IndexOf("EtchedRune", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return false;
			}
			bool flag = prefabName.Equals("Stone", StringComparison.OrdinalIgnoreCase) || prefabName.Equals("$item_stone", StringComparison.OrdinalIgnoreCase);
			bool flag2 = item.m_shared != null && (int)item.m_shared.m_itemType == 1;
			if (!flag && !flag2)
			{
				return false;
			}
			return ItemLooksMagic(item);
		}

		private static bool ItemLooksMagic(ItemData item)
		{
			try
			{
				Type type = FindType("EpicLoot.API");
				if (type == null)
				{
					return false;
				}
				MethodInfo methodInfo = type.GetMethod("IsMagicItem", BindingFlags.Static | BindingFlags.Public) ?? type.GetMethod("IsEpicLootItem", BindingFlags.Static | BindingFlags.Public);
				if (methodInfo != null)
				{
					object obj = methodInfo.Invoke(null, new object[1] { item });
					if (obj is bool && (bool)obj)
					{
						return true;
					}
				}
				MethodInfo method = type.GetMethod("GetMagicItemJson", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					string text = method.Invoke(null, new object[1] { item }) as string;
					if (!string.IsNullOrEmpty(text) && text.IndexOf("EffectType", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static void StripMagic(ItemData item)
		{
			try
			{
				Type type = FindType("EpicLoot.ItemDataExtensions");
				if (type != null)
				{
					string[] array = new string[4] { "RemoveMagicItem", "ClearMagicItem", "DeleteMagicItem", "MakeNonMagic" };
					for (int i = 0; i < array.Length; i++)
					{
						MethodInfo method = type.GetMethod(array[i], BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						if (!(method == null))
						{
							try
							{
								method.Invoke(null, new object[1] { item });
								Logger.LogInfo((object)("Stripped illegal magic via " + array[i] + " from " + GetPrefabName(item)));
								return;
							}
							catch
							{
							}
						}
					}
					MethodInfo method2 = type.GetMethod("SaveMagicItem", BindingFlags.Static | BindingFlags.Public);
					if (method2 != null)
					{
						try
						{
							method2.Invoke(null, new object[2] { item, null });
							Logger.LogInfo((object)("Stripped illegal magic via SaveMagicItem(null) from " + GetPrefabName(item)));
							return;
						}
						catch
						{
						}
					}
				}
				Type type2 = FindType("EpicLoot.API");
				if (type2 != null)
				{
					MethodInfo method3 = type2.GetMethod("ApplyMagicItemJson", BindingFlags.Static | BindingFlags.Public);
					if (method3 != null)
					{
						method3.Invoke(null, new object[2] { item, "" });
						Logger.LogInfo((object)("Stripped illegal magic via empty JSON from " + GetPrefabName(item)));
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("StripMagic failed: " + ex.Message));
			}
		}

		private static bool AlreadyHasEtchedEffect(ItemData item, RichesItemConfig cfg)
		{
			string text = ResolveEffectType(cfg.Enchantment.Value);
			try
			{
				Type type = FindType("EpicLoot.API");
				if (type == null)
				{
					return false;
				}
				MethodInfo method = type.GetMethod("ItemHasMagicEffect", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					object obj = method.Invoke(null, new object[3] { item, text, true });
					if (obj is bool && (bool)obj)
					{
						return true;
					}
				}
				MethodInfo method2 = type.GetMethod("GetMagicItemJson", BindingFlags.Static | BindingFlags.Public);
				if (method2 != null)
				{
					string text2 = method2.Invoke(null, new object[1] { item }) as string;
					if (!string.IsNullOrEmpty(text2) && text2.IndexOf("\"EffectType\":\"" + text + "\"") >= 0)
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static RichesItemConfig FindConfig(ItemData item)
		{
			string[] array = new string[2];
			if ((Object)(object)item.m_dropPrefab != (Object)null)
			{
				array[0] = ((Object)item.m_dropPrefab).name;
			}
			if (item.m_shared != null)
			{
				array[1] = item.m_shared.m_name;
			}
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i];
				if (!string.IsNullOrEmpty(text))
				{
					text = text.Replace("(Clone)", "").Trim();
					if (Registered.TryGetValue(text, out var value))
					{
						return value;
					}
				}
			}
			return null;
		}

		private static void ApplyEtchedMagic(ItemData item, RichesItemConfig cfg)
		{
			try
			{
				string text = ResolveEffectType(cfg.Enchantment.Value);
				float value = cfg.EnchantmentValue.Value;
				string value2 = cfg.Rarity.Value;
				if (!TryApplyViaApiJson(item, text, value, value2) && !TryApplyMagicToItemData(item, text, value, value2) && !TrySaveMagicItem(item, text, value, value2))
				{
					Logger.LogWarning((object)("Could not apply etched magic for " + text + " / " + cfg.Label));
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("ApplyEtchedMagic failed: " + ex.Message));
			}
		}

		private static bool TryApplyViaApiJson(ItemData item, string effectType, float value, string rarityName)
		{
			Type type = FindType("EpicLoot.API");
			if (type == null)
			{
				return false;
			}
			MethodInfo method = type.GetMethod("ApplyMagicItemJson", BindingFlags.Static | BindingFlags.Public);
			if (method == null)
			{
				return false;
			}
			int num = RarityToInt(rarityName);
			string text = "{\"Version\":3,\"Rarity\":" + num + ",\"Effects\":[{\"Version\":1,\"EffectValue\":" + value.ToString(CultureInfo.InvariantCulture) + ",\"EffectType\":\"" + effectType + "\"}],\"TypeNameOverride\":null,\"LegendaryID\":null,\"SetID\":null,\"IsUnidentified\":false,\"SocketCount\":0,\"Sockets\":[]}";
			object obj = method.Invoke(null, new object[2] { item, text });
			bool flag = !(obj is bool) || (bool)obj;
			if (!flag)
			{
				Logger.LogWarning((object)("ApplyMagicItemJson returned false for " + effectType));
			}
			return flag;
		}

		private static int RarityToInt(string rarity)
		{
			if (string.IsNullOrEmpty(rarity))
			{
				return 0;
			}
			return rarity.Trim().ToLowerInvariant() switch
			{
				"rare" => 1, 
				"epic" => 2, 
				"legendary" => 3, 
				"mythic" => 4, 
				_ => 0, 
			};
		}

		private static bool TryApplyMagicToItemData(ItemData item, string effectType, float value, string rarityName)
		{
			Type type = FindType("EpicLoot.ItemDataExtensions");
			if (type == null)
			{
				return false;
			}
			MethodInfo method = type.GetMethod("ApplyMagicToItemData", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (method == null)
			{
				return false;
			}
			ParameterInfo[] parameters = method.GetParameters();
			object[] array = new object[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				Type parameterType = parameters[i].ParameterType;
				string text = ((parameters[i].Name != null) ? parameters[i].Name.ToLowerInvariant() : "");
				if (parameterType.Name.IndexOf("ItemData") >= 0)
				{
					array[i] = item;
				}
				else if (parameterType == typeof(string) && (text.IndexOf("effect") >= 0 || text.IndexOf("type") >= 0))
				{
					array[i] = effectType;
				}
				else if (parameterType == typeof(string) && text.IndexOf("rarity") >= 0)
				{
					array[i] = rarityName;
				}
				else if (parameterType == typeof(float) || parameterType == typeof(double) || parameterType == typeof(int))
				{
					if (parameterType == typeof(int))
					{
						array[i] = Mathf.RoundToInt(value);
					}
					else if (parameterType == typeof(double))
					{
						array[i] = (double)value;
					}
					else
					{
						array[i] = value;
					}
				}
				else if (parameterType.IsEnum && parameterType.Name.IndexOf("Rarity") >= 0)
				{
					array[i] = ParseEnum(parameterType, rarityName);
				}
				else if (parameterType.IsEnum)
				{
					array[i] = ParseEnum(parameterType, effectType);
				}
				else
				{
					array[i] = (parameterType.IsValueType ? Activator.CreateInstance(parameterType) : null);
				}
			}
			method.Invoke(null, array);
			Logger.LogInfo((object)("ApplyMagicToItemData OK: " + effectType));
			return true;
		}

		private static bool TrySaveMagicItem(ItemData item, string effectType, float value, string rarityName)
		{
			Type type = FindType("EpicLoot.ItemDataExtensions");
			Type type2 = FindType("EpicLoot.MagicItem");
			Type effectClrType = FindType("EpicLoot.MagicItemEffect");
			if (type == null || type2 == null)
			{
				return false;
			}
			MethodInfo method = type.GetMethod("GetMagicItem", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = type.GetMethod("SaveMagicItem", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method3 = type.GetMethod("SetNumericEffectValue", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			object obj = null;
			if (method != null)
			{
				try
				{
					obj = method.Invoke(null, new object[1] { item });
				}
				catch
				{
				}
			}
			if (obj == null)
			{
				obj = Activator.CreateInstance(type2);
			}
			PropertyInfo property = type2.GetProperty("Rarity");
			if (property != null)
			{
				object obj3 = ParseEnum(property.PropertyType, rarityName);
				if (obj3 != null)
				{
					property.SetValue(obj, obj3, null);
				}
			}
			EnsureEffectOnMagicItem(obj, effectClrType, effectType, value);
			if (method3 != null && IsNumericEffect(effectType))
			{
				try
				{
					method3.Invoke(null, new object[3] { item, effectType, value });
				}
				catch
				{
					try
					{
						method3.Invoke(null, new object[3] { obj, effectType, value });
					}
					catch
					{
					}
				}
			}
			if (method2 != null)
			{
				method2.Invoke(null, new object[2] { item, obj });
				Logger.LogInfo((object)("SaveMagicItem OK: " + effectType));
				return true;
			}
			return false;
		}

		private static void EnsureEffectOnMagicItem(object magicItem, Type effectClrType, string effectType, float value)
		{
			if (magicItem == null)
			{
				return;
			}
			PropertyInfo property = magicItem.GetType().GetProperty("Effects");
			if (property == null)
			{
				return;
			}
			object value2 = property.GetValue(magicItem, null);
			if (value2 == null)
			{
				return;
			}
			PropertyInfo property2 = value2.GetType().GetProperty("Count");
			int num = 0;
			if (property2 != null)
			{
				num = (int)property2.GetValue(value2, null);
			}
			MethodInfo method = value2.GetType().GetMethod("get_Item", new Type[1] { typeof(int) });
			if (method != null)
			{
				for (int i = 0; i < num; i++)
				{
					object obj = method.Invoke(value2, new object[1] { i });
					if (obj != null)
					{
						string effectTypeName = GetEffectTypeName(obj);
						if (effectTypeName == effectType)
						{
							SetEffectValue(obj, value);
							return;
						}
					}
				}
			}
			object obj2 = CreateMagicItemEffect(effectClrType, effectType, value);
			if (obj2 != null)
			{
				MethodInfo method2 = value2.GetType().GetMethod("Add");
				if (method2 != null)
				{
					method2.Invoke(value2, new object[1] { obj2 });
				}
			}
		}

		private static object CreateMagicItemEffect(Type effectClrType, string effectType, float value)
		{
			if (effectClrType == null)
			{
				effectClrType = FindType("EpicLoot.MagicItemEffect");
			}
			if (effectClrType == null)
			{
				return null;
			}
			object obj = null;
			try
			{
				obj = Activator.CreateInstance(effectClrType);
			}
			catch
			{
				return null;
			}
			PropertyInfo property = effectClrType.GetProperty("EffectType");
			if (property != null)
			{
				if (property.PropertyType == typeof(string))
				{
					property.SetValue(obj, effectType, null);
				}
				else if (property.PropertyType.IsEnum)
				{
					object obj3 = ParseEnum(property.PropertyType, effectType);
					if (obj3 != null)
					{
						property.SetValue(obj, obj3, null);
					}
				}
			}
			FieldInfo field = effectClrType.GetField("EffectType");
			if (field != null && field.FieldType == typeof(string))
			{
				field.SetValue(obj, effectType);
			}
			SetEffectValue(obj, value);
			return obj;
		}

		private static void SetEffectValue(object effect, float value)
		{
			if (effect == null)
			{
				return;
			}
			PropertyInfo property = effect.GetType().GetProperty("EffectValue");
			if (property != null && property.CanWrite)
			{
				if (property.PropertyType == typeof(float))
				{
					property.SetValue(effect, value, null);
				}
				else if (property.PropertyType == typeof(double))
				{
					property.SetValue(effect, (double)value, null);
				}
				else if (property.PropertyType == typeof(int))
				{
					property.SetValue(effect, Mathf.RoundToInt(value), null);
				}
			}
			FieldInfo field = effect.GetType().GetField("EffectValue");
			if (field != null)
			{
				if (field.FieldType == typeof(float))
				{
					field.SetValue(effect, value);
				}
				else if (field.FieldType == typeof(double))
				{
					field.SetValue(effect, (double)value);
				}
			}
		}

		private static string GetEffectTypeName(object effect)
		{
			if (effect == null)
			{
				return null;
			}
			PropertyInfo property = effect.GetType().GetProperty("EffectType");
			if (property != null)
			{
				object value = property.GetValue(effect, null);
				if (value != null)
				{
					return value.ToString();
				}
			}
			FieldInfo field = effect.GetType().GetField("EffectType");
			if (field != null)
			{
				object value2 = field.GetValue(effect);
				if (value2 != null)
				{
					return value2.ToString();
				}
			}
			return null;
		}

		private static string ResolveEffectType(string configured)
		{
			if (string.IsNullOrEmpty(configured))
			{
				return "Riches";
			}
			string text = configured.Trim();
			if (text.Equals("Air Jump", StringComparison.OrdinalIgnoreCase) || text.Equals("AirJump", StringComparison.OrdinalIgnoreCase))
			{
				return "DoubleJump";
			}
			if (text.Equals("Feather Fall", StringComparison.OrdinalIgnoreCase))
			{
				return "FeatherFall";
			}
			return text;
		}

		private static string DisplayEffectName(string effectType)
		{
			string text = ResolveEffectType(effectType);
			if (text == "DoubleJump")
			{
				return "Air Jump";
			}
			if (text == "FeatherFall")
			{
				return "Feather Fall";
			}
			return text;
		}

		private static bool IsNumericEffect(string effectType)
		{
			string text = ResolveEffectType(effectType);
			return text == "Riches";
		}

		private static Type FindType(string fullName)
		{
			Type type = Type.GetType(fullName + ", EpicLoot");
			if (type != null)
			{
				return type;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				try
				{
					if (!(assemblies[i].GetName().Name != "EpicLoot"))
					{
						type = assemblies[i].GetType(fullName);
						if (type != null)
						{
							return type;
						}
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static object ParseEnum(Type enumType, string name)
		{
			if (enumType == null || !enumType.IsEnum || string.IsNullOrEmpty(name))
			{
				return null;
			}
			try
			{
				return Enum.Parse(enumType, name, ignoreCase: true);
			}
			catch
			{
				return null;
			}
		}
	}
	public static class LegendaryRuneManager
	{
		private static readonly Dictionary<string, LegendaryRuneDef> PrefabToRune = new Dictionary<string, LegendaryRuneDef>();

		private static ManualLogSource Logger => EtchedRunesPlugin.Log;

		public static void RegisterAll()
		{
			if (!ModConfig.Enabled.Value)
			{
				return;
			}
			foreach (LegendaryRuneDef legendaryRune in ModConfig.LegendaryRunes)
			{
				if (ModConfig.IsLegendaryEnabled(legendaryRune))
				{
					try
					{
						RegisterSingleRune(legendaryRune);
					}
					catch (Exception ex)
					{
						Logger.LogError((object)("Failed to register rune " + legendaryRune.Key + ": " + ex));
					}
				}
			}
		}

		private static void RegisterSingleRune(LegendaryRuneDef def)
		{
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			string text = def.BasePrefab.Value;
			if (string.IsNullOrEmpty(text))
			{
				text = "EtchedRunestoneLegendary";
			}
			GameObject prefab = PrefabManager.Instance.GetPrefab(text);
			if ((Object)(object)prefab == (Object)null)
			{
				string[] array = new string[5] { "EtchedRunestoneLegendary", "EtchedRunestoneEpic", "EtchedRunestoneRare", "EtchedRunestoneMagic", "SwordBronze" };
				for (int i = 0; i < array.Length; i++)
				{
					prefab = PrefabManager.Instance.GetPrefab(array[i]);
					if ((Object)(object)prefab != (Object)null)
					{
						text = array[i];
						Logger.LogWarning((object)("Base prefab missing, using fallback: " + text + " for " + def.Key));
						break;
					}
				}
			}
			if ((Object)(object)prefab == (Object)null)
			{
				Logger.LogError((object)("No base prefab found for legendary rune " + def.Key + " – skipped."));
				return;
			}
			ItemConfig val = new ItemConfig();
			val.Name = def.DisplayName.Value;
			val.Description = "Apply this rune to a matching item to turn it into the Legendary Set piece.\nLegendary ID: " + def.LegendaryID.Value;
			CustomItem val2 = new CustomItem(def.PrefabName, text, val);
			ItemManager.Instance.AddItem(val2);
			PrefabToRune[def.PrefabName] = def;
			Logger.LogInfo((object)("Registered etched rune: " + def.DisplayName.Value + " (" + def.PrefabName + ") -> " + def.LegendaryID.Value));
		}

		public static LegendaryRuneDef GetRuneByPrefab(string prefabName)
		{
			if (string.IsNullOrEmpty(prefabName))
			{
				return null;
			}
			if (PrefabToRune.TryGetValue(prefabName, out var value))
			{
				return value;
			}
			return null;
		}

		public static LegendaryRuneDef GetRuneByItemData(ItemData item)
		{
			if (item == null || (Object)(object)item.m_dropPrefab == (Object)null)
			{
				return null;
			}
			return GetRuneByPrefab(((Object)item.m_dropPrefab).name);
		}

		public static bool IsEtchedRune(ItemData item)
		{
			return GetRuneByItemData(item) != null;
		}

		public static bool CanApplyTo(LegendaryRuneDef rune, ItemData target)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			if (rune == null || target == null || target.m_shared == null)
			{
				return false;
			}
			SharedData shared = target.m_shared;
			string text = rune.AllowedItemTypes.Value;
			if (text == null)
			{
				text = "";
			}
			if (!string.IsNullOrEmpty(text))
			{
				string[] array = text.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				bool flag = false;
				for (int i = 0; i < array.Length; i++)
				{
					string value = array[i].Trim();
					if (Enum.TryParse<ItemType>(value, ignoreCase: true, out ItemType result) && shared.m_itemType == result)
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					return false;
				}
			}
			string text2 = rune.AllowedSkillTypes.Value;
			if (text2 == null)
			{
				text2 = "";
			}
			if (!string.IsNullOrEmpty(text2))
			{
				string[] array2 = text2.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				bool flag2 = false;
				for (int j = 0; j < array2.Length; j++)
				{
					string value2 = array2[j].Trim();
					if (Enum.TryParse<SkillType>(value2, ignoreCase: true, out SkillType result2) && shared.m_skillType == result2)
					{
						flag2 = true;
						break;
					}
				}
				if (!flag2)
				{
					return false;
				}
			}
			if (rune.RequireNoParryPower.Value && shared.m_timedBlockBonus > 1.01f)
			{
				return false;
			}
			return true;
		}

		public static bool TryApplyRune(LegendaryRuneDef rune, ItemData target, out string message)
		{
			message = "";
			if (!CanApplyTo(rune, target))
			{
				message = "This rune cannot be applied to that item.";
				return false;
			}
			string value = rune.LegendaryID.Value;
			if (string.IsNullOrEmpty(value))
			{
				message = "Rune has no LegendaryID configured.";
				return false;
			}
			try
			{
				if (ApplyLegendaryViaReflection(target, value))
				{
					message = "Successfully etched: " + rune.DisplayName.Value;
					Logger.LogInfo((object)("Applied " + value + " to " + target.m_shared.m_name));
					return true;
				}
				message = "Epic Loot refused to create the legendary item (requirements not met or API not found).";
				Logger.LogWarning((object)("ApplyLegendary failed for " + value));
				return false;
			}
			catch (Exception ex)
			{
				message = "Error while applying rune: " + ex.Message;
				Logger.LogError((object)ex.ToString());
				return false;
			}
		}

		private static bool ApplyLegendaryViaReflection(ItemData item, string legendaryId)
		{
			Assembly assembly = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				try
				{
					if (assemblies[i].GetName().Name == "EpicLoot")
					{
						assembly = assemblies[i];
						break;
					}
				}
				catch
				{
				}
			}
			if (assembly == null)
			{
				Logger.LogError((object)"EpicLoot assembly not found.");
				return false;
			}
			Type type = assembly.GetType("EpicLoot.API");
			if (type == null)
			{
				Logger.LogError((object)"EpicLoot.API type not found.");
				return false;
			}
			MethodInfo method = type.GetMethod("GetMagicItemJson", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = type.GetMethod("ApplyMagicItemJson", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method3 = type.GetMethod("GetLegendaryInfoJson", BindingFlags.Static | BindingFlags.Public);
			if (method != null && method2 != null)
			{
				string text = null;
				try
				{
					text = method.Invoke(null, new object[1] { item }) as string;
				}
				catch (Exception ex)
				{
					Logger.LogWarning((object)("GetMagicItemJson failed: " + ex.Message));
				}
				string text2 = null;
				string setId = null;
				if (method3 != null)
				{
					try
					{
						string text3 = method3.Invoke(null, new object[1] { legendaryId }) as string;
						if (!string.IsNullOrEmpty(text3))
						{
							Logger.LogInfo((object)("LegendaryInfoJson: " + text3));
							text2 = ExtractJsonString(text3, "Name");
							if (string.IsNullOrEmpty(text2))
							{
								text2 = ExtractJsonString(text3, "name");
							}
							if (IndexOfIgnoreCase(text3, "\"IsSetItem\":true") >= 0 || IndexOfIgnoreCase(text3, "\"IsSetItem\": true") >= 0)
							{
								setId = DeriveSetId(legendaryId);
							}
						}
					}
					catch (Exception ex2)
					{
						Logger.LogWarning((object)("GetLegendaryInfoJson failed: " + ex2.Message));
					}
				}
				text = ((!string.IsNullOrEmpty(text) && !(text == "null") && !(text == "{}")) ? InjectLegendaryIntoJson(text, legendaryId, text2, setId) : BuildMinimalMagicJson(legendaryId, text2, setId));
				Logger.LogInfo((object)("Applying magic JSON (preserve effects): " + text));
				try
				{
					if (!(method2.Invoke(null, new object[2] { item, text }) is bool result))
					{
						return true;
					}
					return result;
				}
				catch (Exception ex3)
				{
					Logger.LogError((object)("ApplyMagicItemJson failed: " + ex3));
					if (ex3.InnerException != null)
					{
						Logger.LogError((object)("Inner: " + ex3.InnerException));
					}
				}
			}
			return ApplyLegendaryOnMagicItemObject(assembly, item, legendaryId);
		}

		private static bool ApplyLegendaryOnMagicItemObject(Assembly epicAsm, ItemData item, string legendaryId)
		{
			Type type = epicAsm.GetType("EpicLoot.ItemDataExtensions");
			if (type == null)
			{
				Logger.LogError((object)"ItemDataExtensions not found.");
				return false;
			}
			MethodInfo method = type.GetMethod("GetMagicItem", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = type.GetMethod("SaveMagicItem", BindingFlags.Static | BindingFlags.Public);
			if (method == null || method2 == null)
			{
				Logger.LogError((object)"GetMagicItem/SaveMagicItem not found.");
				return false;
			}
			object obj = null;
			try
			{
				obj = method.Invoke(null, new object[1] { item });
			}
			catch
			{
			}
			Type type2 = epicAsm.GetType("EpicLoot.MagicItem");
			if (type2 == null)
			{
				type2 = epicAsm.GetType("EpicLoot.Magic.MagicItem");
			}
			if (obj == null)
			{
				if (type2 == null)
				{
					Logger.LogError((object)"MagicItem type not found and item has no magic data.");
					return false;
				}
				obj = Activator.CreateInstance(type2);
				PropertyInfo property = type2.GetProperty("Rarity");
				if (property != null)
				{
					Type propertyType = property.PropertyType;
					try
					{
						object value = Enum.Parse(propertyType, "Legendary", ignoreCase: true);
						property.SetValue(obj, value, null);
					}
					catch
					{
					}
				}
			}
			Type type3 = obj.GetType();
			PropertyInfo[] properties = type3.GetProperties(BindingFlags.Instance | BindingFlags.Public);
			for (int i = 0; i < properties.Length; i++)
			{
				Logger.LogInfo((object)("MagicItem prop: " + properties[i].Name + " : " + properties[i].PropertyType.Name));
			}
			SetStringProp(obj, "TypeNameOverride", "$mod_epicloot_l_" + legendaryId.ToLowerInvariant());
			SetStringProp(obj, "LegendaryID", legendaryId);
			SetStringProp(obj, "LegendaryId", legendaryId);
			SetStringProp(obj, "LegendarySetItemID", legendaryId);
			SetStringProp(obj, "LegendarySetItemId", legendaryId);
			try
			{
				method2.Invoke(null, new object[2] { item, obj });
				Logger.LogInfo((object)("SaveMagicItem OK for " + legendaryId));
				return true;
			}
			catch (Exception ex)
			{
				Logger.LogError((object)("SaveMagicItem failed: " + ex));
				return false;
			}
		}

		private static void SetStringProp(object obj, string name, string value)
		{
			if (obj != null && value != null)
			{
				PropertyInfo property = obj.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
				if (property != null && property.CanWrite && property.PropertyType == typeof(string))
				{
					property.SetValue(obj, value, null);
					Logger.LogInfo((object)("Set " + name + " = " + value));
				}
				FieldInfo field = obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public);
				if (field != null && field.FieldType == typeof(string))
				{
					field.SetValue(obj, value);
					Logger.LogInfo((object)("Set field " + name + " = " + value));
				}
			}
		}

		private static string ExtractJsonString(string json, string key)
		{
			if (string.IsNullOrEmpty(json) || string.IsNullOrEmpty(key))
			{
				return null;
			}
			string text = "\"" + key + "\"";
			int num = json.IndexOf(text, StringComparison.OrdinalIgnoreCase);
			if (num < 0)
			{
				return null;
			}
			int num2 = json.IndexOf(':', num + text.Length);
			if (num2 < 0)
			{
				return null;
			}
			int num3 = json.IndexOf('"', num2 + 1);
			if (num3 < 0)
			{
				return null;
			}
			int num4 = json.IndexOf('"', num3 + 1);
			if (num4 < 0)
			{
				return null;
			}
			return json.Substring(num3 + 1, num4 - num3 - 1);
		}

		private static string BuildMinimalMagicJson(string legendaryId, string typeNameOverride, string setId)
		{
			if (string.IsNullOrEmpty(typeNameOverride))
			{
				typeNameOverride = "$mod_epicloot_l_" + legendaryId.ToLowerInvariant();
			}
			string text = "";
			if (!string.IsNullOrEmpty(setId))
			{
				text = ",\"SetID\":\"" + setId + "\"";
			}
			return "{\"Version\":3,\"Rarity\":3,\"Effects\":[],\"TypeNameOverride\":\"" + typeNameOverride + "\",\"LegendaryID\":\"" + legendaryId + "\"" + text + ",\"IsUnidentified\":false}";
		}

		private static string InjectLegendaryIntoJson(string json, string legendaryId, string typeNameOverride, string setId)
		{
			if (string.IsNullOrEmpty(typeNameOverride))
			{
				typeNameOverride = "$mod_epicloot_l_" + legendaryId.ToLowerInvariant();
			}
			json = SetOrReplaceJsonString(json, "TypeNameOverride", typeNameOverride);
			json = SetOrReplaceJsonString(json, "LegendaryID", legendaryId);
			if (!string.IsNullOrEmpty(setId))
			{
				json = SetOrReplaceJsonString(json, "SetID", setId);
			}
			return json;
		}

		private static string SetOrReplaceJsonString(string json, string key, string value)
		{
			if (string.IsNullOrEmpty(json))
			{
				json = "{}";
			}
			string text = value.Replace("\\", "\\\\").Replace("\"", "\\\"");
			string text2 = "\"" + key + "\":\"" + text + "\"";
			string text3 = "\"" + key + "\"";
			int num = IndexOfIgnoreCase(json, text3);
			if (num >= 0)
			{
				int num2 = json.IndexOf(':', num + text3.Length);
				if (num2 < 0)
				{
					return json;
				}
				int i;
				for (i = num2 + 1; i < json.Length && (json[i] == ' ' || json[i] == '\t'); i++)
				{
				}
				int j = i;
				if (i < json.Length && json[i] == '"')
				{
					for (j = i + 1; j < json.Length; j++)
					{
						if (json[j] == '"' && json[j - 1] != '\\')
						{
							j++;
							break;
						}
					}
				}
				else if (i + 4 <= json.Length && json.Substring(i, 4) == "null")
				{
					j = i + 4;
				}
				else
				{
					for (; j < json.Length && json[j] != ',' && json[j] != '}'; j++)
					{
					}
				}
				return json.Substring(0, num) + text2 + json.Substring(j);
			}
			string text4 = json.Trim();
			if (text4.EndsWith("}"))
			{
				text4 = text4.Substring(0, text4.Length - 1).TrimEnd(new char[0]);
			}
			if (!text4.EndsWith("{") && !text4.EndsWith(","))
			{
				text4 += ",";
			}
			return text4 + text2 + "}";
		}

		private static int IndexOfIgnoreCase(string haystack, string needle)
		{
			return haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
		}

		private static string DeriveSetId(string legendaryId)
		{
			if (string.IsNullOrEmpty(legendaryId))
			{
				return legendaryId;
			}
			string[] array = new string[23]
			{
				"Heimdall", "Ragnar", "Thor", "DvergerArsenal", "Loki", "Egil", "Elivagar", "Fylgja", "Freyja", "Bolthorn",
				"Heidr", "Mimir", "Einherjar", "Ullr", "Hel", "Huldra", "Surtr", "HelCourt", "Hrungnir", "Svalinn",
				"Jormungandr", "Gullveig", "GiantsBlood"
			};
			for (int i = 0; i < array.Length; i++)
			{
				if (legendaryId.StartsWith(array[i], StringComparison.OrdinalIgnoreCase))
				{
					return array[i];
				}
			}
			return legendaryId;
		}
	}
}
namespace Orgetorix.EtchedRunes.Patches
{
	[HarmonyPatch]
	internal static class TraderPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
		private static void GetAvailableItems_Postfix(Trader __instance, List<TradeItem> __result)
		{
			if ((Object)(object)__instance == (Object)null || __result == null || !ModConfig.Enabled.Value || !IsHaldor(__instance))
			{
				return;
			}
			try
			{
				TradeItem template = ((__result.Count > 0) ? __result[0] : null);
				if (ModConfig.SellRichesAtHaldor.Value)
				{
					foreach (RichesItemConfig richesItem in ModConfig.RichesItems)
					{
						if (ModConfig.IsRichesEnabled(richesItem))
						{
							string text = FindRegisteredRichesPrefab(richesItem);
							if (!string.IsNullOrEmpty(text))
							{
								AddTrade(__result, text, richesItem.Price.Value, richesItem.Stack.Value, template);
							}
						}
					}
				}
				if (!ModConfig.SellSetRunesAtHaldor.Value)
				{
					return;
				}
				foreach (LegendaryRuneDef legendaryRune in ModConfig.LegendaryRunes)
				{
					if (ModConfig.IsLegendaryEnabled(legendaryRune))
					{
						AddTrade(__result, legendaryRune.PrefabName, legendaryRune.Price.Value, legendaryRune.Stack.Value, template);
					}
				}
			}
			catch (Exception ex)
			{
				EtchedRunesPlugin.Log.LogError((object)("Trader patch failed: " + ex));
			}
		}

		private static bool IsHaldor(Trader trader)
		{
			if ((Object)(object)trader == (Object)null)
			{
				return false;
			}
			string text = ((Object)trader).name ?? "";
			if (text.IndexOf("Haldor", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (text.IndexOf("Trader", StringComparison.OrdinalIgnoreCase) >= 0 && text.IndexOf("Hildir", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("BogWitch", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return true;
			}
			return false;
		}

		private static string FindRegisteredRichesPrefab(RichesItemConfig cfg)
		{
			foreach (KeyValuePair<string, RichesItemConfig> item in RichesRuneManager.Registered)
			{
				if (object.ReferenceEquals(item.Value, cfg))
				{
					return item.Key;
				}
			}
			return null;
		}

		private static void AddTrade(List<TradeItem> list, string prefabName, int price, int stack, TradeItem template)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			if (string.IsNullOrEmpty(prefabName))
			{
				return;
			}
			GameObject prefab = PrefabManager.Instance.GetPrefab(prefabName);
			if ((Object)(object)prefab == (Object)null)
			{
				return;
			}
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
			{
				return;
			}
			TradeItem val;
			if (template != null)
			{
				MethodInfo method = typeof(TradeItem).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);
				if (method != null)
				{
					object obj = method.Invoke(template, null);
					val = (TradeItem)((obj is TradeItem) ? obj : null);
				}
				else
				{
					val = null;
				}
				if (val == null)
				{
					val = new TradeItem();
				}
			}
			else
			{
				val = new TradeItem();
			}
			val.m_prefab = component;
			val.m_price = Mathf.Max(1, price);
			val.m_stack = Mathf.Max(1, stack);
			val.m_requiredGlobalKey = "";
			EnsureStringsNotNull(val);
			list.Add(val);
		}

		private static void EnsureStringsNotNull(TradeItem trade)
		{
			if (trade == null)
			{
				return;
			}
			FieldInfo[] fields = typeof(TradeItem).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (!(fieldInfo.FieldType != typeof(string)))
				{
					object value = fieldInfo.GetValue(trade);
					if (value == null)
					{
						fieldInfo.SetValue(trade, "");
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class ItemUsePatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemDrop), "Awake")]
		private static void ItemDrop_Awake(ItemDrop __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && __instance.m_itemData != null)
			{
				RichesRuneManager.TryApplyMagicData(__instance.m_itemData);
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })]
		[HarmonyPostfix]
		private static void Inventory_AddItem(ItemData item)
		{
			RichesRuneManager.TryApplyMagicData(item);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static bool Humanoid_UseItem(Humanoid __instance, Inventory inventory, ItemData item, bool fromInventoryGui)
		{
			if (!fromInventoryGui || item == null || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			LegendaryRuneDef runeByItemData = LegendaryRuneManager.GetRuneByItemData(item);
			if (runeByItemData == null)
			{
				return true;
			}
			ItemData slotOne = GetSlotOne(inventory);
			if (slotOne == null)
			{
				Say(__instance, "Place the target item in inventory slot 1 (top-left).");
				return false;
			}
			if (object.ReferenceEquals(slotOne, item))
			{
				Say(__instance, "The rune cannot be applied to itself. Put a piece of gear in slot 1.");
				return false;
			}
			string message;
			bool flag = LegendaryRuneManager.TryApplyRune(runeByItemData, slotOne, out message);
			Say(__instance, (!string.IsNullOrEmpty(message)) ? message : (flag ? "Rune applied." : "Rune failed."));
			if (flag && inventory != null)
			{
				inventory.RemoveItem(item, 1);
			}
			return false;
		}

		private static ItemData GetSlotOne(Inventory inventory)
		{
			if (inventory == null)
			{
				return null;
			}
			return inventory.GetItemAt(0, 0);
		}

		private static void Say(Humanoid humanoid, string text)
		{
			if (!((Object)(object)humanoid == (Object)null) && !string.IsNullOrEmpty(text))
			{
				((Character)humanoid).Message((MessageType)2, text, 0, (Sprite)null, false);
			}
		}
	}
}