Decompiled source of Tireless Kelvin v0.4.3

plugins/TirelessKelvin.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using AzNean.SotfCommon;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Sons.Ai.Vail;
using Sons.Ai.Vail.Inventory;
using Sons.Gameplay;
using Sons.Gui;
using Sons.Input;
using Sons.Multiplayer;
using Steamworks;
using TMPro;
using TheForest.Utils;
using TirelessKelvin.Logic;
using TirelessKelvin.Patches;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("TirelessKelvin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.3.0")]
[assembly: AssemblyInformationalVersion("0.4.3+dbd9a85f111a40dc87f0c615935691964d6d51a7")]
[assembly: AssemblyProduct("TirelessKelvin")]
[assembly: AssemblyTitle("TirelessKelvin")]
[assembly: AssemblyVersion("0.4.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

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

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

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
}
namespace TirelessKelvin
{
	[BepInPlugin("aznan.sotf.tirelesskelvin", "TirelessKelvin", "0.4.3")]
	public class Plugin : BasePlugin
	{
		internal const string Version = "0.4.3";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> NoRestDuringOrders;

		internal static ConfigEntry<float> WaitForWorkSeconds;

		internal static ConfigEntry<bool> NoSitDuringWorkOrders;

		internal static ConfigEntry<float> NotepadSpeed;

		internal static ConfigEntry<float> TalkAgainSeconds;

		internal static ConfigEntry<float> CarryMultiplier;

		internal static ConfigEntry<bool> AllowMassOrder;

		internal static ConfigEntry<string> MassOrderOnText;

		internal static ConfigEntry<string> MassOrderOffText;

		internal static ConfigEntry<string> MassOrderRefusedText;

		internal static ConfigEntry<float> MessageSeconds;

		internal static ConfigEntry<float> MassOrderRangeMeters;

		internal static ConfigEntry<bool> HelpOnSameBuild;

		internal static ConfigEntry<bool> FullLogging;

		public override void Load()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Expected O, but got Unknown
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Expected O, but got Unknown
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Expected O, but got Unknown
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			//IL_042e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0433: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_0473: Unknown result type (might be due to invalid IL or missing references)
			//IL_0483: Unknown result type (might be due to invalid IL or missing references)
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_0499: Expected O, but got Unknown
			//IL_049e: Expected O, but got Unknown
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			Notepad.SelfCheck();
			TirelessKelvin.Logic.Carry.SelfCheck();
			Texts.SelfCheck();
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "True = Kelvin works without resting during your orders, plus the options below (notepad speed-up: Notepad section, off by default). False = the game's Kelvin.");
			NoRestDuringOrders = ((BasePlugin)this).Config.Bind<bool>("Rest", "NoRestDuringOrders", true, new ConfigDescription("True = Kelvin no longer sits down to rest in the middle of an order (when his energy runs low). Your \"Take a break\" order and his sits outside work orders stay as in the game (between tasks of a work order: see WaitForWorkSeconds). Default true. Only the host's setting counts: Kelvin's mind runs on the host.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			WaitForWorkSeconds = ((BasePlugin)this).Config.Bind<float>("Rest", "WaitForWorkSeconds", 5f, new ConfigDescription("During a work order (gather, build, clear, repair, maintain...), how long Kelvin waits where he is for his next task after each of his actions, instead of wandering to you or standing idle. In the game he picks one of these (or a sit) at once when no task is ready at that instant and does not come back to work until it ends (measured: 10 to 45 s, up to 100 s by a fire). If no task comes in time, he does as in the game. Eating, drinking, sleeping at night and his reactions to you stay as in the game. Seconds. Default 5. Advised: 0 to 30, step 1. 0 = as in the game. Only the host's setting counts: Kelvin's mind runs on the host.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			NoSitDuringWorkOrders = ((BasePlugin)this).Config.Bind<bool>("Rest", "NoSitDuringWorkOrders", true, new ConfigDescription("True = during a work order (gather, build, clear, repair, maintain...), Kelvin does not sit by a fire or on a bench while waiting for his next task (in the game he does, from 4 s to over 2 min). Outside work orders he sits as in the game. False = his sits are only held back like his other idles (WaitForWorkSeconds). Default true. Only the host's setting counts: Kelvin's mind runs on the host.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			TalkAgainSeconds = ((BasePlugin)this).Config.Bind<float>("Notepad", "TalkAgainSeconds", 0.5f, new ConfigDescription("How long after you hand Kelvin an order (or put the notepad away) before you can talk to him again. The game waits 10 s after an order, 2 s after putting the notepad away. Applies at once, from the next order. Never longer than the game. Your own notepad animation still plays to its end first. Seconds. Default 0.5. Advised: 0 to 10, step 0.5. In multiplayer the host's value counts for everyone (live, guests need ModConfigMenu).", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			CarryMultiplier = ((BasePlugin)this).Config.Bind<float>("Carry", "AmountMultiplier", 1f, new ConfigDescription("How much Kelvin carries in one trip, times the game's amount of each kind: logs 2, sticks 5, rocks 5, stones 2, arrows 5, berries 5, spears 5, fish 1, radio 1 (rounded, never below the game's). Applies at once, from his next pickup. Default 1 = game amounts (off). Advised: 1 to 10, step 0.5. 1 or less = game amounts; over 1000 items of one kind is refused (game amounts), as it could freeze the game. The extra items hang where the game hangs the others, continuing their spacing (fish and radio: on the same spot). Only the host's setting counts: Kelvin's mind runs on the host; other players see at most the game's amount on him.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			NotepadSpeed = ((BasePlugin)this).Config.Bind<float>("Notepad", "AnimationSpeedMultiplier", 1f, new ConfigDescription("Notepad speed-up: how fast the notepad animations play when you give Kelvin an order, times the game's: raising the notepad (game 1.3 s), writing and handing back the order (game 4.2 s, long note 9.2 s), Kelvin reading it (game 6.5 s, long note 11.2 s). Applies at once, even mid-animation. Default 1 = game speed (off): set 2 to give orders twice as fast. Advised: 1 to 10, step 0.5. 0 or less = game speed. You stay still while the notepad is up, as in the game. In multiplayer the host's value counts for everyone (live, guests need ModConfigMenu).", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			AllowMassOrder = ((BasePlugin)this).Config.Bind<bool>("MassOrder", "AllowMassOrder", false, new ConfigDescription("True = with 2 or more Kelvins, the notepad's order list gets one more line, \"All Kelvins: off\": pick it like an order to switch it on or off (the notepad stays up, no animation; off again at each game load). Switch on = the order you give one Kelvin goes to every Kelvin, and they share out the work: one no longer goes for a tree, log, stick, stone, bush, repair, trap or wall to sharpen that another Kelvin of the same order is already on. Switch off = one order for one Kelvin, as in the game. False = no switch, as in the game. Default false. In multiplayer the host decides: it tells every guest who has this mod (no Mod Config Menu needed); a guest needs the mod to see the line, and when the host does not allow it, the guest gets a message and the order goes to one Kelvin.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			MassOrderRangeMeters = ((BasePlugin)this).Config.Bind<float>("MassOrder", "RangeMeters", 0f, new ConfigDescription("During a mass order, a Kelvin only leaves a target to another Kelvin within this distance of him. Meters. Default 0 = any distance; otherwise 20 or more is advised. Advised: 0 to 500, step 10. Only the host's setting counts.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			HelpOnSameBuild = ((BasePlugin)this).Config.Bind<bool>("MassOrder", "HelpOnSameBuild", true, new ConfigDescription("During a mass order: true = several Kelvins may still bring items to the same building, wall or shelter (as in the game); false = one Kelvin per build site. Default true. Only the host's setting counts.", (AcceptableValueBase)null, new object[1] { "HostDecides" }));
			MassOrderOnText = ((BasePlugin)this).Config.Bind<string>("Texts", "MassOrderOnText", "", "Text of the mass order line in the notepad's order list when it is on. Empty = automatic, in the game's language (English: \"All Kelvins: on\").");
			MassOrderOffText = ((BasePlugin)this).Config.Bind<string>("Texts", "MassOrderOffText", "", "Text of the mass order line in the notepad's order list when it is off. Empty = automatic, in the game's language (English: \"All Kelvins: off\").");
			MassOrderRefusedText = ((BasePlugin)this).Config.Bind<string>("Texts", "MassOrderRefusedText", "", "Multiplayer guest: on-screen message when you switch the mass order line on, or give an order with it on, and the host does not allow mass orders (the order goes to that Kelvin only). Empty = automatic, in the game's language.");
			MessageSeconds = ((BasePlugin)this).Config.Bind<float>("Texts", "MessageSeconds", 4f, "Seconds the on-screen message stays. Default 4. Advised: 2 to 8. 0 or less = no message.");
			FullLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "FullLogging", false, "True = the BepInEx log gets every step useful to diagnose a problem (each notepad animation sped up and restored, each work order a Kelvin starts or leaves with what is held back, each action Kelvin starts, each target one Kelvin leaves to another in a mass order). False = only loading, version, errors, one line per Kelvin about his rests and between-task waits, the first wait of each game, and each time his orders change.");
			ModLog.Init(Logger, FullLogging);
			string path = Path.Combine(Paths.ConfigPath, "aznan.sotf.tirelesskelvin.notepadspeed-0.2.1.done");
			if (!File.Exists(path))
			{
				if (NotepadSpeed.Value == 2f)
				{
					NotepadSpeed.Value = 1f;
					Logger.LogInfo((object)"Notepad AnimationSpeedMultiplier: the old default 2 was replaced by the new default 1 (once only).");
				}
				File.WriteAllText(path, "Notepad AnimationSpeedMultiplier default 2 -> 1 migrated once (see NOTES).");
			}
			Enabled.SettingChanged += delegate
			{
				RestGroups.Apply();
			};
			NoRestDuringOrders.SettingChanged += delegate
			{
				RestGroups.Apply();
			};
			Enabled.SettingChanged += delegate
			{
				TirelessKelvin.Patches.Carry.Apply(MassOrder.Robbies);
			};
			CarryMultiplier.SettingChanged += delegate
			{
				TirelessKelvin.Patches.Carry.Apply(MassOrder.Robbies);
			};
			Enabled.SettingChanged += delegate
			{
				HostAdvert.Write();
			};
			AllowMassOrder.SettingChanged += delegate
			{
				HostAdvert.Write();
			};
			Harmony val = new Harmony("aznan.sotf.tirelesskelvin");
			val.PatchAll(typeof(TirelessKelvin.Patches.Carry));
			val.PatchAll(typeof(RestGroups));
			val.PatchAll(typeof(NotepadSpeed));
			val.PatchAll(typeof(TalkAgain));
			val.PatchAll(typeof(BetweenTasks));
			val.PatchAll(typeof(OrderLog));
			MassOrder.Patch(val);
			NotepadSwitch.Patch(val);
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(23, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("TirelessKelvin ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("0.4.3");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" loaded.");
			}
			logger.LogInfo(val2);
		}
	}
}
namespace TirelessKelvin.Patches
{
	[HarmonyPatch(typeof(VailActor), "ClearActiveAction")]
	internal static class BetweenTasks
	{
		private static readonly List<Group> Idles = new List<Group>();

		private static readonly List<Group> Sits = new List<Group>();

		internal static readonly HashSet<IntPtr> WorkOrders = new HashSet<IntPtr>();

		internal static readonly Dictionary<IntPtr, float> LastEnd = new Dictionary<IntPtr, float>();

		private static readonly HashSet<IntPtr> Warned = new HashSet<IntPtr>();

		private static bool _shown;

		private const float SitHoldSeconds = 120f;

		internal static void Find()
		{
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Expected O, but got Unknown
			Idles.Clear();
			Sits.Clear();
			WorkOrders.Clear();
			_shown = false;
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Group>()))
			{
				if (Array.IndexOf(Notepad.IdleGroups, item.name) >= 0)
				{
					Idles.Add(((Il2CppObjectBase)item).Cast<Group>());
				}
				else if (Array.IndexOf(Notepad.SitGroups, item.name) >= 0)
				{
					Sits.Add(((Il2CppObjectBase)item).Cast<Group>());
				}
			}
			foreach (Object item2 in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<VailControllerOverride>()))
			{
				if (Array.IndexOf(Notepad.WorkOrders, item2.name) >= 0)
				{
					WorkOrders.Add(((Il2CppObjectBase)item2).Pointer);
				}
			}
			string text = $"{Idles.Count} of {Notepad.IdleGroups.Length} idle groups, {Sits.Count} of {Notepad.SitGroups.Length} sits, {WorkOrders.Count} of {Notepad.WorkOrders.Length} work orders found";
			bool flag = default(bool);
			if (Idles.Count == Notepad.IdleGroups.Length && Sits.Count == Notepad.SitGroups.Length && WorkOrders.Count == Notepad.WorkOrders.Length)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(94, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Kelvin between tasks of a work order: waits up to ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Plugin.WaitForWorkSeconds.Value, "0.#");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s for the next one before idling, sits ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Plugin.NoSitDuringWorkOrders.Value ? "held for the whole order" : "as idles");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(").");
				}
				logger.LogInfo(val);
			}
			else
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(88, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Kelvin between tasks of a work order: only ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; the missing ones keep the game's behaviour.");
				}
				logger2.LogWarning(val2);
			}
		}

		private static void Prefix(VailActor __instance, out bool __state)
		{
			__state = (Object)(object)__instance != (Object)null && (Object)(object)__instance._activeGroup != (Object)null;
		}

		private static void Postfix(VailActor __instance, bool __state)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			if ((Object)(object)__instance == (Object)null || (int)__instance.TypeId != 9)
			{
				return;
			}
			Dictionary<Group, float> cooldowns = __instance._cooldowns;
			if (cooldowns == null)
			{
				ModLog.Once("no cooldowns", "A Kelvin has no cooldown table: his idles between tasks stay as in the game.", (LogLevel)4);
				return;
			}
			float time = Time.time;
			VailControllerOverride val = null;
			List<VailControllerOverride> overrideControllers = __instance._overrideControllers;
			if (Plugin.Enabled.Value && overrideControllers != null)
			{
				for (int i = 0; i < overrideControllers.Count; i++)
				{
					if (!((Object)(object)val == (Object)null))
					{
						break;
					}
					if ((Object)(object)overrideControllers[i] != (Object)null && WorkOrders.Contains(((Il2CppObjectBase)overrideControllers[i]).Pointer))
					{
						val = overrideControllers[i];
					}
				}
			}
			float value = Plugin.WaitForWorkSeconds.Value;
			bool value2 = Plugin.NoSitDuringWorkOrders.Value;
			if ((Object)(object)val == (Object)null)
			{
				LastEnd.Remove(((Il2CppObjectBase)__instance).Pointer);
				Warned.Remove(((Il2CppObjectBase)__instance).Pointer);
				int num = 0;
				float num2 = default(float);
				foreach (Group sit in Sits)
				{
					if ((Object)(object)sit != (Object)null && cooldowns.TryGetValue(sit, ref num2) && num2 > time + 30f)
					{
						cooldowns[sit] = time;
						num++;
					}
				}
				if (ModLog.Changed(__instance.UniqueId, "work order", 0))
				{
					ModLog.Trace($"Kelvin (id {__instance.UniqueId}) out of work orders{(Plugin.Enabled.Value ? "" : " (mod off)")}: idles and sits as in the game, {num} held sit(s) given back.");
				}
				return;
			}
			if (!__state)
			{
				CheckHeld(__instance, val, cooldowns, time, value);
				return;
			}
			LastEnd[((Il2CppObjectBase)__instance).Pointer] = time;
			Warned.Remove(((Il2CppObjectBase)__instance).Pointer);
			bool flag = ModLog.Changed(__instance.UniqueId, "work order", HashCode.Combine(((Il2CppObjectBase)val).Pointer, value, value2));
			if (value > 0f)
			{
				foreach (Group idle in Idles)
				{
					Hold(cooldowns, idle, time + value);
				}
			}
			foreach (Group sit2 in Sits)
			{
				if (value2)
				{
					Hold(cooldowns, sit2, time + 120f);
				}
				else if (value > 0f)
				{
					Hold(cooldowns, sit2, time + value);
				}
			}
			if (!_shown)
			{
				_shown = true;
				ManualLogSource logger = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(92, 4, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Kelvin (id ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(__instance.UniqueId);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") works on ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": idles held back ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(value, "0.#");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" s after each action, sits ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(value2 ? "held during the order" : "too");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" (first time since load).");
				}
				logger.LogInfo(val2);
			}
			else if (flag)
			{
				ModLog.Trace($"Kelvin (id {__instance.UniqueId}) works on {((Object)val).name}: idles held back {value:0.#} s after each action, sits {(value2 ? "held during the order" : "too")}.");
			}
		}

		private static void CheckHeld(VailActor kelvin, VailControllerOverride order, Dictionary<Group, float> table, float now, float wait)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			if (wait <= 0f || Idles.Count == 0 || Warned.Contains(((Il2CppObjectBase)kelvin).Pointer) || !LastEnd.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return;
			}
			float num = now - value;
			if (num <= wait + 30f)
			{
				return;
			}
			float num2 = default(float);
			foreach (Group idle in Idles)
			{
				if ((Object)(object)idle == (Object)null || !table.TryGetValue(idle, ref num2) || num2 <= now)
				{
					return;
				}
			}
			Warned.Add(((Il2CppObjectBase)kelvin).Pointer);
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(111, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Kelvin (id ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(kelvin.UniqueId);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") stood still ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num, "0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s during ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)order).name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": his idles are still held past the ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(wait, "0.#");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s wait (hold pushed without an action).");
			}
			logger.LogWarning(val);
		}

		private static void Hold(Dictionary<Group, float> table, Group g, float until)
		{
			float num = default(float);
			if ((Object)(object)g != (Object)null && (!table.TryGetValue(g, ref num) || num < until))
			{
				table[g] = until;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryManager), "GetItemCarryTypeCount")]
	internal static class Carry
	{
		private static readonly Dictionary<string, int> Game = new Dictionary<string, int>();

		private static readonly HashSet<IntPtr> Kelvins = new HashSet<IntPtr>();

		private static bool _raised;

		private static bool _sentShown;

		private static int[] _groups = new int[16];

		private const int Slots = 5;

		private const int BitsPerItem = 6;

		private static float Multiplier
		{
			get
			{
				if (!Plugin.Enabled.Value)
				{
					return 1f;
				}
				return Plugin.CarryMultiplier.Value;
			}
		}

		private static int Max(string kind)
		{
			if (kind == null || !Game.TryGetValue(kind, out var value))
			{
				return -1;
			}
			int num = TirelessKelvin.Logic.Carry.Max(value, Multiplier);
			if (num >= 0)
			{
				return num;
			}
			return value;
		}

		internal static void Apply(IEnumerable<Robby> robbies)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Expected O, but got Unknown
			bool flag = default(bool);
			if (TirelessKelvin.Logic.Carry.Max(5, Multiplier) < 0)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(110, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Carry: x");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Multiplier);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" gives over ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(1000);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" items of one kind, refused (it could freeze the game): Kelvin carries the game's amounts.");
				}
				logger.LogWarning(val);
			}
			VailPickupManager instance = VailPickupManager._instance;
			if ((Object)(object)instance == (Object)null)
			{
				Plugin.Logger.LogWarning((object)"Carry: the game's pickup table is not loaded yet; Kelvin carries the game's amounts until the next Kelvin starts or the setting changes.");
				return;
			}
			List<string> list = new List<string>();
			Enumerator<TypeInfo> enumerator = instance._pickupTypes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				TypeInfo current = enumerator.Current;
				if (!Game.TryGetValue(current.itemType, out var value))
				{
					value = (Game[current.itemType] = current.maxHeld);
				}
				int num = (current.maxHeld = Max(current.itemType));
				if (num > value)
				{
					_raised = true;
					list.Add($"{current.itemType} {num} (game {value})");
				}
			}
			int num3 = Limits();
			int num4 = 0;
			foreach (Robby robby in robbies)
			{
				if ((Object)(object)robby != (Object)null)
				{
					num4 += Points(robby);
				}
			}
			if (list.Count == 0)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(81, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Carry: Kelvin carries the game's amounts (x");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(Multiplier);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" gather order limits at the game's).");
				}
				logger2.LogInfo(val2);
			}
			else
			{
				ManualLogSource logger3 = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(76, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Carry: Kelvin carries ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(string.Join(", ", list));
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" of ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(TirelessKelvin.Logic.Carry.GatherGroups.Length);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" gather order limits set, ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num4);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" carry point(s) added.");
				}
				logger3.LogInfo(val2);
			}
			if (num3 < TirelessKelvin.Logic.Carry.GatherGroups.Length)
			{
				ManualLogSource logger4 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(89, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Carry: only ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" of ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(TirelessKelvin.Logic.Carry.GatherGroups.Length);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" gather order limits found; the missing orders stop at the game's amount.");
				}
				logger4.LogWarning(val);
			}
		}

		private static int Limits()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Invalid comparison between Unknown and I4
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Invalid comparison between Unknown and I4
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Invalid comparison between Unknown and I4
			int num = 0;
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Group>()))
			{
				Group val = ((Il2CppObjectBase)item).TryCast<Group>();
				if ((Object)(object)val == (Object)null || Array.IndexOf(TirelessKelvin.Logic.Carry.GatherGroups, ((Object)val).name) < 0)
				{
					continue;
				}
				Enumerator<Thought> enumerator2 = val._thoughts.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					Enumerator<Condition> enumerator3 = enumerator2.Current._conditions.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						Condition current = enumerator3.Current;
						if ((int)current._conditionType == 2 && (int)current._targetType == 0)
						{
							bool flag = (int)current._operator == 5;
							int num2 = Max(current._inventoryItemName);
							if ((flag || (int)current._operator == 3) && num2 >= 0)
							{
								current._value = TirelessKelvin.Logic.Carry.Threshold(flag, num2);
								num++;
							}
						}
					}
				}
			}
			return num;
		}

		private static int Points(Robby robby)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: 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)
			VailActor actor = robby._actor;
			InventoryManager val = (((Object)(object)actor == (Object)null) ? null : actor._inventoryManager);
			if ((Object)(object)val == (Object)null)
			{
				ModLog.Trace("Carry: a Kelvin without inventory, no carry points added.");
				return 0;
			}
			Kelvins.Add(((Il2CppObjectBase)val).Pointer);
			int num = 0;
			Enumerator<CarryAttachments> enumerator = val._carryAttachments.GetEnumerator();
			while (enumerator.MoveNext())
			{
				CarryAttachments current = enumerator.Current;
				List<Transform> val2 = (((Object)(object)current == (Object)null) ? null : current._transforms);
				int num2 = val2?.Count ?? 0;
				int num3 = 0;
				if (num2 != 0)
				{
					Enumerator<string> enumerator2 = current._itemTypes.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						string current2 = enumerator2.Current;
						num3 = Math.Max(num3, Max(current2));
					}
					Transform val3 = val2[num2 - 1];
					Vector3 val4 = ((num2 >= 2) ? (val3.localPosition - val2[num2 - 2].localPosition) : Vector3.zero);
					for (int i = 1; num2 + i - 1 < num3; i++)
					{
						Transform transform = new GameObject($"{((Object)val3).name}+{i}").transform;
						transform.SetParent(val3.parent, false);
						transform.localPosition = val3.localPosition + val4 * (float)i;
						transform.localRotation = val3.localRotation;
						transform.localScale = val3.localScale;
						val2.Add(transform);
						num++;
					}
				}
			}
			return num;
		}

		private static void Postfix(InventoryManager __instance, ref int __result)
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			if (!_raised || !Kelvins.Contains(((Il2CppObjectBase)__instance).Pointer))
			{
				return;
			}
			List<VailPickup> heldItems = __instance._heldItems;
			int num = heldItems?.Count ?? 0;
			if (num < 2)
			{
				return;
			}
			if (_groups.Length < num)
			{
				_groups = new int[num * 2];
			}
			int num2 = 0;
			int num3 = 0;
			bool flag = false;
			for (int i = 0; i < num; i++)
			{
				if (num3 >= 5)
				{
					break;
				}
				string itemType = heldItems[i]._itemType;
				int groupId = InventoryTypeList.GetGroupId(itemType);
				int num4 = 0;
				_groups[i] = groupId;
				for (int j = 0; j < i; j++)
				{
					if (_groups[j] == groupId)
					{
						num4++;
					}
				}
				if (Game.TryGetValue(itemType, out var value) && num4 >= value)
				{
					flag = true;
				}
				else
				{
					num2 |= InventoryTypeList.GetTypeId(itemType) << 6 * num3++;
				}
			}
			if (!flag)
			{
				return;
			}
			__result = num2;
			if (!_sentShown)
			{
				_sentShown = true;
				ManualLogSource logger = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(114, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Carry: Kelvin holds ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" items; other players are sent at most the game's amount of each kind (first time since load).");
				}
				logger.LogInfo(val);
			}
		}
	}
	internal static class HostAdvert
	{
		private static string _written;

		private static string _read;

		private static CoopLobby Lobby()
		{
			return CoopLobbyManager.GetActiveInstance();
		}

		internal static void Write()
		{
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (BoltNetwork.isClient)
				{
					return;
				}
				CoopLobby val = Lobby();
				if (val == null)
				{
					ModLog.Trace("Mass order: no Steam lobby (single player or dedicated server): nothing told to guests.");
				}
				else
				{
					if (SteamMatchmaking.GetLobbyOwner(val.LobbyId).m_SteamID != SteamUser.GetSteamID().m_SteamID)
					{
						return;
					}
					string text = Notepad.HostValue(MassOrder.Allowed);
					string text2 = $"{val.LobbyId.m_SteamID} {text}";
					if (!(text2 == _written))
					{
						bool flag = SteamMatchmaking.SetLobbyData(val.LobbyId, "aznan.tirelesskelvin:massorder", text);
						if (flag)
						{
							_written = text2;
						}
						string text3 = $"Multiplayer: guests told mass orders are {(MassOrder.Allowed ? "allowed" : "not allowed")} through the lobby {val.LobbyId.m_SteamID} ({(flag ? "done" : "refused by Steam")})";
						if (flag)
						{
							Plugin.Logger.LogInfo((object)text3);
						}
						else
						{
							Plugin.Logger.LogWarning((object)text3);
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(62, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Multiplayer: guests not told whether mass orders are allowed: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val2);
			}
		}

		internal static bool? HostSays()
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Expected O, but got Unknown
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				CoopLobby val = Lobby();
				string value = ((val == null) ? null : SteamMatchmaking.GetLobbyData(val.LobbyId, "aznan.tirelesskelvin:massorder"));
				bool? result = Notepad.HostSays(value);
				string text = $"{((val != null) ? new ulong?(val.LobbyId.m_SteamID) : ((ulong?)null))} {value}";
				if (text != _read)
				{
					_read = text;
					if (result.HasValue)
					{
						ManualLogSource logger = Plugin.Logger;
						BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(50, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Multiplayer: host's mass order setting received: ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(result.Value ? "allowed" : "not allowed");
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
						}
						logger.LogInfo(val2);
					}
					else
					{
						Plugin.Logger.LogInfo((object)"Multiplayer: the host has said nothing about mass orders (host without TirelessKelvin 0.4.2 or later): your own setting is used; an older TirelessKelvin on the host that does not allow it refuses the copies.");
					}
				}
				return result;
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(49, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Multiplayer: host's mass order setting not read: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				logger2.LogError(val3);
				return null;
			}
		}

		internal static bool GuestRefused(string what)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			if (BoltNetwork.isClient)
			{
				bool? flag = HostSays();
				bool flag2 = false;
				if (flag == flag2)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(56, 1, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Mass order: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(what);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; the host does not allow it, message shown.");
					}
					logger.LogInfo(val);
					string text;
					if (!string.IsNullOrEmpty(Plugin.MassOrderRefusedText.Value))
					{
						text = Plugin.MassOrderRefusedText.Value;
					}
					else
					{
						Locale selectedLocale = LocalizationSettings.SelectedLocale;
						text = Texts.Get((selectedLocale != null) ? selectedLocale.Identifier.Code : null, "HostRefuses");
					}
					Show(text);
					return true;
				}
			}
			return false;
		}

		private static void Show(string text)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			if (Plugin.MessageSeconds.Value <= 0f)
			{
				ModLog.Trace("Mass order: no on-screen message, [Texts] MessageSeconds is 0 or less.");
				return;
			}
			HudGui instance = HudGui._instance;
			if ((Object)(object)instance == (Object)null)
			{
				ModLog.Once("no hud", "Mass order: the game's message line (HudGui) was not found: no on-screen message.", (LogLevel)4);
				return;
			}
			try
			{
				instance.DisplayGeneralMessage(text, Plugin.MessageSeconds.Value, (ItemUiData)null);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(38, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Mass order: game message line failed: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogWarning(val);
			}
		}
	}
	internal static class MassOrder
	{
		private struct Given
		{
			public VailActor Actor;

			public int Type;

			public int Sub;

			public int Sub2;

			public IntPtr Player;

			public float Time;
		}

		[HarmonyPatch(typeof(Robby), "LocalPlayerGiveOrdersFromTactipad")]
		private static class FromNotepad
		{
			private static void Prefix(Robby __instance)
			{
				_giver = __instance;
			}

			private static void Postfix()
			{
				_giver = null;
			}
		}

		[HarmonyPatch(typeof(Robby), "ServerGiveOrders")]
		private static class ServerGive
		{
			private static bool Prefix(Robby __instance, OrderType orderType, int subOrderType, int subOrderType2, Transform fromPlayer)
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Expected I4, but got Unknown
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				if (Allowed || _spreading || (Object)(object)_giver == (Object)(object)__instance || !IsCopy(__instance._actor, (int)orderType, subOrderType, subOrderType2, fromPlayer))
				{
					return true;
				}
				if (!_refusedShown)
				{
					_refusedShown = true;
					Plugin.Logger.LogInfo((object)"Mass order: a player sent one order to several Kelvins; refused, not allowed in the host's config (first time since load).");
				}
				else
				{
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(80, 2);
					defaultInterpolatedStringHandler.AppendLiteral("Mass order: copy of ");
					defaultInterpolatedStringHandler.AppendFormatted<OrderType>(orderType);
					defaultInterpolatedStringHandler.AppendLiteral(" for Kelvin (id ");
					VailActor actor = __instance._actor;
					defaultInterpolatedStringHandler.AppendFormatted((actor != null) ? new int?(actor.UniqueId) : ((int?)null));
					defaultInterpolatedStringHandler.AppendLiteral(") refused, not allowed in the host's config.");
					ModLog.Trace(defaultInterpolatedStringHandler.ToStringAndClear());
				}
				return false;
			}

			private unsafe static void Postfix(Robby __instance, OrderType orderType, int subOrderType, int subOrderType2, Transform fromPlayer)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Expected I4, but got Unknown
				Remember(__instance._actor, (int)orderType, subOrderType, subOrderType2, fromPlayer);
				Spread(__instance, ((object)(*(OrderType*)(&orderType))/*cast due to .constrained prefix*/).ToString(), delegate(Robby r)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					r.ServerGiveOrders(orderType, subOrderType, subOrderType2, fromPlayer);
				});
			}
		}

		[HarmonyPatch(typeof(Robby), "ClientSendOrders")]
		private static class ClientSend
		{
			private unsafe static void Postfix(Robby __instance, OrderType orderType, int subOrderType, int subOrderType2)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				Spread(__instance, ((object)(*(OrderType*)(&orderType))/*cast due to .constrained prefix*/).ToString(), delegate(Robby r)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					r.ClientSendOrders(orderType, subOrderType, subOrderType2);
				});
			}
		}

		[HarmonyPatch(typeof(VailActor), "IsValidStimuli")]
		private static class ShareTargets
		{
			private static readonly Dictionary<IntPtr, int> Kinds = new Dictionary<IntPtr, int>();

			private static bool _shown;

			private static void Postfix(VailActor __instance, IStimuli stimuli, ref bool __result)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Invalid comparison between Unknown and I4
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fa: 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_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0131: Expected O, but got Unknown
				if (!__result || stimuli == null || (Object)(object)__instance == (Object)null || (int)__instance.TypeId != 9 || !Allowed || !LastGiven.TryGetValue(((Il2CppObjectBase)__instance).Pointer, out var value))
				{
					return;
				}
				IntPtr pointer = ((Il2CppObjectBase)stimuli).Pointer;
				switch (Kind(pointer))
				{
				case 2:
					if (Plugin.HelpOnSameBuild.Value)
					{
						break;
					}
					goto default;
				default:
				{
					if (Holds(__instance, pointer))
					{
						break;
					}
					float value2 = Plugin.MassOrderRangeMeters.Value;
					Vector3 position = ((Component)__instance).transform.position;
					{
						bool flag = default(bool);
						foreach (KeyValuePair<IntPtr, Given> item in LastGiven)
						{
							VailActor actor = item.Value.Actor;
							if (item.Key == ((Il2CppObjectBase)__instance).Pointer || (Object)(object)actor == (Object)null || !Same(value, item.Value) || !Holds(actor, pointer))
							{
								continue;
							}
							if (value2 > 0f)
							{
								Vector3 val = ((Component)actor).transform.position - position;
								if (((Vector3)(ref val)).sqrMagnitude > value2 * value2)
								{
									continue;
								}
							}
							__result = false;
							if (!_shown)
							{
								_shown = true;
								ManualLogSource logger = Plugin.Logger;
								BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(100, 3, ref flag);
								if (flag)
								{
									((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Mass order: Kelvin (id ");
									((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(__instance.UniqueId);
									((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") leaves a ");
									((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ClassName(pointer));
									((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" to Kelvin (id ");
									((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(actor.UniqueId);
									((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") and takes another target (first time since load).");
								}
								logger.LogInfo(val2);
							}
							else if (ModLog.Changed(HashCode.Combine(__instance.UniqueId, pointer), "left to", actor.UniqueId))
							{
								ModLog.Trace($"Mass order: Kelvin (id {__instance.UniqueId}) leaves a {ClassName(pointer)} to Kelvin (id {actor.UniqueId}).");
							}
							break;
						}
						break;
					}
				}
				case 0:
					break;
				}
			}

			private static bool Holds(VailActor a, IntPtr target)
			{
				ActiveStimuliInfo activeStimuli = a._activeStimuli;
				if (activeStimuli != null && activeStimuli._active && activeStimuli._stimuli != null)
				{
					return ((Il2CppObjectBase)activeStimuli._stimuli).Pointer == target;
				}
				return false;
			}

			private static int Kind(IntPtr obj)
			{
				IntPtr intPtr = IL2CPP.il2cpp_object_get_class(obj);
				if (Kinds.TryGetValue(intPtr, out var value))
				{
					return value;
				}
				IntPtr intPtr2 = intPtr;
				while (intPtr2 != IntPtr.Zero && value == 0)
				{
					string text = Marshal.PtrToStringAnsi(IL2CPP.il2cpp_class_get_name(intPtr2));
					if (Array.IndexOf(Notepad.OwnWorkTargets, text) >= 0)
					{
						value = 1;
					}
					else if (text == "BuildActionStimuli")
					{
						value = 2;
					}
					intPtr2 = IL2CPP.il2cpp_class_get_parent(intPtr2);
				}
				Kinds[intPtr] = value;
				return value;
			}

			private static string ClassName(IntPtr obj)
			{
				return Marshal.PtrToStringAnsi(IL2CPP.il2cpp_class_get_name(IL2CPP.il2cpp_object_get_class(obj)));
			}
		}

		internal static bool On;

		internal static readonly List<Robby> Robbies = new List<Robby>();

		private static Robby _giver;

		private static bool _spreading;

		private static bool _sharePatched;

		private static bool _groupShown;

		private static bool _refusedShown;

		internal static Harmony Harmony;

		private static readonly Dictionary<IntPtr, Given> LastGiven = new Dictionary<IntPtr, Given>();

		internal static int Count
		{
			get
			{
				Robbies.RemoveAll((Robby r) => (Object)(object)r == (Object)null);
				return Robbies.Count;
			}
		}

		internal static bool Allowed
		{
			get
			{
				if (Plugin.Enabled.Value)
				{
					return Plugin.AllowMassOrder.Value;
				}
				return false;
			}
		}

		internal static void Seen(Robby robby)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			if (Count == 0)
			{
				On = false;
				LastGiven.Clear();
				_groupShown = (_refusedShown = false);
				ModLog.Trace("Mass order: first Kelvin of this game, notepad switch reset to off.");
			}
			Robbies.Add(robby);
			if (Robbies.Count == 2)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(44, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Mass order: 2 Kelvins seen, notepad switch ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Plugin.AllowMassOrder.Value ? "shown when the notepad is up" : "not allowed by the host's config");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				}
				logger.LogInfo(val);
			}
			HostAdvert.Write();
		}

		internal static void Patch(Harmony harmony)
		{
			Harmony = harmony;
			harmony.PatchAll(typeof(FromNotepad));
			harmony.PatchAll(typeof(ServerGive));
			harmony.PatchAll(typeof(ClientSend));
		}

		private static void Spread(Robby from, string order, Action<Robby> give)
		{
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_giver == (Object)null || ((Il2CppObjectBase)_giver).Pointer != ((Il2CppObjectBase)from).Pointer || _spreading)
			{
				return;
			}
			if (!On || !Allowed)
			{
				ModLog.Trace($"Mass order: {order} for this Kelvin only (switch {(On ? "on" : "off")}, {(Allowed ? "allowed" : "not allowed by the host's config or mod off")}).");
				return;
			}
			if (HostAdvert.GuestRefused(order + " given with the switch on"))
			{
				On = false;
				return;
			}
			int num = 0;
			_spreading = true;
			try
			{
				Robby[] array = Robbies.ToArray();
				foreach (Robby val in array)
				{
					if ((Object)(object)val != (Object)null && ((Il2CppObjectBase)val).Pointer != ((Il2CppObjectBase)from).Pointer && (int)val._injuredState == 0)
					{
						give(val);
						num++;
					}
				}
			}
			finally
			{
				_spreading = false;
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(44, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Mass order: ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(order);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" also given to ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" other Kelvin(s).");
			}
			logger.LogInfo(val2);
		}

		private static void Remember(VailActor actor, int type, int sub, int sub2, Transform player)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			if ((Object)(object)actor == (Object)null)
			{
				return;
			}
			Given given = new Given
			{
				Actor = actor,
				Type = type,
				Sub = sub,
				Sub2 = sub2,
				Player = (((Object)(object)player == (Object)null) ? IntPtr.Zero : ((Il2CppObjectBase)player).Pointer),
				Time = Time.time
			};
			LastGiven[((Il2CppObjectBase)actor).Pointer] = given;
			bool flag = default(bool);
			foreach (KeyValuePair<IntPtr, Given> item in LastGiven)
			{
				if (!(item.Key != ((Il2CppObjectBase)actor).Pointer) || !Same(given, item.Value))
				{
					continue;
				}
				if (!_sharePatched)
				{
					_sharePatched = true;
					Harmony.PatchAll(typeof(ShareTargets));
				}
				if (!_groupShown)
				{
					_groupShown = true;
					ManualLogSource logger = Plugin.Logger;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(116, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Mass order: Kelvins (id ");
						VailActor actor2 = item.Value.Actor;
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int?>((actor2 != null) ? new int?(actor2.UniqueId) : ((int?)null));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", id ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(actor.UniqueId);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ...) got the same order together; they share out its targets (first time since load).");
					}
					logger.LogInfo(val);
				}
				else
				{
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(88, 2);
					defaultInterpolatedStringHandler.AppendLiteral("Mass order: Kelvin (id ");
					defaultInterpolatedStringHandler.AppendFormatted(actor.UniqueId);
					defaultInterpolatedStringHandler.AppendLiteral(") got the same order as Kelvin (id ");
					VailActor actor3 = item.Value.Actor;
					defaultInterpolatedStringHandler.AppendFormatted((actor3 != null) ? new int?(actor3.UniqueId) : ((int?)null));
					defaultInterpolatedStringHandler.AppendLiteral("); they share out its targets.");
					ModLog.Trace(defaultInterpolatedStringHandler.ToStringAndClear());
				}
				break;
			}
		}

		private static bool IsCopy(VailActor actor, int type, int sub, int sub2, Transform player)
		{
			Given a = new Given
			{
				Type = type,
				Sub = sub,
				Sub2 = sub2,
				Player = (((Object)(object)player == (Object)null) ? IntPtr.Zero : ((Il2CppObjectBase)player).Pointer),
				Time = Time.time
			};
			foreach (KeyValuePair<IntPtr, Given> item in LastGiven)
			{
				if (((Object)(object)actor == (Object)null || item.Key != ((Il2CppObjectBase)actor).Pointer) && Same(a, item.Value))
				{
					return true;
				}
			}
			return false;
		}

		private static bool Same(Given a, Given b)
		{
			if (a.Type == b.Type && a.Sub == b.Sub && a.Sub2 == b.Sub2 && a.Player == b.Player)
			{
				return Mathf.Abs(a.Time - b.Time) <= 0.5f;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Robby), "Update")]
	internal static class NotepadSpeed
	{
		private static readonly int[] Kelvin = Hashes("Base Layer.Idling.RobbyPad.", Notepad.KelvinStates);

		private static readonly int[] Player = Hashes("fullBodyActions.RobbyInteractions.", Notepad.PlayerStates);

		private static readonly int[] Pad = Hashes("Base Layer.", Notepad.PadStates);

		private static readonly Dictionary<IntPtr, (float Before, float Times)> Sped = new Dictionary<IntPtr, (float, float)>();

		private static IntPtr _playerAnimator;

		private static int _playerLayer = -1;

		private static bool _playerShown;

		private static bool _playerWarned;

		private static bool _playerSpedThisOrder;

		private static int[] Hashes(string path, string[] states)
		{
			return states.Select((string s) => Animator.StringToHash(path + s)).ToArray();
		}

		private static void Postfix(Robby __instance)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			float value = Plugin.NotepadSpeed.Value;
			bool flag = Plugin.Enabled.Value && Notepad.IsUsable(value) && value != 1f;
			PlayerRobbyInteraction robbyInteraction = LocalPlayer.RobbyInteraction;
			Animator val = ((robbyInteraction != null) ? robbyInteraction._animator : null);
			bool flag2 = default(bool);
			if ((Object)(object)val != (Object)null)
			{
				if (((Il2CppObjectBase)val).Pointer != _playerAnimator || _playerLayer < 0)
				{
					_playerAnimator = ((Il2CppObjectBase)val).Pointer;
					_playerLayer = val.GetLayerIndex("fullBodyActions");
				}
				if (_playerLayer >= 0 && Tune(val, _playerLayer, Player, flag, value, "player") > 0)
				{
					_playerSpedThisOrder = true;
					if (!_playerShown)
					{
						_playerShown = true;
						ManualLogSource logger = Plugin.Logger;
						BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(51, 1, ref flag2);
						if (flag2)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Notepad: your hands play x");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(value);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" (first time since load).");
						}
						logger.LogInfo(val2);
					}
				}
			}
			RobbyWorldUi tactiPad = __instance._tactiPad;
			if ((Object)(object)tactiPad != (Object)null && (Object)(object)tactiPad._animator != (Object)null)
			{
				Tune(tactiPad._animator, 0, Pad, flag, value, "notepad");
			}
			if (BoltNetwork.isClient)
			{
				if (ModLog.Changed(((Object)__instance).GetInstanceID(), "guest", 1))
				{
					ModLog.Trace("Notepad: you are a guest: Kelvin's own notepad animation speed comes from the host.");
				}
			}
			else
			{
				if ((Object)(object)__instance._robbyAnimator == (Object)null)
				{
					return;
				}
				int num = Tune(__instance._robbyAnimator, 0, Kelvin, flag, value, "Kelvin");
				if (num > 0)
				{
					_playerSpedThisOrder = (Object)(object)val != (Object)null && Sped.ContainsKey(((Il2CppObjectBase)val).Pointer);
				}
				else if (num < 0 && !_playerSpedThisOrder && !_playerWarned)
				{
					_playerWarned = true;
					ManualLogSource logger2 = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(94, 3, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Notepad: Kelvin's notepad animation was sped but not your hands (player animator ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(((Object)(object)val == (Object)null) ? "missing" : "found");
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(", layer ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>("fullBodyActions");
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" = ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(_playerLayer);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(").");
					}
					logger2.LogWarning(val3);
				}
			}
		}

		private static int Tune(Animator animator, int layer, int[] states, bool on, float speed, string who)
		{
			//IL_0014: 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)
			AnimatorStateInfo val = (animator.IsInTransition(layer) ? animator.GetNextAnimatorStateInfo(layer) : animator.GetCurrentAnimatorStateInfo(layer));
			bool flag = on && Array.IndexOf(states, ((AnimatorStateInfo)(ref val)).fullPathHash) >= 0;
			(float, float) value;
			bool flag2 = Sped.TryGetValue(((Il2CppObjectBase)animator).Pointer, out value);
			var (num, _) = value;
			if (flag && !flag2)
			{
				float speed2 = animator.speed;
				Sped[((Il2CppObjectBase)animator).Pointer] = (speed2, speed);
				animator.speed = speed2 * speed;
				ModLog.Trace($"Notepad: {who} animation (state {((AnimatorStateInfo)(ref val)).fullPathHash}) played x{speed} (speed {speed2} -> {animator.speed}).");
				return 1;
			}
			if (!flag && flag2)
			{
				animator.speed = num;
				Sped.Remove(((Il2CppObjectBase)animator).Pointer);
				ModLog.Trace($"Notepad: {who} animation back to speed {num}.");
				return -1;
			}
			if (flag && value.Item2 != speed)
			{
				animator.speed = num * speed;
				Sped[((Il2CppObjectBase)animator).Pointer] = (num, speed);
				ModLog.Trace($"Notepad: {who} animation now x{speed} (setting changed mid-animation).");
			}
			return 0;
		}
	}
	[HarmonyPatch(typeof(Robby), "LocalPlayerOpenTactipad")]
	internal static class NotepadSwitch
	{
		[HarmonyPatch(typeof(RobbyWorldUi), "HandlePlayerInput")]
		private static class Skip
		{
			private static void Prefix(RobbyWorldUi __instance, out int __state)
			{
				__state = int.MinValue;
				if (!((Object)(object)_pad == (Object)null) && !(((Il2CppObjectBase)__instance).Pointer != ((Il2CppObjectBase)_pad).Pointer))
				{
					FixWrapCopy(__instance);
					TextCarousel val = OrderList(__instance);
					if ((Object)(object)val != (Object)null)
					{
						__state = ((Carousel<TMP_Text>)(object)val)._currentTarget;
					}
				}
			}

			private static void Postfix(RobbyWorldUi __instance, int __state)
			{
				if (__state == int.MinValue)
				{
					return;
				}
				TextCarousel val = OrderList(__instance);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				int count = ((Carousel<TMP_Text>)(object)val)._optionsList.Count;
				int currentTarget = ((Carousel<TMP_Text>)(object)val)._currentTarget;
				if (count < 3 || ((Carousel<TMP_Text>)(object)val)._optionIdList[count - 1] != 100)
				{
					return;
				}
				int num = Notepad.SkipOurLine(__state, currentTarget, count);
				if (num != currentTarget)
				{
					((Carousel<TMP_Text>)(object)val)._currentTarget = num;
					((Carousel<TMP_Text>)(object)val)._currentScroll = num;
					((Carousel<TMP_Text>)(object)val)._lastScrollStart = num;
					if (!_skipShown)
					{
						_skipShown = true;
						Plugin.Logger.LogInfo((object)"Mass order: up on the first order went to the game's last order, past our line (first time since load).");
					}
					else
					{
						ModLog.Trace("Mass order: up on the first order went to the game's last order, past our line.");
					}
				}
			}
		}

		[HarmonyPatch(typeof(RobbyWorldUi), "HandlePlayerInput")]
		private static class Input
		{
			private static bool Prefix(RobbyWorldUi __instance)
			{
				if ((Object)(object)_pad == (Object)null || __instance._closing || __instance._selectedCarousel != 0 || !OurLineSelected(__instance))
				{
					return true;
				}
				if (__instance._lastNextPressTime >= 0f || InputSystem.GetAxis(Actions.Horizontal) <= 0.5f)
				{
					return true;
				}
				__instance._lastNextPressTime = Time.timeSinceLevelLoad;
				Flip(__instance, "from the notepad's order list", rename: true);
				return false;
			}
		}

		[HarmonyPatch(typeof(Robby), "LocalPlayerCloseTactipad")]
		private static class Close
		{
			private static void Prefix(Robby __instance, ref PadState newPadState)
			{
				if ((int)newPadState == 2 || (int)newPadState == 3)
				{
					RobbyWorldUi tactiPad = __instance._tactiPad;
					if (OurLineSelected(tactiPad))
					{
						newPadState = (PadState)4;
						Flip(tactiPad, "while the notepad closed (no order given)", rename: false);
						ModLog.Once("closed on line", "Mass order: the notepad closed on the mass order line by another way than the next key; handled as a cancel.", (LogLevel)4);
					}
				}
			}
		}

		private static RobbyWorldUi _pad;

		private static bool _shown;

		private static bool _copyDone;

		private static bool _skipShown;

		private const int Orders = 0;

		private static void Prefix(Robby __instance, out bool __state)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			__state = (int)__instance._localPadState != 1;
		}

		private static void Postfix(Robby __instance, bool __state)
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Expected O, but got Unknown
			if (!__state)
			{
				return;
			}
			RobbyWorldUi tactiPad = __instance._tactiPad;
			bool flag = MassOrder.Allowed && MassOrder.Count >= 2;
			bool flag2 = ModLog.Changed(((Object)__instance).GetInstanceID(), "switch", flag ? 1 : 0);
			_pad = null;
			if (!flag)
			{
				if (flag2)
				{
					ModLog.Trace("Mass order: no line in the notepad (" + (MassOrder.Allowed ? $"{MassOrder.Count} Kelvin(s), 2 needed" : "not allowed by the host's config or mod off") + ").");
				}
				return;
			}
			if ((Object)(object)tactiPad == (Object)null)
			{
				ModLog.Once("no pad", "Mass order: Kelvin's notepad was not found; no mass order line.", (LogLevel)4);
				return;
			}
			tactiPad.AddMenuItem(0, 100, Label(), -1);
			tactiPad.UpdateVisuals();
			_pad = tactiPad;
			_copyDone = false;
			FixWrapCopy(tactiPad);
			if (!_shown)
			{
				_shown = true;
				ManualLogSource logger = Plugin.Logger;
				bool flag3 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(102, 1, ref flag3);
				if (flag3)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Mass order: line \"");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Label());
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("\" added after the game's orders in the notepad's order list (first time since load).");
				}
				logger.LogInfo(val);
			}
			else if (flag2)
			{
				ModLog.Trace("Mass order: line shown in the notepad again, now " + (MassOrder.On ? "on" : "off") + ".");
			}
		}

		private static TextCarousel OrderList(RobbyWorldUi pad)
		{
			if (!((Object)(object)pad != (Object)null) || pad._selectedCarousel != 0)
			{
				return null;
			}
			return pad.SelectedCarousel();
		}

		private static void FixWrapCopy(RobbyWorldUi pad)
		{
			TextCarousel val = OrderList(pad);
			if (_copyDone || (Object)(object)val == (Object)null)
			{
				return;
			}
			_copyDone = true;
			int count = ((Carousel<TMP_Text>)(object)val)._optionsList.Count;
			TMP_Text lastOption = ((Carousel<TMP_Text>)(object)val)._lastOption;
			if (count < 3 || (Object)(object)lastOption == (Object)null || ((Carousel<TMP_Text>)(object)val)._optionIdList[count - 1] != 100)
			{
				ModLog.Once("no wrap copy", $"Mass order: the order list is not as read ({count} lines, wrap copy {(((Object)(object)lastOption == (Object)null) ? "missing" : "found")}, last id {((count > 0) ? ((Carousel<TMP_Text>)(object)val)._optionIdList[count - 1] : (-1))}): the line above the first order is left as the game made it.", (LogLevel)4);
			}
			else
			{
				string text = (lastOption.text = ((Carousel<TMP_Text>)(object)val)._optionsList[count - 2].text);
				if (lastOption.text == Label())
				{
					Plugin.Logger.LogWarning((object)"Mass order: our line shows above the first order of the notepad's list.");
				}
				else
				{
					ModLog.Trace("Mass order: the line above the first order shows '" + text + "' (the game's last order); ours is after it.");
				}
			}
		}

		private static string Label()
		{
			string text = (MassOrder.On ? Plugin.MassOrderOnText.Value : Plugin.MassOrderOffText.Value);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			Locale selectedLocale = LocalizationSettings.SelectedLocale;
			return Texts.Get((selectedLocale != null) ? selectedLocale.Identifier.Code : null, MassOrder.On ? "SwitchOn" : "SwitchOff");
		}

		private static bool OurLineSelected(RobbyWorldUi pad)
		{
			if ((Object)(object)_pad != (Object)null && (Object)(object)pad != (Object)null && ((Il2CppObjectBase)pad).Pointer == ((Il2CppObjectBase)_pad).Pointer)
			{
				return pad.GetSelection(0) == 100;
			}
			return false;
		}

		private static void Flip(RobbyWorldUi pad, string how, bool rename)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			if (!MassOrder.On && HostAdvert.GuestRefused("switch picked " + how))
			{
				return;
			}
			string text = Label();
			MassOrder.On = !MassOrder.On;
			string text2 = Label();
			TextCarousel val = (rename ? pad.SelectedCarousel() : null);
			if ((Object)(object)val != (Object)null)
			{
				for (int i = 0; i < ((Carousel<TMP_Text>)(object)val)._optionsList.Count; i++)
				{
					TMP_Text val2 = ((Carousel<TMP_Text>)(object)val)._optionsList[i];
					if ((Object)(object)val2 != (Object)null && val2.text == text)
					{
						val2.text = text2;
					}
				}
				for (int j = 0; j < ((Carousel<TMP_Text>)(object)val)._displayList.Count; j++)
				{
					TMP_Text val3 = ((Carousel<TMP_Text>)(object)val)._displayList[j];
					if ((Object)(object)val3 != (Object)null && val3.text == text)
					{
						val3.text = text2;
					}
				}
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val4 = new BepInExInfoLogInterpolatedStringHandler(23, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("Mass order: switched ");
				((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(MassOrder.On ? "on" : "off");
				((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(how);
				((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(".");
			}
			logger.LogInfo(val4);
		}

		internal static void Patch(Harmony harmony)
		{
			harmony.PatchAll(typeof(NotepadSwitch));
			harmony.PatchAll(typeof(Input));
			harmony.PatchAll(typeof(Skip));
			harmony.PatchAll(typeof(Close));
		}
	}
	[HarmonyPatch(typeof(VailActor), "PerformAction")]
	internal static class OrderLog
	{
		private static readonly Dictionary<IntPtr, long> LastOrders = new Dictionary<IntPtr, long>();

		private static void Postfix(VailActor __instance, Group group)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			if ((Object)(object)group == (Object)null || (Object)(object)__instance == (Object)null || (int)__instance.TypeId != 9 || !Plugin.Enabled.Value)
			{
				return;
			}
			List<VailControllerOverride> overrideControllers = __instance._overrideControllers;
			long num = 0L;
			if (overrideControllers != null)
			{
				for (int i = 0; i < overrideControllers.Count; i++)
				{
					if ((Object)(object)overrideControllers[i] != (Object)null)
					{
						num += (long)((Il2CppObjectBase)overrideControllers[i]).Pointer;
					}
				}
			}
			if (!LastOrders.TryGetValue(((Il2CppObjectBase)__instance).Pointer, out var value) || value != num)
			{
				LastOrders[((Il2CppObjectBase)__instance).Pointer] = num;
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(25, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Kelvin (id ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(__instance.UniqueId);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") order now: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Names(overrideControllers));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				}
				logger.LogInfo(val);
			}
			Check(__instance, group, overrideControllers);
			if (ModLog.Full)
			{
				ModLog.Trace($"Kelvin (id {__instance.UniqueId}) t={Time.time:0.00} does: {group._name}.");
			}
		}

		private static void Check(VailActor kelvin, Group group, List<VailControllerOverride> orders)
		{
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			VailControllerOverride val = null;
			if (orders != null)
			{
				for (int i = 0; i < orders.Count; i++)
				{
					if (!((Object)(object)val == (Object)null))
					{
						break;
					}
					if ((Object)(object)orders[i] != (Object)null && BetweenTasks.WorkOrders.Contains(((Il2CppObjectBase)orders[i]).Pointer))
					{
						val = orders[i];
					}
				}
			}
			if ((Object)(object)val == (Object)null || !BetweenTasks.LastEnd.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return;
			}
			float num = Time.time - value;
			float value2 = Plugin.WaitForWorkSeconds.Value;
			string name = ((Object)group).name;
			bool flag = default(bool);
			if (value2 > 0f && num < value2 - 0.5f && Array.IndexOf(Notepad.IdleGroups, name) >= 0)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(81, 5, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Kelvin (id ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(kelvin.UniqueId);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") idles (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(num, "0.#");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" s after his last action during ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", before the ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(value2, "0.#");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" s hold ended.");
				}
				logger.LogWarning(val2);
			}
			if (Plugin.NoSitDuringWorkOrders.Value && Array.IndexOf(Notepad.SitGroups, name) >= 0)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(66, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Kelvin (id ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(kelvin.UniqueId);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") sits (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") during ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" although sits are held for the order.");
				}
				logger2.LogWarning(val2);
			}
		}

		private static string Names(List<VailControllerOverride> orders)
		{
			List<string> list = new List<string>();
			if (orders != null)
			{
				for (int i = 0; i < orders.Count; i++)
				{
					if ((Object)(object)orders[i] != (Object)null)
					{
						list.Add(((Object)orders[i]).name);
					}
				}
			}
			if (list.Count != 0)
			{
				return string.Join(", ", list);
			}
			return "none";
		}
	}
	[HarmonyPatch(typeof(Robby), "Start")]
	internal static class RestGroups
	{
		private static readonly List<Thought> Muted = new List<Thought>();

		private static void Postfix(Robby __instance)
		{
			Apply();
			BetweenTasks.Find();
			MassOrder.Seen(__instance);
			Carry.Apply(MassOrder.Robbies);
		}

		internal static void Apply()
		{
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Expected O, but got Unknown
			bool flag = Plugin.Enabled.Value && Plugin.NoRestDuringOrders.Value;
			foreach (Thought item in Muted)
			{
				if (item != null)
				{
					item._mute = false;
				}
			}
			Muted.Clear();
			if (!flag)
			{
				Plugin.Logger.LogInfo((object)"Kelvin rests during orders: as in the game (setting off).");
				return;
			}
			List<string> list = new List<string>();
			foreach (Object item2 in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Group>()))
			{
				Group val = ((Il2CppObjectBase)item2).TryCast<Group>();
				if (!((Object)(object)val == (Object)null) && Array.IndexOf(Notepad.RestGroups, ((Object)val).name) >= 0)
				{
					Enumerator<Thought> enumerator3 = val._thoughts.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						Thought current2 = enumerator3.Current;
						current2._mute = true;
						Muted.Add(current2);
					}
					list.Add($"{((Object)val).name} ({val._thoughts.Count} thought(s))");
				}
			}
			bool flag2 = default(bool);
			if (list.Count == Notepad.RestGroups.Length)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(41, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Kelvin rests during orders: off (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(string.Join(", ", list));
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" muted).");
				}
				logger.LogInfo(val2);
				return;
			}
			ManualLogSource logger2 = Plugin.Logger;
			BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(97, 3, ref flag2);
			if (flag2)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Kelvin rests during orders: only ");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(list.Count);
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" of ");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(Notepad.RestGroups.Length);
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" rest groups found (");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(string.Join(", ", list));
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("); the missing ones still make him rest.");
			}
			logger2.LogWarning(val3);
		}
	}
	[HarmonyPatch(typeof(Robby), "LocalPlayerCloseTactipad")]
	internal static class TalkAgain
	{
		private static void Postfix(Robby __instance)
		{
			float value = Plugin.TalkAgainSeconds.Value;
			ShoulderTapActor shoulderTap = __instance._shoulderTap;
			if (Plugin.Enabled.Value && !((Object)(object)shoulderTap == (Object)null))
			{
				float num = Time.time + Mathf.Max(0f, value);
				float nextInteractionTime = shoulderTap._nextInteractionTime;
				if (!(num >= nextInteractionTime))
				{
					shoulderTap._nextInteractionTime = num;
					ModLog.Trace($"Talk again: Kelvin can be talked to in {Mathf.Max(0f, value)} s instead of {nextInteractionTime - Time.time:0.0} s.");
				}
			}
		}
	}
}
namespace TirelessKelvin.Logic
{
	public static class Carry
	{
		public const int MaxItems = 1000;

		public static readonly string[] GatherGroups = new string[9] { "RobbyGetLog", "RobbyGetSticks", "RobbyGetRocks", "RobbyGetStones", "RobbyGetArrows", "RobbyGetBerries", "RobbyGetSpears", "RobbyGetFish", "RobbyGetRadio" };

		public static int Max(int game, float multiplier)
		{
			if (!(multiplier > 1f) || float.IsInfinity(multiplier))
			{
				if (!float.IsPositiveInfinity(multiplier))
				{
					return game;
				}
				return -1;
			}
			double num = Math.Round((double)game * (double)multiplier);
			if (!(num > 1000.0))
			{
				return Math.Max(game, (int)num);
			}
			return -1;
		}

		public static float Threshold(bool orEqual, int max)
		{
			return orEqual ? max : (max - 1);
		}

		public static void SelfCheck()
		{
			if (Max(2, 1f) != 2 || Max(2, 0.5f) != 2 || Max(2, float.NaN) != 2 || Max(2, 2f) != 4 || Max(5, 1.5f) != 8 || Max(1, 1.2f) != 1 || Max(2, 600f) != -1 || Max(2, float.PositiveInfinity) != -1)
			{
				throw new Exception("Carry.Max: game amount times the multiplier, rounded, never below the game's, refused above MaxItems");
			}
			if (Threshold(orEqual: true, 4) != 4f || Threshold(orEqual: false, 4) != 3f)
			{
				throw new Exception("Carry.Threshold: \">=\" blocks at the maximum, \">\" one below");
			}
		}
	}
	public static class Notepad
	{
		public static readonly string[] RestGroups = new string[4] { "RobbyRest", "RobbyRestMaintain", "RobbyRestWaiting", "SitToRestNow" };

		public static readonly string[] IdleGroups = new string[2] { "RobbyWander", "RobbyStandIdle" };

		public static readonly string[] SitGroups = new string[3] { "RobbySitByPlayerFire", "SitByNewPlayerFire", "RobbySitOnStructure" };

		public const float GameSitCooldownMax = 30f;

		public const float StillMarginSeconds = 30f;

		public static readonly string[] WorkOrders = new string[19]
		{
			"RobbyMaintain", "RobbyGetLog", "RobbyGetSticks", "RobbyGetRocks", "RobbyGetStones", "RobbyGetBerries", "RobbyGetFish", "RobbyGetArrows", "RobbyGetSpears", "RobbyGetRadio",
			"RobbyBuildFire", "RobbyBuildPerimeterWall", "RobbyBuildShelter", "RobbyBuildStructure", "RobbyClearArea", "RobbyDismantleShelter", "RobbyRepair", "RobbyResetTraps", "RobbySharpenWall"
		};

		public static readonly string[] OwnWorkTargets = new string[7] { "RobbyClearTreeStimuli", "RobbyClearStimuli", "PickupStimuli", "BerryBushStimuli", "RobbyRepairStimuli", "PlayerTrapStimuli", "StructureSharpenStimuli" };

		public const string BuildTarget = "BuildActionStimuli";

		public const float MassOrderWindowSeconds = 0.5f;

		public const int SwitchOptionId = 100;

		public const float AxisPress = 0.5f;

		public const string HostKey = "aznan.tirelesskelvin:massorder";

		public static readonly string[] KelvinStates = new string[6] { "RobbyPadRaise", "RobbyPadTakeOrderFast", "RobbyPadTakeNoteGame", "LookAround", "RefuseOrder", "RobbyPadLower" };

		public const string KelvinPath = "Base Layer.Idling.RobbyPad.";

		public static readonly string[] PlayerStates = new string[4] { "RobbyPadRaise", "RobbyPadGiveOrderFast", "RobbyPadGiveNote", "RobbyPadLower" };

		public const string PlayerLayer = "fullBodyActions";

		public const string PlayerPath = "fullBodyActions.RobbyInteractions.";

		public static readonly string[] PadStates = new string[4] { "RobbyPadRaise", "RobbyPadGiveNote", "RobbyPadTakeNote", "RobbyPadLower" };

		public const string PadPath = "Base Layer.";

		public static int SkipOurLine(int before, int after, int count)
		{
			if (count < 3 || after != before - 1 || Wrap(before, count) != 0)
			{
				return after;
			}
			return after - 1;
		}

		public static int Wrap(int index, int count)
		{
			if (count > 0)
			{
				return (index % count + count) % count;
			}
			return 0;
		}

		public static string HostValue(bool allowed)
		{
			if (!allowed)
			{
				return "0";
			}
			return "1";
		}

		public static bool? HostSays(string value)
		{
			if (!(value == "1"))
			{
				if (!(value == "0"))
				{
					return null;
				}
				return false;
			}
			return true;
		}

		public static bool IsUsable(float multiplier)
		{
			if (multiplier > 0f && !float.IsNaN(multiplier))
			{
				return !float.IsInfinity(multiplier);
			}
			return false;
		}

		public static void SelfCheck()
		{
			if (!IsUsable(2f) || IsUsable(0f) || IsUsable(-1f) || IsUsable(float.NaN) || IsUsable(float.PositiveInfinity))
			{
				throw new Exception("Notepad.IsUsable: only a finite multiplier above 0 is usable");
			}
			if (SkipOurLine(0, -1, 9) != -2 || SkipOurLine(9, 8, 9) != 7 || SkipOurLine(7, 8, 9) != 8 || SkipOurLine(8, 7, 9) != 7 || SkipOurLine(1, 0, 9) != 0 || SkipOurLine(0, 1, 9) != 1 || SkipOurLine(0, -1, 2) != -1 || Wrap(-2, 9) != 7)
			{
				throw new Exception("Notepad.SkipOurLine: only up on the game's first line skips our line");
			}
			if (HostSays(HostValue(allowed: true)) != true || HostSays(HostValue(allowed: false)) != false || HostSays(null).HasValue || HostSays("").HasValue)
			{
				throw new Exception("Notepad.HostSays: 1 = allowed, 0 = not, anything else = unknown");
			}
		}
	}
	public static class Texts
	{
		public const string SwitchOn = "SwitchOn";

		public const string SwitchOff = "SwitchOff";

		public const string HostRefuses = "HostRefuses";

		private static readonly Dictionary<string, Dictionary<string, string>> ByLanguage = new Dictionary<string, Dictionary<string, string>>
		{
			["en"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "All Kelvins: on",
				["SwitchOff"] = "All Kelvins: off",
				["HostRefuses"] = "The host does not allow one order for all Kelvins: this order goes to this Kelvin only"
			},
			["fr"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Tous les Kelvin : oui",
				["SwitchOff"] = "Tous les Kelvin : non",
				["HostRefuses"] = "L'hôte n'autorise pas un ordre pour tous les Kelvin : cet ordre va à ce Kelvin seulement"
			},
			["zh"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "所有Kelvin:开启",
				["SwitchOff"] = "所有Kelvin:关闭",
				["HostRefuses"] = "房主禁止群发指令:此指令仅下达给当前Kelvin"
			},
			["zh-hant"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "所有Kelvin:開啟",
				["SwitchOff"] = "所有Kelvin:關閉",
				["HostRefuses"] = "房主禁止群發指令:此指令僅下達給當前Kelvin"
			},
			["cs"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Všichni Kelvinové: zapnuto",
				["SwitchOff"] = "Všichni Kelvinové: vypnuto",
				["HostRefuses"] = "Hostitel nepovoluje hromadný příkaz: tento příkaz dostane pouze tento Kelvin"
			},
			["fi"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Kaikki Kelvinit: päällä",
				["SwitchOff"] = "Kaikki Kelvinit: pois päältä",
				["HostRefuses"] = "Ylläpitäjä ei salli yhteiskäskyä: tämä käsky koskee vain tätä Kelviniä"
			},
			["de"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Alle Kelvins: Ein",
				["SwitchOff"] = "Alle Kelvins: Aus",
				["HostRefuses"] = "Der Host erlaubt keine Befehle an alle Kelvins: Dieser Befehl gilt nur für diesen Kelvin"
			},
			["it"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Tutti i Kelvin: On",
				["SwitchOff"] = "Tutti i Kelvin: Off",
				["HostRefuses"] = "L'host non consente un ordine per tutti i Kelvin: questo ordine è solo per questo Kelvin"
			},
			["ja"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "すべてのKelvin:オン",
				["SwitchOff"] = "すべてのKelvin:オフ",
				["HostRefuses"] = "ホストが一斉指示を許可していません:この指示はこのKelvinにのみ出されます"
			},
			["ko"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "모든 Kelvin: 켜짐",
				["SwitchOff"] = "모든 Kelvin: 꺼짐",
				["HostRefuses"] = "호스트가 전체 지시를 허용하지 않습니다: 이 지시는 현재 Kelvin에게만 전달됩니다"
			},
			["pl"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Wszyscy Kelvini: wł.",
				["SwitchOff"] = "Wszyscy Kelvini: wył.",
				["HostRefuses"] = "Host nie pozwala na rozkaz dla wszystkich Kelvinów: ten rozkaz trafia tylko do tego Kelvina"
			},
			["pt"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Todos os Kelvins: ligado",
				["SwitchOff"] = "Todos os Kelvins: desligado",
				["HostRefuses"] = "O host não permite ordens coletivas: esta ordem será dada apenas a este Kelvin"
			},
			["ru"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Все Kelvin: вкл.",
				["SwitchOff"] = "Все Kelvin: выкл.",
				["HostRefuses"] = "Хост запретил общий приказ: этот приказ получит только этот Kelvin"
			},
			["es"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Todos los Kelvin: activado",
				["SwitchOff"] = "Todos los Kelvin: desactivado",
				["HostRefuses"] = "El anfitrión no permite órdenes conjuntas: esta orden se dará solo a este Kelvin"
			},
			["sv"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Alla Kelvins: på",
				["SwitchOff"] = "Alla Kelvins: av",
				["HostRefuses"] = "Värden tillåter inte order för alla Kelvins: ordern gäller endast för denna Kelvin"
			},
			["tr"] = new Dictionary<string, string>
			{
				["SwitchOn"] = "Tüm Kelvinler: açık",
				["SwitchOff"] = "Tüm Kelvinler: kapalı",
				["HostRefuses"] = "Oda sahibi tüm Kelvinler için tek emre izin vermiyor: bu emir yalnızca bu Kelvin içindir"
			}
		};

		public static string Get(string localeCode, string key)
		{
			string text = (localeCode ?? "en").ToLowerInvariant();
			string key2 = (ByLanguage.ContainsKey(text) ? text : text.Split('-')[0]);
			if (!ByLanguage.TryGetValue(key2, out var value) || !value.TryGetValue(key, out var value2))
			{
				return ByLanguage["en"][key];
			}
			return value2;
		}

		public static void SelfCheck()
		{
			if (Get("fr-FR", "SwitchOn") != ByLanguage["fr"]["SwitchOn"] || Get("xx", "SwitchOff") != ByLanguage["en"]["SwitchOff"] || Get(null, "HostRefuses") != ByLanguage["en"]["HostRefuses"])
			{
				throw new InvalidOperationException("Texts lookup is wrong.");
			}
			foreach (KeyValuePair<string, Dictionary<string, string>> item in ByLanguage)
			{
				foreach (string key in ByLanguage["en"].Keys)
				{
					if (!item.Value.ContainsKey(key))
					{
						throw new InvalidOperationException($"Texts: {item.Key} lacks {key}.");
					}
				}
			}
		}
	}
}