Decompiled source of ImmersiveTrader v1.4.6

ImmersiveTrader.dll

Decompiled 4 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HypnoCode;
using HypnoCode.Crafting;
using HypnoCode.Dummy;
using HypnoCode.Dungeons;
using ImmersiveTrader;
using ImmersiveTrader.AfkTraining;
using ImmersiveTrader.Commands;
using ImmersiveTrader.Components;
using ImmersiveTrader.Dungeons;
using ImmersiveTrader.Models;
using ImmersiveTrader.Patches;
using ImmersiveTrader.Quests;
using ImmersiveTrader.Quests.StoneBeasts;
using ImmersiveTrader.Quests.Wyrm;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using SoftReferenceableAssets;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Valheim.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("ImmersiveTrader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+74818f65649895da1ef6d3824465421faaf15ccf")]
[assembly: AssemblyProduct("ImmersiveTrader")]
[assembly: AssemblyTitle("ImmersiveTrader")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal sealed class RnrBloodReplay : MonoBehaviour
{
	private float next = 6f;

	private int left = 3;

	private void Update()
	{
		//IL_0049: 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_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		if (left <= 0)
		{
			return;
		}
		next -= Time.deltaTime;
		if (next > 0f)
		{
			return;
		}
		next = 10f;
		Player localPlayer = Player.m_localPlayer;
		if (!Object.op_Implicit((Object)(object)localPlayer))
		{
			return;
		}
		Vector3 val = ((Component)localPlayer).transform.position - ((Component)this).transform.position;
		if (!(((Vector3)(ref val)).sqrMagnitude > 1600f))
		{
			left--;
			ParticleSystem component = ((Component)this).GetComponent<ParticleSystem>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.Play(true);
			}
		}
	}
}
namespace HypnoCode
{
	internal static class Admin
	{
		private static readonly FieldInfo AdminListField = AccessTools.Field(typeof(ZNet), "m_adminList");

		private static string Bare(string value)
		{
			return value.Substring(value.LastIndexOf('_') + 1).Trim();
		}

		private static bool Listed(IEnumerable<string> admins, string id)
		{
			if (admins == null || string.IsNullOrEmpty(id))
			{
				return false;
			}
			string text = Bare(id);
			if (text.Length == 0)
			{
				return false;
			}
			foreach (string admin in admins)
			{
				if (admin != null && (string.Equals(admin.Trim(), id, StringComparison.OrdinalIgnoreCase) || string.Equals(Bare(admin), text, StringComparison.OrdinalIgnoreCase)))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool IsPeer(long uid)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (uid == ZNet.GetUID())
			{
				return true;
			}
			ZNetPeer peer = instance.GetPeer(uid);
			if (peer == null || peer.m_socket == null)
			{
				return false;
			}
			string hostName = peer.m_socket.GetHostName();
			if (string.IsNullOrEmpty(hostName))
			{
				return false;
			}
			if (instance.IsAdmin(hostName))
			{
				return true;
			}
			SyncedList val = (SyncedList)((AdminListField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			return Listed((val != null) ? val.GetList() : instance.GetAdminList(), hostName);
		}

		internal static bool IsLocal(bool serverSays = false)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (instance.LocalPlayerIsAdminOrHost() || serverSays)
			{
				return true;
			}
			string id;
			try
			{
				id = ((object)Unsafe.As<PlatformUserID, PlatformUserID>(ref UserInfo.GetLocalUser().UserId)/*cast due to .constrained prefix*/).ToString();
			}
			catch
			{
				return false;
			}
			return Listed(instance.GetAdminList(), id);
		}
	}
	internal static class Compat
	{
		internal enum Kind
		{
			CompatMode,
			Info,
			Option,
			Resolved
		}

		internal sealed class Known
		{
			public string Guid;

			public string TypeName;

			public string Name;

			public Kind Kind;

			public Dictionary<string, string> Does;

			public Dictionary<string, string> Toggle;
		}

		private const string Backpack = "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)";

		private const string BackpackSlots = "the backpack's rows go right after the player's own rows, before Extra Slots' special slots";

		private const string BackpackArchery = "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is";

		internal static readonly Known[] Table = new Known[7]
		{
			new Known
			{
				Guid = "seneaL.valheim.ui",
				Name = "SeneaL UI",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" },
					{ "AdvancedBackpacks", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "SeneaLUI" },
					{ "AdvancedBackpacks", "SeneaLUI" }
				}
			},
			new Known
			{
				Guid = "seneaL.valheim.api",
				Name = "SeneaL API",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "the Quest Log gets a tab in SeneaL's character window" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "SeneaLQuestLogTab" } }
			},
			new Known
			{
				Guid = "shudnal.ExtraSlots",
				Name = "Extra Slots",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" },
					{ "AdvancedBackpacks", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "ExtraSlots" },
					{ "AdvancedBackpacks", "ExtraSlots" }
				}
			},
			new Known
			{
				Guid = "ishid4.mods.betterarchery",
				Name = "Better Archery",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" },
					{ "AdvancedBackpacks", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "BetterArchery" },
					{ "AdvancedBackpacks", "BetterArchery" }
				}
			},
			new Known
			{
				TypeName = "ValheimProfessions.ProfessionManager",
				Name = "ValheimProfessions",
				Kind = Kind.Option,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "traders, boards and caravans turn away a player with a profession when [Compatibility] BlockPlayersWithProfession is on" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "BlockPlayersWithProfession" } }
			},
			new Known
			{
				Guid = "goldenrevolver.quick_stack_store",
				Name = "Quick Stack Store",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "SortByQoL", "works with it: when it refreshes the crafting list, the sorting and the filters are applied again" } }
			},
			new Known
			{
				Guid = "p0kahontazz.coah",
				Name = "Children of the Ancient Heart",
				Kind = Kind.Resolved,
				Does = new Dictionary<string, string>
				{
					{ "AdvancedBackpacks", "Advanced Backpacks is switched off (COAH has the same backpacks); the Advanced Backpacks a player carries become COAH backpacks with what they hold" },
					{ "AdvancedPortal", "the Advanced Portal is no longer in the hammer (COAH's Heart Portal is the same); the ones standing keep working" }
				}
			}
		};

		private static readonly Dictionary<string, string> OurGuids = new Dictionary<string, string>
		{
			{ "ImmersiveTrader", "p0kahontazz.immersivetrader" },
			{ "COAH", "p0kahontazz.coah" },
			{ "AdvancedBackpacks", "p0kahontazz.advancedbackpacks" },
			{ "AdvancedPortal", "p0kahontazz.advancedportal" },
			{ "SortByQoL", "p0kahontazz.sortbyqol" }
		};

		internal static Type FindType(string fullName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					Type type = assembly.GetType(fullName, throwOnError: false);
					if (type != null)
					{
						return type;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		internal static bool Installed(Known known, out string version)
		{
			version = "";
			try
			{
				if (known.Guid != null)
				{
					if (!Chainloader.PluginInfos.TryGetValue(known.Guid, out var value) || value == null)
					{
						return false;
					}
					version = ((value.Metadata != null && value.Metadata.Version != null) ? value.Metadata.Version.ToString() : "");
					return true;
				}
				return known.TypeName != null && FindType(known.TypeName) != null;
			}
			catch
			{
				return false;
			}
		}

		private static string Off(Known known, string ours)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			try
			{
				if (known.Toggle == null || !known.Toggle.TryGetValue(ours, out var value) || !OurGuids.TryGetValue(ours, out var value2))
				{
					return "";
				}
				if (!Chainloader.PluginInfos.TryGetValue(value2, out var value3) || value3 == null || (Object)(object)value3.Instance == (Object)null)
				{
					return "";
				}
				ConfigFile config = value3.Instance.Config;
				ConfigDefinition val = new ConfigDefinition("Compatibility", value);
				if (config == null || !config.ContainsKey(val) || !(config[val].BoxedValue is bool))
				{
					return "";
				}
				return ((bool)config[val].BoxedValue) ? "" : (" (off: [Compatibility] " + value + " = false)");
			}
			catch
			{
				return "";
			}
		}

		internal static void Report(ManualLogSource log, string ours)
		{
			if (log == null)
			{
				return;
			}
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (known.Does != null && known.Does.TryGetValue(ours, out var value) && Installed(known, out var version))
				{
					log.LogInfo((object)("Detected " + known.Name + ((version.Length > 0) ? (" " + version) : "") + ": " + value + Off(known, ours) + "."));
				}
			}
		}

		internal static List<string> Lines()
		{
			List<string> list = new List<string>();
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (Installed(known, out var version))
				{
					list.Add(known.Name + ((version.Length > 0) ? (" " + version) : "") + " (" + (known.Guid ?? known.TypeName) + ", " + known.Kind.ToString() + "): " + string.Join("; ", known.Does.Select((KeyValuePair<string, string> p) => p.Key + " - " + p.Value + Off(known, p.Key)).ToArray()));
				}
			}
			return list;
		}
	}
	internal static class LogLimit
	{
		private sealed class Seen
		{
			public float Next = float.MinValue;

			public int Skipped;
		}

		private const float Every = 10f;

		private static readonly Dictionary<string, Seen> State = new Dictionary<string, Seen>();

		internal static void Warn(ManualLogSource log, string key, string message)
		{
			if (log != null)
			{
				float unscaledTime = Time.unscaledTime;
				if (!State.TryGetValue(key, out var value))
				{
					value = (State[key] = new Seen());
				}
				if (unscaledTime < value.Next)
				{
					value.Skipped++;
					return;
				}
				log.LogWarning((object)((value.Skipped > 0) ? (message + " (and " + value.Skipped + " more times in the last " + 10f.ToString("0") + " s)") : message));
				value.Next = unscaledTime + 10f;
				value.Skipped = 0;
			}
		}
	}
	internal static class ModReport
	{
		private sealed class Listener : ILogListener, IDisposable
		{
			public void LogEvent(object sender, LogEventArgs e)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//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)
				if (e == null || (e.Level & 7) == 0)
				{
					return;
				}
				string text = Convert.ToString(e.Data) ?? "";
				if (text.Length > 800)
				{
					text = text.Substring(0, 800) + " ...";
				}
				string item = DateTime.Now.ToString("HH:mm:ss") + " [" + ((object)e.Level/*cast due to .constrained prefix*/).ToString() + ": " + ((e.Source != null) ? e.Source.SourceName : "?") + "] " + text.Replace("\r", "").Replace("\n", " | ");
				lock (recent)
				{
					recent.Enqueue(item);
					while (recent.Count > 200)
					{
						recent.Dequeue();
					}
				}
			}

			public void Dispose()
			{
			}
		}

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

			public static Func<PluginInfo, bool> <>9__8_0;

			public static Func<PluginInfo, string> <>9__8_1;

			public static Func<PluginInfo, bool> <>9__8_2;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_0;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_1;

			public static ConsoleEvent <>9__12_0;

			public static Func<PluginInfo, bool> <>9__14_0;

			public static Func<PluginInfo, string> <>9__14_1;

			internal bool <Plugins>b__8_0(PluginInfo p)
			{
				if (p != null)
				{
					return p.Metadata != null;
				}
				return false;
			}

			internal string <Plugins>b__8_1(PluginInfo p)
			{
				return p.Metadata.GUID;
			}

			internal bool <Plugins>b__8_2(PluginInfo p)
			{
				return IsHypnogoogic(p.Metadata.GUID);
			}

			internal string <ChangedSettings>b__9_0(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Section;
			}

			internal string <ChangedSettings>b__9_1(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Key;
			}

			internal void <RegisterCommand>b__12_0(ConsoleEventArgs args)
			{
				if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Usage: hypno report");
					}
					return;
				}
				try
				{
					string text = WriteCommon();
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
					}
				}
				catch (Exception ex)
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("The report could not be written: " + ex.Message);
					}
				}
			}

			internal bool <WriteCommon>b__14_0(PluginInfo p)
			{
				if (p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null)
				{
					return IsHypnogoogic(p.Metadata.GUID);
				}
				return false;
			}

			internal string <WriteCommon>b__14_1(PluginInfo p)
			{
				return p.Metadata.Name;
			}
		}

		private const int Keep = 200;

		private static readonly Queue<string> recent = new Queue<string>();

		private static Listener listener;

		internal const string CommonFile = "Hypnogoogic-report.txt";

		internal static readonly List<Action<StringBuilder>> Extra = new List<Action<StringBuilder>>();

		internal static void StartLog()
		{
			if (listener == null)
			{
				listener = new Listener();
				Logger.Listeners.Add((ILogListener)(object)listener);
			}
		}

		internal static bool IsHypnogoogic(string guid)
		{
			if (guid != null)
			{
				if (!guid.StartsWith("p0kahontazz.", StringComparison.OrdinalIgnoreCase))
				{
					return guid == "pl.rootsandremedies.foods";
				}
				return true;
			}
			return false;
		}

		internal static string GameType()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return "main menu (no world)";
			}
			if (!instance.IsServer())
			{
				return "client on a server";
			}
			if (instance.IsDedicated())
			{
				return "dedicated server";
			}
			bool flag = true;
			try
			{
				FieldInfo field = typeof(ZNet).GetField("m_openServer", BindingFlags.Static | BindingFlags.NonPublic);
				if (field != null)
				{
					flag = (bool)field.GetValue(null);
				}
			}
			catch
			{
			}
			if (!flag)
			{
				return "single player";
			}
			return "host (others can join)";
		}

		internal static void Head(StringBuilder sb, string title)
		{
			sb.AppendLine("=== " + title + " ===");
			sb.AppendLine("Written: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " UTC");
			try
			{
				sb.AppendLine("Valheim: " + Version.GetVersionString(false));
			}
			catch
			{
				sb.AppendLine("Valheim: ?");
			}
			sb.AppendLine("Game: " + GameType());
			try
			{
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.GetWorldName() != null)
				{
					sb.AppendLine("World: " + ZNet.instance.GetWorldName());
				}
			}
			catch
			{
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				sb.AppendLine("Character: " + localPlayer.GetPlayerName() + " (player id " + localPlayer.GetPlayerID() + ")");
			}
			sb.AppendLine();
		}

		internal static void Plugins(StringBuilder sb)
		{
			List<PluginInfo> list = Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.GUID, StringComparer.OrdinalIgnoreCase).ToList();
			sb.AppendLine("--- Hypnogoogic mods ---");
			foreach (PluginInfo item in list.Where((PluginInfo p) => IsHypnogoogic(p.Metadata.GUID)))
			{
				sb.AppendLine(item.Metadata.Name + " " + item.Metadata.Version?.ToString() + "  (" + item.Metadata.GUID + ")");
			}
			sb.AppendLine();
			sb.AppendLine("--- Known mods (how ours work with them, see Compat) ---");
			List<string> list2 = Compat.Lines();
			if (list2.Count == 0)
			{
				sb.AppendLine("(none installed)");
			}
			foreach (string item2 in list2)
			{
				sb.AppendLine(item2);
			}
			sb.AppendLine();
			sb.AppendLine("--- All plugins (" + list.Count + ") ---");
			foreach (PluginInfo item3 in list)
			{
				sb.AppendLine(item3.Metadata.GUID + "  " + item3.Metadata.Version?.ToString() + "  " + item3.Metadata.Name);
			}
			sb.AppendLine();
		}

		internal static void ChangedSettings(StringBuilder sb, ConfigFile config, string title)
		{
			sb.AppendLine("--- " + title + ": settings changed from the default ---");
			int num = 0;
			if (config != null)
			{
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in from p in (IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config
					orderby p.Key.Section, p.Key.Key
					select p)
				{
					ConfigEntryBase value = item.Value;
					if (value != null && !object.Equals(value.BoxedValue, value.DefaultValue))
					{
						string text = item.Key.Section + "." + item.Key.Key;
						string text2 = item.Key.Key.ToLowerInvariant();
						bool flag = value.SettingType == typeof(string) && (text2.Contains("key") || text2.Contains("token") || text2.Contains("password") || text2.Contains("secret") || text2.Contains("webhook"));
						sb.AppendLine(text + " = " + (flag ? "(hidden)" : value.GetSerializedValue()) + "   (default " + (flag ? "(hidden)" : ((value.DefaultValue != null) ? Convert.ToString(value.DefaultValue) : "none")) + ")");
						num++;
					}
				}
			}
			if (num == 0)
			{
				sb.AppendLine("(none)");
			}
			sb.AppendLine();
		}

		internal static void RecentLog(StringBuilder sb)
		{
			string[] array;
			lock (recent)
			{
				array = recent.ToArray();
			}
			sb.AppendLine("--- Last " + array.Length + " warnings and errors of the log (all mods) ---");
			if (listener == null)
			{
				sb.AppendLine("(not kept: the log was not watched)");
			}
			string[] array2 = array;
			foreach (string value in array2)
			{
				sb.AppendLine(value);
			}
			sb.AppendLine();
		}

		internal static void RegisterCommand()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			StartLog();
			object obj = <>c.<>9__12_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Usage: hypno report");
						}
						return;
					}
					try
					{
						string text = WriteCommon();
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
						}
					}
					catch (Exception ex)
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("The report could not be written: " + ex.Message);
						}
					}
				};
				<>c.<>9__12_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("hypno", "hypno report - writes BepInEx/Hypnogoogic-report.txt (game, mods, settings, last warnings) to send with a bug report", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		internal static string WriteCommon()
		{
			StringBuilder stringBuilder = new StringBuilder();
			Head(stringBuilder, "Hypnogoogic mods report");
			Plugins(stringBuilder);
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null && IsHypnogoogic(p.Metadata.GUID)).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.Name, StringComparer.OrdinalIgnoreCase))
			{
				ChangedSettings(stringBuilder, item.Instance.Config, item.Metadata.Name + " " + item.Metadata.Version);
			}
			Action<StringBuilder>[] array = Extra.ToArray();
			foreach (Action<StringBuilder> action in array)
			{
				try
				{
					action(stringBuilder);
				}
				catch (Exception ex)
				{
					stringBuilder.AppendLine("(a report section failed: " + ex.Message + ")");
				}
			}
			RecentLog(stringBuilder);
			return Write("Hypnogoogic-report.txt", stringBuilder.ToString());
		}

		internal static string Write(string fileName, string text)
		{
			string text2 = Path.Combine(Paths.BepInExRootPath, fileName);
			File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			return text2;
		}
	}
	internal static class Prefabs
	{
		private static Dictionary<int, GameObject> Named(ZNetScene scene)
		{
			return (Dictionary<int, GameObject>)AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs").GetValue(scene);
		}

		internal static void RegisterScene(ZNetScene scene, GameObject prefab)
		{
			Dictionary<int, GameObject> dictionary = Named(scene);
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name);
			if (dictionary.ContainsKey(stableHashCode))
			{
				throw new InvalidOperationException("Prefab name collision: " + ((Object)prefab).name);
			}
			dictionary.Add(stableHashCode, prefab);
			scene.m_prefabs.Add(prefab);
		}

		internal static void Replace(ZNetScene scene, GameObject prefab)
		{
			Named(scene)[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab;
			if (!scene.m_prefabs.Contains(prefab))
			{
				scene.m_prefabs.Add(prefab);
			}
		}

		internal static PieceTable Hammer(ZNetScene scene)
		{
			GameObject val = (((Object)(object)scene != (Object)null) ? scene.GetPrefab("Hammer") : null);
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.m_itemData.m_shared.m_buildPieces;
		}

		internal static void AddToHammer(PieceTable table, GameObject prefab)
		{
			if (!((Object)(object)table == (Object)null) && !((Object)(object)prefab == (Object)null))
			{
				table.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name == ((Object)prefab).name);
				table.m_pieces.Add(prefab);
			}
		}
	}
	internal static class StateFile
	{
		internal static class WorldCopy
		{
			internal static Func<bool> Applies = () => false;

			internal static Func<bool> Ready = () => false;

			internal static Func<string, string[]> Read = (string name) => (string[])null;

			internal static Func<string, DateTime> Stamp = (string name) => DateTime.MinValue;

			internal static Func<string, string[], bool> Write = (string name, string[] lines) => false;

			internal static Func<List<string>> Names = () => new List<string>();
		}

		internal sealed class Source
		{
			internal string Label;

			internal string[] Lines;

			internal DateTime Stamp;

			internal bool IsWorld;
		}

		internal static Action<string> Info = delegate
		{
		};

		internal static Action<string> Warn = delegate
		{
		};

		private const int KeepBackups = 7;

		private const string MirrorFolder = "HypnoCode-state";

		private const string LatestName = "latest";

		private const double LatestEverySeconds = 60.0;

		private static readonly Dictionary<string, DateTime> latestAt = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);

		private static readonly object Gate = new object();

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

		private static readonly HashSet<string> reconciled = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> warned = new HashSet<string>();

		internal static Func<string> SaveRoot = DefaultSaveRoot;

		internal static Func<string> GameRoot = DefaultGameRoot;

		internal const double WorldNewerBySeconds = 120.0;

		internal static string Folder(string mod)
		{
			string text = Path.Combine(Paths.BepInExRootPath, "data", mod);
			Directory.CreateDirectory(text);
			return text;
		}

		private static void WarnOnce(string key, string text)
		{
			if (warned.Add(key))
			{
				Warn(text);
			}
		}

		private static string DefaultSaveRoot()
		{
			try
			{
				string saveDataPath = Utils.GetSaveDataPath((FileSource)2);
				if (!string.IsNullOrEmpty(saveDataPath))
				{
					return saveDataPath;
				}
			}
			catch (Exception ex)
			{
				WarnOnce("saveroot", "State file copy beside the saves: the game's save path is not available (" + ex.Message + "); trying the default data path.");
			}
			try
			{
				string persistantDataPath = Utils.persistantDataPath;
				if (!string.IsNullOrEmpty(persistantDataPath))
				{
					return persistantDataPath;
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static string DefaultGameRoot()
		{
			try
			{
				string bepInExRootPath = Paths.BepInExRootPath;
				if (string.IsNullOrEmpty(bepInExRootPath))
				{
					return null;
				}
				string directoryName = Path.GetDirectoryName(bepInExRootPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
				return string.IsNullOrEmpty(directoryName) ? null : directoryName;
			}
			catch (Exception ex)
			{
				WarnOnce("gameroot", "State file copy in the game folder: the folder is not known (" + ex.Message + ").");
				return null;
			}
		}

		private static List<string> MirrorRoots()
		{
			List<string> list = new List<string>();
			Func<string>[] array = new Func<string>[2] { SaveRoot, GameRoot };
			foreach (Func<string> func in array)
			{
				string text = null;
				try
				{
					text = func();
				}
				catch (Exception ex)
				{
					WarnOnce("root:" + ex.Message, "State file copy: a folder could not be resolved (" + ex.Message + ").");
				}
				if (!string.IsNullOrEmpty(text))
				{
					string root = Path.Combine(text, "HypnoCode-state");
					if (!list.Any((string r) => string.Equals(r, root, StringComparison.OrdinalIgnoreCase)))
					{
						list.Add(root);
					}
				}
			}
			if (list.Count == 0)
			{
				WarnOnce("noroots", "State files have NO copy outside BepInEx/data (neither the save folder nor the game folder could be resolved): the state is only as safe as BepInEx/data on this server.");
			}
			return list;
		}

		private static List<string> MirrorPaths(string path)
		{
			string mod = Path.GetFileName(Path.GetDirectoryName(path));
			string file = Path.GetFileName(path);
			return (from r in MirrorRoots()
				select Path.Combine(r, mod, file)).ToList();
		}

		internal static string PathOf(string mod, string file)
		{
			string text = Path.Combine(Folder(mod), file);
			MoveOld(Path.Combine(Paths.ConfigPath, file), text);
			MoveOld(Path.Combine(Paths.ConfigPath, file + ".bak"), text + ".bak");
			return text;
		}

		private static void MoveOld(string old, string path)
		{
			try
			{
				if (!File.Exists(path) && File.Exists(old))
				{
					File.Copy(old, path);
					string text = old + ".moved";
					if (File.Exists(text))
					{
						File.Delete(text);
					}
					File.Move(old, text);
					Info("State file moved out of BepInEx/config: " + Path.GetFileName(old) + " -> " + path + " (the old one is kept as " + Path.GetFileName(text) + ").");
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(old) + " could not be moved (" + ex.Message + "); it is read where it is next time.");
			}
		}

		private static string[] TryRead(string file)
		{
			try
			{
				if (File.Exists(file))
				{
					return File.ReadAllLines(file);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + file + " could not be read (" + ex.Message + ").");
			}
			return null;
		}

		internal static string[] ReadLines(string path)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string> { path };
				list.AddRange(MirrorPaths(path));
				Dictionary<string, string[]> found = new Dictionary<string, string[]>();
				foreach (string item in list)
				{
					found[item] = TryRead(item);
				}
				List<string> list2 = list.Where((string p) => found[p] != null && found[p].Length != 0).ToList();
				string[] array = null;
				DateTime dateTime = DateTime.MinValue;
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
					if (flag2)
					{
						array = WorldCopy.Read(fileName);
						if (array != null)
						{
							dateTime = WorldCopy.Stamp(fileName);
						}
					}
				}
				catch (Exception ex)
				{
					flag2 = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex.Message + ").");
				}
				if (flag && !flag2)
				{
					WarnOnce("worldnotready:" + fileName, "State file " + fileName + " was read before the world was loaded: the world's copy is merged at the next read.");
				}
				DateTime dateTime2 = DateTime.MinValue;
				foreach (string item2 in list)
				{
					try
					{
						if (found[item2] != null)
						{
							DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(item2);
							if (lastWriteTimeUtc > dateTime2)
							{
								dateTime2 = lastWriteTimeUtc;
							}
						}
					}
					catch (Exception)
					{
					}
				}
				bool flag3 = array != null && array.Length != 0 && (list.All((string p) => found[p] == null) || ((list2.Count == 0) ? (dateTime > dateTime2) : (dateTime > dateTime2.AddSeconds(120.0))));
				if (flag3)
				{
					if (list2.Count == 0)
					{
						Warn("State file " + fileName + " is gone from BepInEx/data and from its copies (wiped on this server?): " + array.Length + " lines taken from the world save.");
					}
					else
					{
						Warn("State file " + fileName + ": the world's copy (" + array.Length + " lines, " + dateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC) is newer than every file (" + dateTime2.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC): the files were behind, merged.");
					}
				}
				else if (array != null && array.Length != 0 && list2.Count > 0)
				{
					Info("State file " + fileName + ": the world's copy is not newer than the files, the files are used.");
				}
				List<string[]> list3 = list2.Select((string p) => found[p]).ToList();
				if (flag3)
				{
					list3.Add(array);
				}
				List<string> merged;
				if (list3.Count > 0)
				{
					merged = Merge(list3);
				}
				else if (list.All((string p) => found[p] == null))
				{
					merged = FromBackups(path);
				}
				else
				{
					merged = new List<string>();
					string text = path + ".bak";
					if (list.Count == 1)
					{
						string[] array2 = TryRead(text);
						if (array2 != null && array2.Length != 0)
						{
							Warn("State file " + fileName + " is empty: read from " + Path.GetFileName(text) + ".");
							merged = array2.ToList();
						}
					}
				}
				if (merged.Count > 0)
				{
					foreach (string place in list)
					{
						string[] array3 = found[place];
						if (array3 != null && array3.SequenceEqual(merged))
						{
							continue;
						}
						bool flag4 = place == path;
						try
						{
							RewriteFile(place, merged);
							if (array3 == null || array3.Length == 0)
							{
								if (flag4 && list2.Count > 0)
								{
									Warn("State file " + fileName + " was missing or empty in BepInEx/data (wiped on this server?): " + merged.Count + " lines put back from " + string.Join(", ", list2.Where((string p) => p != place)) + ".");
								}
								else
								{
									Info("State file " + fileName + ": copy made in " + place + " (" + merged.Count + " lines).");
								}
							}
							else
							{
								Warn("State file " + fileName + ": the copy in " + place + " was behind (" + array3.Length + " lines, the merge of all copies has " + merged.Count + "): updated, nothing was lost.");
							}
						}
						catch (Exception ex3)
						{
							WarnOnce("repair:" + place, "State file " + fileName + ": the copy in " + place + " could not be updated (" + ex3.Message + ").");
						}
					}
				}
				if (flag2 && ((array == null) ? (merged.Count > 0) : (!array.SequenceEqual(merged))))
				{
					try
					{
						if (WorldCopy.Write(fileName, merged.ToArray()))
						{
							Info("State file " + fileName + ": the world's copy " + ((array == null) ? "made" : "updated") + " (" + merged.Count + " lines).");
						}
					}
					catch (Exception ex4)
					{
						WarnOnce("worldwrite:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex4.Message + ").");
					}
				}
				if (!flag || flag2)
				{
					reconciled.Add(path);
				}
				if (merged.Count > 0)
				{
					KeepLatest(path, found.Values.Any((string[] l) => l == null || l.Length != merged.Count));
				}
				return merged.ToArray();
			}
		}

		internal static List<Source> ReadSources(string path, out bool worldPending)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				List<Source> list2 = new List<Source>();
				foreach (string item in list)
				{
					DateTime stamp = DateTime.MinValue;
					string[] array = TryRead(item);
					if (array != null)
					{
						try
						{
							stamp = File.GetLastWriteTimeUtc(item);
						}
						catch (Exception)
						{
						}
					}
					list2.Add(new Source
					{
						Label = item,
						Lines = array,
						Stamp = stamp
					});
				}
				worldPending = false;
				try
				{
					if (WorldCopy.Applies())
					{
						if (WorldCopy.Ready())
						{
							string[] array2 = WorldCopy.Read(fileName);
							list2.Add(new Source
							{
								Label = "the world save",
								Lines = array2,
								Stamp = ((array2 == null) ? DateTime.MinValue : WorldCopy.Stamp(fileName)),
								IsWorld = true
							});
						}
						else
						{
							worldPending = true;
						}
					}
				}
				catch (Exception ex2)
				{
					worldPending = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex2.Message + ").");
				}
				return list2;
			}
		}

		internal static List<string> LinesFromBackups(string path)
		{
			lock (Gate)
			{
				return FromBackups(path);
			}
		}

		internal static bool WorldReady()
		{
			try
			{
				return WorldCopy.Applies() && WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static bool WorldNotLoadedYet()
		{
			try
			{
				return WorldCopy.Applies() && !WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static void MarkReconciled(string path)
		{
			lock (Gate)
			{
				reconciled.Add(path);
			}
		}

		private static List<string> Merge(List<string[]> sources)
		{
			int num = 0;
			for (int i = 1; i < sources.Count; i++)
			{
				if (sources[i].Length > sources[num].Length)
				{
					num = i;
				}
			}
			List<string> list = new List<string>(sources[num]);
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (string item in list)
			{
				dictionary.TryGetValue(item, out var value);
				dictionary[item] = value + 1;
			}
			for (int j = 0; j < sources.Count; j++)
			{
				if (j == num)
				{
					continue;
				}
				Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
				string[] array = sources[j];
				foreach (string text in array)
				{
					dictionary2.TryGetValue(text, out var value2);
					value2 = (dictionary2[text] = value2 + 1);
					dictionary.TryGetValue(text, out var value3);
					if (value2 > value3)
					{
						list.Add(text);
						dictionary[text] = value3 + 1;
					}
				}
			}
			return list;
		}

		private static List<string> FromBackups(string path)
		{
			string fileName = Path.GetFileName(path);
			string text = path + ".bak";
			string[] array = TryRead(text);
			if (array != null && array.Length != 0)
			{
				Warn("State file " + fileName + " is gone: read from " + Path.GetFileName(text) + ".");
				return array.ToList();
			}
			try
			{
				string directoryName = Path.GetDirectoryName(path);
				List<KeyValuePair<string, string>> source = Backups(directoryName);
				foreach (KeyValuePair<string, string> item in source.Where((KeyValuePair<string, string> b) => b.Key == "latest").Concat(source.Where((KeyValuePair<string, string> b) => b.Key != "latest")).ToList())
				{
					string[] array2 = null;
					foreach (string item2 in BackupLocations(directoryName, item.Key))
					{
						string[] array3 = TryRead(Path.Combine(item2, fileName));
						if (array3 != null && array3.Length != 0 && (array2 == null || array3.Length > array2.Length))
						{
							array2 = array3;
						}
					}
					if (array2 != null)
					{
						Warn("State file " + fileName + " is gone from every place: restored from the backup copy '" + item.Key + "' (" + array2.Length + " lines). Anything newer than that copy is lost.");
						return array2.ToList();
					}
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + fileName + ": the backup copies could not be searched (" + ex.Message + ").");
			}
			return new List<string>();
		}

		internal static void Append(string path, string line)
		{
			lock (Gate)
			{
				if (!reconciled.Contains(path))
				{
					ReadLines(path);
				}
				string fileName = Path.GetFileName(path);
				string contents = line + Environment.NewLine;
				bool flag = false;
				try
				{
					Directory.CreateDirectory(Path.GetDirectoryName(path));
					File.AppendAllText(path, contents);
					flag = true;
				}
				catch (Exception ex)
				{
					WarnOnce("append:" + path, "State file " + fileName + " could not be written in BepInEx/data (" + ex.Message + "); the other copies are written.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						Directory.CreateDirectory(Path.GetDirectoryName(item));
						if (File.Exists(item))
						{
							File.AppendAllText(item, contents);
						}
						else if (File.Exists(path))
						{
							File.Copy(path, item);
						}
						else
						{
							File.AppendAllText(item, contents);
						}
						flag = true;
					}
					catch (Exception ex2)
					{
						WarnOnce("append:" + item, "State file " + fileName + ": the copy in " + item + " could not be written (" + ex2.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready())
					{
						string[] array = WorldCopy.Read(fileName) ?? new string[0];
						string[] array2 = new string[array.Length + 1];
						Array.Copy(array, array2, array.Length);
						array2[array.Length] = line;
						if (WorldCopy.Write(fileName, array2))
						{
							flag = true;
						}
					}
				}
				catch (Exception ex3)
				{
					WarnOnce("worldappend:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex3.Message + ").");
				}
				if (!flag)
				{
					throw new IOException("State file " + fileName + " could not be written in any place.");
				}
				DailyBackup(path);
				KeepLatest(path, force: false);
			}
		}

		internal static void Rewrite(string path, IEnumerable<string> lines)
		{
			lock (Gate)
			{
				List<string> list = lines.ToList();
				string fileName = Path.GetFileName(path);
				bool flag = false;
				Exception ex = null;
				try
				{
					RewriteFile(path, list);
					flag = true;
				}
				catch (Exception ex2)
				{
					ex = ex2;
					WarnOnce("rewrite:" + path, "State file " + fileName + " could not be rewritten in BepInEx/data (" + ex2.Message + "); the other copies are.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						RewriteFile(item, list);
						flag = true;
					}
					catch (Exception ex3)
					{
						WarnOnce("rewrite:" + item, "State file " + fileName + ": the copy in " + item + " could not be rewritten (" + ex3.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready() && WorldCopy.Write(fileName, list.ToArray()))
					{
						flag = true;
					}
				}
				catch (Exception ex4)
				{
					WarnOnce("worldrewrite:" + fileName, "State file " + fileName + ": the world's copy could not be rewritten (" + ex4.Message + ").");
				}
				reconciled.Add(path);
				if (!flag)
				{
					throw ex ?? new IOException("State file " + fileName + " could not be rewritten in any place.");
				}
				KeepLatest(path, force: true);
			}
		}

		private static void RewriteFile(string path, IEnumerable<string> lines)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string text = path + ".tmp";
			string text2 = path + ".bak";
			File.WriteAllLines(text, lines);
			try
			{
				if (File.Exists(path))
				{
					File.Replace(text, path, text2);
				}
				else
				{
					File.Move(text, path);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(path) + ": atomic replace failed (" + ex.Message + "), copying instead.");
				if (File.Exists(path))
				{
					File.Copy(path, text2, overwrite: true);
				}
				File.Copy(text, path, overwrite: true);
				File.Delete(text);
			}
		}

		private static void KeepLatest(string path, bool force)
		{
			try
			{
				DateTime utcNow = DateTime.UtcNow;
				if (!force && latestAt.TryGetValue(path, out var value) && (utcNow - value).TotalSeconds < 60.0)
				{
					return;
				}
				latestAt[path] = utcNow;
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				foreach (string item in list)
				{
					if (File.Exists(item))
					{
						string text = Path.Combine(Path.GetDirectoryName(item), "backups", "latest");
						Directory.CreateDirectory(text);
						File.Copy(item, Path.Combine(text, fileName), overwrite: true);
					}
				}
			}
			catch (Exception ex)
			{
				WarnOnce("latest", "State files: the rolling backup copy could not be written (" + ex.Message + ").");
			}
		}

		private static List<string> BackupRoots(string dir)
		{
			string mod = Path.GetFileName(dir);
			List<string> list = new List<string>();
			list.Add(Path.Combine(dir, "backups"));
			list.AddRange(from r in MirrorRoots()
				select Path.Combine(r, mod, "backups"));
			return list;
		}

		private static List<string> BackupLocations(string dir, string name)
		{
			return (from r in BackupRoots(dir)
				select Path.Combine(r, name)).Where(Directory.Exists).ToList();
		}

		private static long SizeOf(string folder)
		{
			try
			{
				return Directory.GetFiles(folder).Sum((string f) => new FileInfo(f).Length);
			}
			catch (Exception)
			{
				return 0L;
			}
		}

		internal static void DailyBackup(string path)
		{
			lock (Gate)
			{
				try
				{
					string directoryName = Path.GetDirectoryName(path);
					if (string.IsNullOrEmpty(directoryName))
					{
						return;
					}
					string text = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
					if (backedUpOn.TryGetValue(directoryName, out var value) && value == text)
					{
						return;
					}
					string fileName = Path.GetFileName(directoryName);
					bool flag = BackupInto(directoryName, text);
					foreach (string item in MirrorRoots())
					{
						BackupInto(Path.Combine(item, fileName), text);
					}
					if (flag)
					{
						backedUpOn[directoryName] = text;
					}
				}
				catch (Exception ex)
				{
					Warn("Daily backup of the state files failed (" + ex.Message + ").");
				}
			}
		}

		private static bool BackupInto(string folder, string name)
		{
			if (!Directory.Exists(folder))
			{
				return false;
			}
			string text = Path.Combine(folder, "backups");
			string text2 = Path.Combine(text, name);
			if (Directory.Exists(text2))
			{
				return true;
			}
			string[] array = (from f in Directory.GetFiles(folder)
				where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
				select f).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			Directory.CreateDirectory(text2);
			string[] array2 = array;
			foreach (string text3 in array2)
			{
				File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
			}
			array2 = (from d in Directory.GetDirectories(text)
				where IsDaily(Path.GetFileName(d))
				select d).OrderByDescending<string, string>((string d) => Path.GetFileName(d), StringComparer.Ordinal).Skip(7).ToArray();
			for (int num = 0; num < array2.Length; num++)
			{
				Directory.Delete(array2[num], recursive: true);
			}
			Info("State files backed up to " + text2 + " (" + array.Length + " files, the " + 7 + " newest days are kept).");
			return true;
		}

		private static bool IsDaily(string name)
		{
			DateTime result;
			if (name.Length == 10)
			{
				return DateTime.TryParseExact(name, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
			}
			return false;
		}

		private static bool IsStateFile(string path)
		{
			string fileName = Path.GetFileName(path);
			if (!fileName.EndsWith(".bak", StringComparison.OrdinalIgnoreCase) && !fileName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
			{
				return !fileName.EndsWith(".moved", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		internal static string Snapshot(string dir, string label, out int count)
		{
			lock (Gate)
			{
				count = 0;
				string text = label + "-" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
				string mod = Path.GetFileName(dir);
				List<string> list = new List<string>();
				list.Add(dir);
				list.AddRange(from r in MirrorRoots()
					select Path.Combine(r, mod));
				foreach (string item in list)
				{
					if (!Directory.Exists(item))
					{
						continue;
					}
					string[] array = (from f in Directory.GetFiles(item)
						where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
						select f).ToArray();
					if (array.Length != 0)
					{
						string text2 = Path.Combine(item, "backups", text);
						Directory.CreateDirectory(text2);
						string[] array2 = array;
						foreach (string text3 in array2)
						{
							File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
						}
						count = Math.Max(count, array.Length);
						Info("State files copied to " + text2 + " (" + array.Length + " files).");
					}
				}
				return text;
			}
		}

		internal static List<KeyValuePair<string, string>> Backups(string dir)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
			foreach (string item in BackupRoots(dir))
			{
				if (!Directory.Exists(item))
				{
					continue;
				}
				string[] directories = Directory.GetDirectories(item);
				foreach (string path in directories)
				{
					string fileName = Path.GetFileName(path);
					DateTime lastWriteTime = Directory.GetLastWriteTime(path);
					if (!dictionary.TryGetValue(fileName, out var value) || lastWriteTime > value)
					{
						dictionary[fileName] = lastWriteTime;
					}
				}
			}
			foreach (KeyValuePair<string, DateTime> item2 in dictionary.OrderByDescending((KeyValuePair<string, DateTime> p) => p.Value))
			{
				int num = (from l in BackupLocations(dir, item2.Key)
					select Directory.GetFiles(l).Count(IsStateFile)).DefaultIfEmpty(0).Max();
				list.Add(new KeyValuePair<string, string>(item2.Key, item2.Value.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + ", " + num + " state files"));
			}
			return list;
		}

		internal static int RestoreFrom(string dir, string backupName)
		{
			if (string.IsNullOrEmpty(backupName) || backupName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || backupName.Contains(".."))
			{
				return -1;
			}
			List<string> list = BackupLocations(dir, backupName);
			if (list.Count == 0)
			{
				return -1;
			}
			string text = list.OrderByDescending(SizeOf).First();
			int num = 0;
			foreach (string item in Directory.GetFiles(text).Where(IsStateFile))
			{
				Rewrite(Path.Combine(dir, Path.GetFileName(item)), File.ReadAllLines(item));
				num++;
			}
			Info("State files restored from " + text + " (" + num + " files).");
			return num;
		}

		private static string Brief(string file)
		{
			try
			{
				if (!File.Exists(file))
				{
					return "MISSING";
				}
				FileInfo fileInfo = new FileInfo(file);
				return File.ReadAllLines(file).Length + " lines, " + fileInfo.Length + " B, " + fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
			}
			catch (Exception ex)
			{
				return "unreadable (" + ex.Message + ")";
			}
		}

		internal static List<string> Describe(string mod)
		{
			lock (Gate)
			{
				List<string> list = new List<string>();
				string text = Folder(mod);
				List<string> list2 = MirrorRoots();
				list.Add("Copies of the state files (reading merges all of them, every write goes to all):");
				list.Add("  data:   " + text);
				foreach (string item in list2)
				{
					list.Add("  copy:   " + Path.Combine(item, mod));
				}
				if (list2.Count == 0)
				{
					list.Add("  WARNING: no copy outside BepInEx/data (the save folder and the game folder could not be resolved).");
				}
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
				}
				catch (Exception)
				{
				}
				list.Add("  world:  " + ((!flag) ? "not on this side (only a server or host keeps it)" : (flag2 ? "inside the world save (a persistent object far outside the map; saved with the world)" : "the world is not loaded yet")));
				List<string> list3 = new List<string>();
				list3.Add(text);
				list3.AddRange(list2.Select((string r) => Path.Combine(r, mod)));
				SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
				foreach (string item2 in list3)
				{
					if (!Directory.Exists(item2))
					{
						continue;
					}
					foreach (string item3 in Directory.GetFiles(item2).Where(IsStateFile))
					{
						sortedSet.Add(Path.GetFileName(item3));
					}
				}
				if (flag2)
				{
					try
					{
						foreach (string item4 in WorldCopy.Names())
						{
							sortedSet.Add(item4);
						}
					}
					catch (Exception ex2)
					{
						list.Add("  world copy: names could not be read (" + ex2.Message + ")");
					}
				}
				foreach (string item5 in sortedSet)
				{
					List<string> list4 = new List<string> { "data " + Brief(Path.Combine(text, item5)) };
					for (int num = 0; num < list2.Count; num++)
					{
						list4.Add("copy" + (num + 1) + " " + Brief(Path.Combine(list2[num], mod, item5)));
					}
					if (flag2)
					{
						try
						{
							string[] array = WorldCopy.Read(item5);
							list4.Add((array == null) ? "world MISSING" : ("world " + array.Length + " lines, " + WorldCopy.Stamp(item5).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC"));
						}
						catch (Exception ex3)
						{
							list4.Add("world unreadable (" + ex3.Message + ")");
						}
					}
					list.Add("  " + item5 + ": " + string.Join(" | ", list4));
				}
				List<KeyValuePair<string, string>> list5 = Backups(text);
				list.Add("  backups: " + list5.Count + ((list5.Count > 0) ? (" (newest " + list5[0].Key + ")") : "") + " - 'it backup list'");
				return list;
			}
		}

		internal static void ForgetReconciled()
		{
			lock (Gate)
			{
				reconciled.Clear();
			}
		}

		internal static void ForgetForTests()
		{
			lock (Gate)
			{
				backedUpOn.Clear();
				reconciled.Clear();
				warned.Clear();
				latestAt.Clear();
			}
		}
	}
	internal static class UiKit
	{
		internal static Action<string> Warn = delegate
		{
		};

		internal static readonly Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		internal static Sprite panelSprite;

		internal static Type panelType;

		internal static Color panelColor = new Color(0.25f, 0.17f, 0.1f, 0.97f);

		internal static float panelPpu = 1f;

		internal static Material panelMaterial;

		internal static Button buttonTemplate;

		internal static TMP_FontAsset font;

		internal static TMP_FontAsset titleFont;

		internal static Color titleColor = new Color(1f, 0.63f, 0.235f);

		internal static Color bodyColor = new Color(0.98f, 0.95f, 0.9f);

		internal static bool skin;

		internal static Sprite flat;

		internal static TMP_FontAsset BodyFont()
		{
			if ((Object)(object)font == (Object)null)
			{
				Discover();
			}
			return font;
		}

		internal static RectTransform Rect(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) })
			{
				layer = LayerMask.NameToLayer("UI")
			}.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			component.anchorMin = aMin;
			component.anchorMax = aMax;
			component.offsetMin = oMin;
			component.offsetMax = oMax;
			return component;
		}

		internal static Image Box(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			return obj;
		}

		internal static Sprite FindSprite(string name)
		{
			if (sprites.TryGetValue(name, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			value = null;
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name == name)
				{
					value = val;
					break;
				}
			}
			sprites[name] = value;
			return value;
		}

		internal static bool Draws(TMP_FontAsset f)
		{
			if ((Object)(object)f == (Object)null)
			{
				return false;
			}
			try
			{
				return f.HasCharacter('A', true, true) && f.HasCharacter('g', true, true) && f.HasCharacter('7', true, true);
			}
			catch
			{
				return false;
			}
		}

		internal static void Discover()
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			skin = false;
			panelSprite = null;
			buttonTemplate = null;
			InventoryGui instance = InventoryGui.instance;
			TMP_FontAsset val = null;
			try
			{
				val = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null) ? instance.m_recipeDecription.font : null);
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null)
				{
					bodyColor = ((Graphic)instance.m_recipeDecription).color;
				}
			}
			catch
			{
			}
			try
			{
				titleFont = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeName != (Object)null && Draws(instance.m_recipeName.font)) ? instance.m_recipeName.font : null);
			}
			catch
			{
				titleFont = null;
			}
			TMP_FontAsset val2 = (Draws(val) ? val : null);
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val3 in array)
				{
					if ((Object)(object)val3 != (Object)null && ((Object)val3).name.IndexOf("Averia", StringComparison.OrdinalIgnoreCase) >= 0 && Draws(val3))
					{
						val2 = val3;
						break;
					}
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				try
				{
					TMP_FontAsset defaultFontAsset = TMP_Settings.defaultFontAsset;
					if (Draws(defaultFontAsset))
					{
						val2 = defaultFontAsset;
					}
				}
				catch
				{
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val4 in array)
				{
					if (Draws(val4))
					{
						val2 = val4;
						break;
					}
				}
			}
			font = val2 ?? val;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_crafting == (Object)null)
			{
				return;
			}
			try
			{
				List<Image> list = ((Component)instance.m_crafting).GetComponentsInChildren<Image>(true).ToList();
				Transform parent = ((Transform)instance.m_crafting).parent;
				int num = 0;
				while (num < 3 && (Object)(object)parent != (Object)null)
				{
					Image component = ((Component)parent).GetComponent<Image>();
					if ((Object)(object)component != (Object)null)
					{
						list.Add(component);
					}
					num++;
					parent = parent.parent;
				}
				Func<Image, bool> bad = delegate(Image val6)
				{
					string text = (((Object)val6).name + " " + ((Object)val6.sprite).name).ToLowerInvariant();
					string[] array2 = new string[12]
					{
						"darken", "blob", "shadow", "glow", "select", "icon", "scroll", "handle", "bar", "highlight",
						"button", "tab"
					};
					foreach (string value in array2)
					{
						if (text.Contains(value))
						{
							return true;
						}
					}
					return false;
				};
				Image val5 = list.Where((Image val6) => (Object)(object)val6.sprite != (Object)null && !bad(val6) && ((Graphic)val6).color.a > 0.5f).OrderByDescending(delegate(Image val6)
				{
					//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_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					Rect rect = ((Graphic)val6).rectTransform.rect;
					float width = ((Rect)(ref rect)).width;
					rect = ((Graphic)val6).rectTransform.rect;
					return width * ((Rect)(ref rect)).height;
				}).FirstOrDefault();
				if ((Object)(object)val5 != (Object)null)
				{
					panelSprite = val5.sprite;
					panelType = val5.type;
					panelColor = ((Graphic)val5).color;
					panelPpu = val5.pixelsPerUnitMultiplier;
					panelMaterial = ((Graphic)val5).material;
				}
				buttonTemplate = instance.m_craftButton;
				skin = (Object)(object)val5 != (Object)null;
			}
			catch (Exception ex)
			{
				Warn("HypnoCode: the game's skin was not found (" + ex.Message + "), plain colours are used.");
			}
		}

		internal static TMP_Text Label(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, float size, Color color, TextAlignmentOptions align, bool ellipsis = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject;
			gameObject.SetActive(false);
			TextMeshProUGUI val = gameObject.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)val).font = font;
			}
			((TMP_Text)val).text = text;
			((TMP_Text)val).fontSize = size;
			((Graphic)val).color = color;
			((TMP_Text)val).alignment = align;
			((Graphic)val).raycastTarget = false;
			((TMP_Text)val).enableWordWrapping = false;
			((TMP_Text)val).overflowMode = (TextOverflowModes)(ellipsis ? 1 : 0);
			gameObject.SetActive(true);
			return (TMP_Text)(object)val;
		}

		internal static bool Keep(Component c)
		{
			if (!(c is Graphic) && !(c is Selectable) && !(c is Mask) && !(c is RectMask2D) && !(c is LayoutGroup) && !(c is ContentSizeFitter) && !(c is LayoutElement))
			{
				return c is BaseMeshEffect;
			}
			return true;
		}

		internal static Button MakeButton(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, Color colour, Action click, out TMP_Text labelOut, float size = 30f, bool edge = false)
		{
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: 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_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			Image val2;
			Button val3;
			if (skin && (Object)(object)buttonTemplate != (Object)null)
			{
				GameObject val = Object.Instantiate<GameObject>(((Component)buttonTemplate).gameObject, parent, false);
				((Object)val).name = name;
				val.SetActive(true);
				ColorBlock colors = ((Selectable)buttonTemplate).colors;
				Transition transition = ((Selectable)buttonTemplate).transition;
				SpriteState spriteState = ((Selectable)buttonTemplate).spriteState;
				foreach (MonoBehaviour item in val.GetComponentsInChildren<MonoBehaviour>(true).ToList())
				{
					if ((Object)(object)item != (Object)null && !Keep((Component)(object)item))
					{
						Object.DestroyImmediate((Object)(object)item);
					}
				}
				foreach (Selectable item2 in val.GetComponentsInChildren<Selectable>(true).ToList())
				{
					if ((Object)(object)item2 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)item2);
					}
				}
				val2 = val.GetComponent<Image>();
				val3 = val.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
				((Selectable)val3).transition = transition;
				((Selectable)val3).colors = colors;
				((Selectable)val3).spriteState = spriteState;
				TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.SetActive(false);
				}
				RectTransform val4 = (RectTransform)val.transform;
				val4.anchorMin = aMin;
				val4.anchorMax = aMax;
				val4.offsetMin = oMin;
				val4.offsetMax = oMax;
			}
			else
			{
				val2 = Box(name, parent, aMin, aMax, oMin, oMax, new Color(0.1f, 0.07f, 0.04f, 0.9f));
				val3 = ((Component)val2).gameObject.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			}
			((UnityEvent)val3.onClick).AddListener((UnityAction)delegate
			{
				ClickSound();
				click();
			});
			TMP_Text val5 = Label("text", ((Component)val2).transform, Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero, text, size, colour, (TextAlignmentOptions)514);
			GameObject edge2 = null;
			RectTransform val6;
			if (edge)
			{
				val6 = Rect("edge", ((Component)val3).transform, Vector2.zero, Vector2.one, new Vector2(-1f, -1f), new Vector2(1f, 1f));
				Image val7 = ((Component)val6).gameObject.AddComponent<Image>();
				((Graphic)val7).raycastTarget = false;
				Sprite val8 = FindSprite("selection_frame");
				if ((Object)(object)val8 != (Object)null)
				{
					Vector4 border = val8.border;
					if (((Vector4)(ref border)).sqrMagnitude > 0f)
					{
						val7.sprite = val8;
						val7.type = (Type)1;
						((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0.95f);
						goto IL_033e;
					}
				}
				((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0f);
				Outline obj = ((Component)val6).gameObject.AddComponent<Outline>();
				((Shadow)obj).effectColor = new Color(colour.r, colour.g, colour.b, 0.9f);
				((Shadow)obj).effectDistance = new Vector2(2f, -2f);
				goto IL_033e;
			}
			goto IL_034e;
			IL_033e:
			((Transform)val6).SetAsFirstSibling();
			edge2 = ((Component)val6).gameObject;
			goto IL_034e;
			IL_034e:
			UiButtonTint uiButtonTint = ((Component)val3).gameObject.AddComponent<UiButtonTint>();
			uiButtonTint.Target = val3;
			uiButtonTint.Label = val5;
			uiButtonTint.Colour = colour;
			uiButtonTint.Edge = edge2;
			labelOut = val5;
			return val3;
		}

		internal static void ClickSound()
		{
			//IL_0041: 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)
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("sfx_gui_button") : null);
			if ((Object)(object)val != (Object)null && (Object)(object)Utils.GetMainCamera() != (Object)null)
			{
				Object.Instantiate<GameObject>(val, ((Component)Utils.GetMainCamera()).transform.position, Quaternion.identity);
			}
		}

		internal static Sprite FlatSprite()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)flat != (Object)null)
			{
				return flat;
			}
			Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false)
			{
				hideFlags = (HideFlags)61
			};
			Color32[] array = (Color32[])(object)new Color32[16];
			for (int i = 0; i < 16; i++)
			{
				array[i] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
			}
			val.SetPixels32(array);
			val.Apply(false, true);
			flat = Sprite.Create(val, new Rect(0f, 0f, 4f, 4f), new Vector2(0.5f, 0.5f), 100f);
			((Object)flat).hideFlags = (HideFlags)61;
			return flat;
		}
	}
	public sealed class UiButtonTint : MonoBehaviour
	{
		public Button Target;

		public TMP_Text Label;

		public Color Colour;

		public GameObject Edge;

		private void Update()
		{
			//IL_004e: 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)
			if (!((Object)(object)Target == (Object)null))
			{
				bool interactable = ((Selectable)Target).interactable;
				if ((Object)(object)Label != (Object)null)
				{
					((Graphic)Label).color = (Color)(interactable ? Colour : new Color(0.5f, 0.48f, 0.45f, 1f));
				}
				if ((Object)(object)Edge != (Object)null && Edge.activeSelf != interactable)
				{
					Edge.SetActive(interactable);
				}
			}
		}
	}
}
namespace HypnoCode.Crafting
{
	internal static class Icons
	{
		private static Texture2D Readable(Texture source)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)0);
			Graphics.Blit(source, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(source.width, source.height, (TextureFormat)4, false);
			val.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		internal static Sprite WhiteOf(Sprite source)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Expected O, but got Unknown
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			Rect textureRect = source.textureRect;
			int num = (int)((Rect)(ref textureRect)).x;
			int num2 = (int)((Rect)(ref textureRect)).y;
			int num3 = (int)((Rect)(ref textureRect)).width;
			int num4 = (int)((Rect)(ref textureRect)).height;
			Texture2D obj = Readable((Texture)(object)source.texture);
			Color[] pixels = obj.GetPixels(num, num2, num3, num4);
			Object.Destroy((Object)(object)obj);
			for (int i = 0; i < pixels.Length; i++)
			{
				Color val = pixels[i];
				float num5 = Mathf.Clamp01(0.5f + 0.6f * (0.299f * val.r + 0.587f * val.g + 0.114f * val.b));
				pixels[i] = new Color(num5, num5, num5, val.a);
			}
			Texture2D val2 = new Texture2D(num3, num4, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)1,
				hideFlags = (HideFlags)61
			};
			val2.SetPixels(pixels);
			val2.Apply();
			Sprite obj2 = Sprite.Create(val2, new Rect(0f, 0f, (float)num3, (float)num4), new Vector2(0.5f, 0.5f), 100f);
			((Object)obj2).hideFlags = (HideFlags)61;
			return obj2;
		}
	}
	internal sealed class Page
	{
		internal Func<string> Topic = () => "";

		internal Func<string> Text = () => "";

		internal Func<Sprite> Icon;

		internal bool AsIs;

		internal Func<Recipe, bool> Has = (Recipe recipe) => true;

		internal static bool IsArmor(Recipe recipe)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			ItemType val = (ItemType)((!((Object)(object)recipe.m_item != (Object)null)) ? 1 : ((int)recipe.m_item.m_itemData.m_shared.m_itemType));
			if ((int)val != 6 && (int)val != 7 && (int)val != 11)
			{
				return (int)val == 17;
			}
			return true;
		}
	}
	internal sealed class RecipeDef
	{
		internal string Key;

		internal ItemDrop Result;

		internal ItemDrop Ingredient;

		internal int Amount = 1;

		internal ItemDrop[] Ingredients;

		internal bool OnlyOne;

		internal bool Known;

		internal bool Silent;

		internal int ResultAmount = 1;

		internal Func<Player, bool> Allowed;
	}
	internal sealed class StationDef
	{
		internal string Name;

		internal Func<Sprite> Icon;

		internal float UseDistance = 3f;

		internal float DiscoverRange = 6f;

		internal Func<CraftingStation, Player, string> Refusal;

		internal Func<CraftingStation, string> HoverNote;

		internal Page[] Pages = new Page[0];

		internal int DefaultPage;

		internal string RecipePrefix = "HC_";

		internal Func<ObjectDB, IEnumerable<RecipeDef>> Recipes;
	}
	internal static class Stations
	{
		[HarmonyPatch(typeof(Player), "AddKnownRecipe", new Type[] { typeof(Recipe) })]
		internal static class SilentKnownPatch
		{
			private static bool Prefix(Player __instance, Recipe recipe)
			{
				if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || (!KnownAlways.Contains(recipe) && !SilentRecipes.Contains(recipe)) || KnownRecipes == null)
				{
					return true;
				}
				if (!(KnownRecipes.GetValue(__instance) is HashSet<string> hashSet))
				{
					return true;
				}
				hashSet.Add(recipe.m_item.m_itemData.m_shared.m_name);
				return false;
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		internal static class ObjectDbAwakePatch
		{
			[HarmonyPriority(0)]
			private static void Postfix(ObjectDB __instance)
			{
				try
				{
					Rebuild(__instance);
				}
				catch (Exception ex)
				{
					if (Log != null)
					{
						Log.LogError((object)("Station recipes failed: " + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		internal static class ObjectDbCopyPatch
		{
			[HarmonyPriority(0)]
			private static void Postfix(ObjectDB __instance)
			{
				try
				{
					Rebuild(__instance);
				}
				catch (Exception ex)
				{
					if (Log != null)
					{
						Log.LogError((object)("Station recipes failed: " + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned", new Type[] { typeof(bool) })]
		internal static class SpawnedPatch
		{
			private static void Postfix(Player __instance)
			{
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)ObjectDB.instance == (Object)null)
				{
					return;
				}
				try
				{
					Rebuild(ObjectDB.instance);
				}
				catch (Exception ex)
				{
					if (Log != null)
					{
						Log.LogError((object)("Station recipes failed: " + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "AddKnownItem")]
		internal static class KnownItemPatch
		{
			private static void Postfix(Player __instance, ItemData item)
			{
				try
				{
					Learn(__instance, item);
				}
				catch (Exception ex)
				{
					LogLimit.Warn(Log, "station.learn", "Station recipes: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(Player), "GetAvailableRecipes")]
		internal static class AvailablePatch
		{
			private static void Prefix(Player __instance)
			{
				if (KnownAlways.Count == 0 || KnownRecipes == null || !(KnownRecipes.GetValue(__instance) is HashSet<string> hashSet))
				{
					return;
				}
				foreach (Recipe knownAlway in KnownAlways)
				{
					if ((Object)(object)knownAlway != (Object)null && (Object)(object)knownAlway.m_item != (Object)null)
					{
						hashSet.Add(knownAlway.m_item.m_itemData.m_shared.m_name);
					}
				}
			}

			private static void Postfix(Player __instance, ref List<Recipe> available)
			{
				if (Ingredient.Count > 0 && !__instance.NoCostCheat())
				{
					available.RemoveAll((Recipe r) => (Object)(object)r != (Object)null && Ingredient.TryGetValue(r, out var value) && !__instance.IsMaterialKnown(value));
				}
				if (Ours(__instance, out var def) && def.Pages.Length != 0)
				{
					available.RemoveAll((Recipe r) => !Tabs.Shows(def, r));
				}
				if (Gates.Count > 0 && Ours(__instance, out def) && !__instance.NoCostCheat())
				{
					available.RemoveAll((Recipe r) => (Object)(object)r != (Object)null && Gates.TryGetValue(r, out var value) && !value(__instance));
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		internal static class DoCraftingPatch
		{
			private static readonly MethodInfo GetZdo = AccessTools.Method(typeof(ZNetView), "GetZDO", (Type[])null, (Type[])null);

			private static readonly MethodInfo GetBool = AccessTools.Method(typeof(ZDO), "GetBool", new Type[2]
			{
				typeof(int),
				typeof(bool)
			}, (Type[])null);

			private static readonly Type CheatUtils = AccessTools.TypeByName("CheatUtils");

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

			private static readonly Func<ZDO, bool> RealIsCheated = ((IsCheated != null) ? ((Func<ZDO, bool>)Delegate.CreateDelegate(typeof(Func<ZDO, bool>), IsCheated)) : null);

			private static readonly MethodInfo SafeZdo = AccessTools.Method(typeof(DoCraftingPatch), "ZdoOf", (Type[])null, (Type[])null);

			private static readonly MethodInfo SafeBool = AccessTools.Method(typeof(DoCraftingPatch), "BoolOf", (Type[])null, (Type[])null);

			private static readonly MethodInfo SafeCheated = AccessTools.Method(typeof(DoCraftingPatch), "CheatedOf", (Type[])null, (Type[])null);

			internal static ZDO ZdoOf(ZNetView view)
			{
				if (!((Object)(object)view != (Object)null))
				{
					return null;
				}
				return view.GetZDO();
			}

			internal static bool BoolOf(ZDO zdo, int hash, bool fallback)
			{
				if (zdo == null)
				{
					return fallback;
				}
				return zdo.GetBool(hash, fallback);
			}

			internal static bool CheatedOf(ZDO zdo)
			{
				if (zdo != null && RealIsCheated != null)
				{
					return RealIsCheated(zdo);
				}
				return false;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code)
			{
				int changed = 0;
				foreach (CodeInstruction item in code)
				{
					if (CodeInstructionExtensions.Calls(item, GetZdo))
					{
						item.opcode = OpCodes.Call;
						item.operand = SafeZdo;
						changed++;
					}
					else if (CodeInstructionExtensions.Calls(item, GetBool))
					{
						item.opcode = OpCodes.Call;
						item.operand = SafeBool;
						changed++;
					}
					else if (IsCheated != null && CodeInstructionExtensions.Calls(item, IsCheated))
					{
						item.opcode = OpCodes.Call;
						item.operand = SafeCheated;
						changed++;
					}
					yield return item;
				}
				if (Log != null)
				{
					((changed == 2) ? new Action<string>(Log.LogDebug) : new Action<string>(Log.LogWarning))("Station crafting: " + changed + " calls of DoCrafting made safe for a station without a network object (expected 2).");
				}
			}
		}

		[HarmonyPatch(typeof(CraftingStation), "CheckUsable")]
		internal static class UsablePatch
		{
			private static void Postfix(CraftingStation __instance, Player player, bool showMessage, ref bool __result)
			{
				if (!__result || !Defs.TryGetValue(__instance.m_name, out var value) || value.Refusal == null || player.NoCostCheat())
				{
					return;
				}
				string text = value.Refusal(__instance, player);
				if (text != null)
				{
					__result = false;
					if (showMessage && text.Length > 0)
					{
						((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false);
					}
				}
			}
		}

		[HarmonyPatch(typeof(CraftingStation), "GetHoverText")]
		internal static class HoverPatch
		{
			private static void Postfix(CraftingStation __instance, ref string __result)
			{
				if (Defs.TryGetValue(__instance.m_name, out var value) && value.HoverNote != null && !((Object)(object)Player.m_localPlayer == (Object)null))
				{
					string text = value.HoverNote(__instance);
					if (!string.IsNullOrEmpty(text))
					{
						__result = __result + "\n<color=#888888>" + text + "</color>";
					}
				}
			}
		}

		internal static ManualLogSource Log;

		private static readonly Dictionary<string, StationDef> Defs = new Dictionary<string, StationDef>();

		private static readonly Dictionary<Recipe, string> Ingredient = new Dictionary<Recipe, string>();

		private static readonly List<Recipe> KnownAlways = new List<Recipe>();

		private static readonly HashSet<Recipe> SilentRecipes = new HashSet<Recipe>();

		private static readonly FieldInfo KnownRecipes = AccessTools.Field(typeof(Player), "m_knownRecipes");

		private static readonly Dictionary<Recipe, Func<Player, bool>> Gates = new Dictionary<Recipe, Func<Player, bool>>();

		private static readonly Dictionary<string, CraftingStation> Holders = new Dictionary<string, CraftingStation>();

		private static readonly MethodInfo AddKnownRecipe = AccessTools.Method(typeof(Player), "AddKnownRecipe", new Type[1] { typeof(Recipe) }, (Type[])null);

		internal static IEnumerable<StationDef> All => Defs.Values;

		internal static void Register(StationDef def)
		{
			Defs[def.Name] = def;
		}

		internal static bool Find(string name, out StationDef def)
		{
			return Defs.TryGetValue(name ?? "", out def);
		}

		internal static bool Ours(Player player, out StationDef def)
		{
			def = null;
			CraftingStation val = (((Object)(object)player != (Object)null) ? player.GetCurrentCraftingStation() : null);
			if ((Object)(object)val != (Object)null)
			{
				return Defs.TryGetValue(val.m_name, out def);
			}
			return false;
		}

		private static CraftingStation Configure(CraftingStation station, StationDef def)
		{
			station.m_name = def.Name;
			station.m_icon = ((def.Icon != null) ? def.Icon() : null);
			station.m_craftRequireRoof = false;
			station.m_craftRequireFire = false;
			station.m_showBasicRecipies = false;
			station.m_canRepair = false;
			station.m_hasCraftTab = true;
			station.m_upgrader = false;
			station.m_rangeBuild = 0f;
			station.m_discoverRange = def.DiscoverRange;
			station.m_useDistance = def.UseDistance;
			return station;
		}

		internal static void Attach(GameObject copy, string name)
		{
			if (Defs.TryGetValue(name, out var value))
			{
				Configure(copy.GetComponent<CraftingStation>() ?? copy.AddComponent<CraftingStation>(), value);
			}
		}

		private static CraftingStation Holder(StationDef def)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			if (Holders.TryGetValue(def.Name, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			GameObject val = new GameObject("HC_Station_" + def.Name);
			val.SetActive(false);
			Object.DontDestroyOnLoad((Object)val);
			value = Configure(val.AddComponent<CraftingStation>(), def);
			Holders[def.Name] = value;
			return value;
		}

		internal static void Rebuild(ObjectDB db)
		{
			if ((Object)(object)db == (Object)null || db.m_recipes == null)
			{
				return;
			}
			foreach (StationDef value in Defs.Values)
			{
				string prefix = value.RecipePrefix;
				db.m_recipes.RemoveAll((Recipe r) => (Object)(object)r != (Object)null && ((Object)r).name.StartsWith(prefix, StringComparison.Ordinal));
				foreach (Recipe item in Ingredient.Keys.Where((Recipe r) => (Object)(object)r == (Object)null || ((Object)r).name.StartsWith(prefix, StringComparison.Ordinal)).ToList())
				{
					Ingredient.Remove(item);
					SilentRecipes.Remove(item);
					if ((Object)(object)item != (Object)null)
					{
						Gates.Remove(item);
						Object.Destroy((Object)(object)item);
					}
				}
				foreach (Recipe item2 in KnownAlways.Where((Recipe r) => (Object)(object)r == (Object)null || ((Object)r).name.StartsWith(prefix, StringComparison.Ordinal)).ToList())
				{
					KnownAlways.Remove(item2);
					if ((Object)(object)item2 != (Object)null)
					{
						Gates.Remove(item2);
						Object.Destroy((Object)(object)item2);
					}
				}
				if (value.Recipes == null)
				{
					continue;
				}
				int num = 0;
				foreach (RecipeDef d in value.Recipes(db))
				{
					ItemDrop[] array = (ItemDrop[])((d == null) ? new ItemDrop[0] : ((d.Ingredients != null && d.Ingredients.Length != 0) ? ((Array)d.Ingredients.Where((ItemDrop i) => (Object)(object)i != (Object)null).ToArray()) : ((Array)((!((Object)(object)d.Ingredient != (Object)null)) ? new ItemDrop[0] : new ItemDrop[1] { d.Ingredient }))));
					if (d != null && !((Object)(object)d.Result == (Object)null) && array.Length != 0)
					{
						Recipe val = ScriptableObject.CreateInstance<Recipe>();
						((Object)val).name = prefix + d.Key;
						val.m_item = d.Result;
						val.m_amount = Math.Max(1, d.ResultAmount);
						val.m_enabled = true;
						val.m_craftingStation = Holder(value);
						val.m_minStationLevel = 1;
						val.m_resources = ((IEnumerable<ItemDrop>)array).Select((Func<ItemDrop, Requirement>)((ItemDrop i) => new Requirement
						{
							m_resItem = i,
							m_amount = d.Amount,
							m_recover = false
						})).ToArray();
						val.m_requireOnlyOneIngredient = d.OnlyOne && array.Length > 1;
						db.m_recipes.Add(val);
						if (d.Known)
						{
							KnownAlways.Add(val);
						}
						else
						{
							Ingredient[val] = array[0].m_itemData.m_shared.m_name;
						}
						if (d.Silent)
						{
							SilentRecipes.Add(val);
						}
						if (d.Allowed != null)
						{
							Gates[val] = d.Allowed;
						}
						num++;
					}
				}
				if (Log != null)
				{
					Log.LogDebug((object)(value.Name + ": " + num + " recipes in the object database."));
				}
			}
		}

		internal static void Learn(Player player, ItemData item)
		{
			if (Ingredient.Count == 0 || item == null || item.m_shared == null || (Object)(object)player != (Object)(object)Player.m_localPlayer || AddKnownRecipe == null)
			{
				return;
			}
			string name = item.m_shared.m_name;
			foreach (KeyValuePair<Recipe, string> item2 in Ingredient.ToList())
			{
				if ((Object)(object)item2.Key != (Object)null && item2.Value == name)
				{
					AddKnownRecipe.Invoke(player, new object[1] { item2.Key });
				}
			}
		}
	}
	internal static class Tabs
	{
		private sealed class Set
		{
			internal StationDef Def;

			internal GameObject[] Tab;

			internal GameObject[] Plate;

			internal GameObject[] Glow;

			internal Image[] Icon;
		}

		[DefaultExecutionOrder(32000)]
		internal sealed class Controller : MonoBehaviour
		{
			private void LateUpdate()
			{
				Follow();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Show")]
		internal static class ShowPatch
		{
			private static void Postfix(InventoryGui __instance)
			{
				Ensure(__instance);
			}
		}

		private const float Step = 80f;

		private static InventoryGui gui;

		private static readonly List<Set> Sets = new List<Set>();

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

		private static bool failed;

		private static readonly MethodInfo UpdatePanel = AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", new Type[1] { typeof(bool) }, (Type[])null);

		internal static int OpenPage(StationDef def)
		{
			if (!Open.TryGetValue(def.Name, out var value))
			{
				return def.DefaultPage;
			}
			return Mathf.Clamp(value, 0, Math.Max(0, def.Pages.Length - 1));
		}

		internal static bool Shows(StationDef def, Recipe recipe)
		{
			if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_craftingStation == (Object)null || recipe.m_craftingStation.m_name != def.Name || def.Pages.Length == 0)
			{
				return false;
			}
			return def.Pages[OpenPage(def)].Has(recipe);
		}

		internal static void Ensure(InventoryGui window)
		{
			if ((Object)(object)window == (Object)null || (Object)(object)window.m_crafting == (Object)null || (Object)(object)window.m_repairButton == (Object)null || (Object)(object)window.m_repairPanel == (Object)null || ((Object)(object)gui == (Object)(object)window && (failed || Sets.Count > 0)))
			{
				return;
			}
			Destroy();
			gui = window;
			failed = false;
			try
			{
				foreach (StationDef item in Stations.All)
				{
					if (item.Pages.Length != 0)
					{
						Sets.Add(Build(window, item));
					}
				}
				if (Sets.Count > 0)
				{
					((Component)window.m_crafting).gameObject.AddComponent<Controller>();
				}
				Follow();
			}
			catch (Exception ex)
			{
				failed = true;
				if (Stations.Log != null)
				{
					Stations.Log.LogError((object)("The station tabs could not be built: " + ex));
				}
			}
		}

		private static void Destroy()
		{
			foreach (Set set in Sets)
			{
				for (int i = 0; i < set.Tab.Length; i++)
				{
					if ((Object)(object)set.Tab[i] != (Object)null)
					{
						Object.Destroy((Object)(object)set.Tab[i]);
					}
					if ((Object)(object)set.Plate[i] != (Object)null)
					{
						Object.Destroy((Object)(object)set.Plate[i]);
					}
				}
			}
			Sets.Clear();
			gui = null;
		}

		private static bool Keep(Component c)
		{
			if (!(c is Graphic) && !(c is Selectable) && !(c is Mask) && !(c is RectMask2D) && !(c is LayoutGroup) && !(c is ContentSizeFitter) && !(c is LayoutElement) && !(c is BaseMeshEffect))
			{
				return c is UITooltip;
			}
			return true;
		}

		private static GameObject Clone(GameObject source, Transform parent, string name)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			GameObject val = new GameObject("HC_TabHolder");
			val.SetActive(false);
			GameObject val2 = Object.Instantiate<GameObject>(source, val.transform, false);
			((Object)val2).name = name;
			foreach (MonoBehaviour item in val2.GetComponentsInChildren<MonoBehaviour>(true).ToList())
			{
				if ((Object)(object)item != (Object)null && !Keep((Component)(object)item))
				{
					Object.DestroyImmediate((Object)(object)item);
				}
			}
			val2.transform.SetParent(parent, false);
			Object.Destroy((Object)(object)val);
			return val2;
		}

		private static Set Build(InventoryGui window, StationDef def)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			int num = def.Pages.Length;
			Set set = new Set
			{
				Def = def,
				Tab = (GameObject[])(object)new GameObject[num],
				Plate = (GameObject[])(object)new GameObject[num],
				Glow = (GameObject[])(object)new GameObject[num],
				Icon = (Image[])(object)new Image[num]
			};
			Vector2 val6 = default(Vector2);
			for (int i = 0; i < num; i++)
			{
				Page page = def.Pages[i];
				GameObject val = Clone(((Component)window.m_repairPanel).gameObject, (Transform)(object)window.m_crafting, "HC_TabPlate_" + def.Name + i);
				val.SetActive(false);
				set.Plate[i] = val;
				val.transform.SetSiblingIndex(window.m_repairPanel.GetSiblingIndex());
				GameObject val2 = Clone(((Component)window.m_repairButton).gameObject, (Transform)(object)window.m_crafting, "HC_Tab_" + def.Name + i);
				val2.SetActive(false);
				set.Tab[i] = val2;
				Image component = val2.GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					((Graphic)component).color = Color.white;
				}
				Button component2 = val2.GetComponent<Button>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Selectable)component2).interactable = true;
					component2.onClick = new ButtonClickedEvent();
					int which = i;
					((UnityEvent)component2.onClick).AddListener((UnityAction)delegate
					{
						Choose(def, which);
					});
				}
				string[] array = new string[3] { "gamepad_hint", "Selected", "Text" };
				foreach (string text in