Decompiled source of SimpleHQ v0.4.20

SimpleHQ.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SimpleHQ.Core;
using SimpleHQ.Features;
using SimpleHQ.Patches;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("DunGen")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.ASPP")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.UnityNav")]
[assembly: IgnoresAccessChecksTo("EasyTextEffects")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.CoreUtils")]
[assembly: IgnoresAccessChecksTo("Unity.XR.Management")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.ConformanceAutomation")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MetaQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MockRuntime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.OculusQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.RuntimeDebugger")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpatialTracking")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XR.LegacyInputHelpers")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 SimpleHQ
{
	public static class BankInfo
	{
		public static int Total => BankStore.Total;

		public static int Count => BankStore.Items.Count;
	}
	internal static class ChatUtil
	{
		internal static bool BroadcastReplies;

		internal static void Send(string message, bool broadcast = false)
		{
			try
			{
				if (BroadcastReplies)
				{
					broadcast = true;
				}
				HUDManager instance = HUDManager.Instance;
				if (!((Object)(object)instance == (Object)null))
				{
					string text = "<color=#ff6a33>HQ</color>: <color=#e8e8e8>" + message + "</color>";
					if (broadcast)
					{
						instance.AddTextMessageServerRpc(text);
					}
					else
					{
						instance.AddChatMessage(text, "", -1, false);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[ChatUtil.Send] {arg}");
			}
		}

		internal static void SendChunked(string message, bool broadcast = false, int maxLen = 120)
		{
			if (string.IsNullOrEmpty(message))
			{
				return;
			}
			while (message.Length > maxLen)
			{
				int num = message.LastIndexOf(',', maxLen);
				if (num < maxLen / 2)
				{
					num = message.LastIndexOf(' ', maxLen);
				}
				if (num < maxLen / 2)
				{
					num = maxLen;
				}
				Send(message.Substring(0, num).TrimEnd(), broadcast);
				message = message.Substring(num).TrimStart(' ', ',');
			}
			if (message.Length > 0)
			{
				Send(message, broadcast);
			}
		}
	}
	internal static class CommandRouter
	{
		internal static bool IsOurs(string raw)
		{
			string[] array = Split(raw);
			if (array.Length == 0)
			{
				return false;
			}
			switch (array[0].ToLowerInvariant())
			{
			case "clear":
			case "bank":
			case "tournament":
			case "agree":
				return true;
			case "sell":
			case "s":
				if (array.Length >= 2)
				{
					return array[1].ToLowerInvariant() == "bank";
				}
				break;
			}
			return false;
		}

		internal static void Route(string raw, string who, PlayerControllerB requester = null)
		{
			string[] array = Split(raw);
			string text = array[0].ToLowerInvariant();
			switch (text)
			{
			case "clear":
			{
				bool flag = (Object)(object)requester == (Object)null;
				string text3 = ((array.Length >= 2) ? array[1].ToLowerInvariant() : "");
				if (flag)
				{
					switch (text3)
					{
					case "me":
					case "mine":
					case "self":
						ChatClear.Local();
						break;
					default:
						ChatClear.Everyone();
						break;
					}
				}
				else
				{
					ChatUtil.Send((who ?? "Player") + ": install SimpleHQ to clear your own chat.", broadcast: true);
				}
				return;
			}
			case "tournament":
			case "agree":
			{
				string text2 = ArenaMarker.Refusal("tournament mode");
				if (text2 != null)
				{
					ChatUtil.Send(text2);
				}
				else
				{
					RouteTournament(array, text, who, requester);
				}
				return;
			}
			}
			if (ArenaMarker.Active)
			{
				ChatUtil.Send(ArenaMarker.Refusal("the crew bank"));
				return;
			}
			if (TournamentInfo.Active)
			{
				ChatUtil.Send("Tournament mode: the bank is off until the run ends.");
				return;
			}
			if ((!(text == "bank") || array.Length != 1) && (Object)(object)requester != (Object)null && !WhitelistBridge.IsWhitelisted(requester.playerSteamId))
			{
				ChatUtil.Send("Only the host and whitelisted players can use bank commands" + (string.IsNullOrEmpty(who) ? "" : (" (" + who + ")")) + ". /bank shows the total.");
				return;
			}
			if (text != "bank")
			{
				BankService.SellFromBank(Join(array, 2), who);
				return;
			}
			switch ((array.Length >= 2) ? array[1].ToLowerInvariant() : "")
			{
			case "":
				BankService.Status();
				break;
			case "d":
			case "deposit":
				BankService.Deposit(Join(array, 2), who);
				break;
			case "auto":
				BankService.SetAuto(Join(array, 2), who);
				break;
			case "info":
				BankService.Info();
				break;
			case "w":
			case "withdraw":
				if (array.Length == 3 && array[2].ToLowerInvariant() == "all")
				{
					BankService.WithdrawAll(who);
				}
				else
				{
					BankService.Withdraw(Join(array, 2), who, requester);
				}
				break;
			case "l":
			case "list":
				BankService.List();
				break;
			case "sell":
				BankService.SellFromBank(Join(array, 2), who);
				break;
			default:
				ChatUtil.Send("/bank, /bank deposit <amount|all|item [count]>, /bank withdraw <item> [count|all], /bank withdraw all, /bank auto on|off, /bank list, /bank info, /bank sell (or /sell bank) <amount|quota|all>");
				break;
			}
		}

		private static void RouteTournament(string[] parts, string verb, string who, PlayerControllerB requester)
		{
			if (verb == "agree")
			{
				TournamentService.Agree(who, requester);
				return;
			}
			string text = ((parts.Length >= 2) ? parts[1].ToLowerInvariant() : "");
			bool flag = (Object)(object)requester == (Object)null;
			switch (text)
			{
			case "status":
			case "":
				TournamentService.Status();
				break;
			case "start":
			case "on":
				if (!flag)
				{
					ChatUtil.Send("Only the host can start tournament mode.");
				}
				else
				{
					TournamentService.Start();
				}
				break;
			case "load":
				if (!flag)
				{
					ChatUtil.Send("Only the host can load a tournament kit.");
				}
				else
				{
					TournamentService.Load((parts.Length >= 3) ? parts[2] : "");
				}
				break;
			case "stop":
			case "end":
				if (!flag)
				{
					ChatUtil.Send("Only the host can end tournament mode.");
				}
				else
				{
					TournamentService.End();
				}
				break;
			default:
				ChatUtil.Send("/tournament (status), /tournament start (host), /agree, /tournament load <code> (host), /tournament end (host)");
				break;
			}
		}

		internal static bool IsSenderTheHost(int playerId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsHost)
			{
				return false;
			}
			if (playerId < 0)
			{
				return true;
			}
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val != (Object)null)
			{
				if (playerId != (int)val.playerClientId)
				{
					return playerId == (int)val.actualClientId;
				}
				return true;
			}
			return false;
		}

		private static string[] Split(string raw)
		{
			return (raw ?? "").Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
		}

		private static string Join(string[] parts, int from)
		{
			if (parts.Length <= from)
			{
				return "";
			}
			return string.Join(" ", parts, from, parts.Length - from);
		}
	}
	internal static class ModConfig
	{
		internal static ConfigEntry<string> CommandPrefix { get; private set; }

		internal static ConfigEntry<string> AltCommandPrefix { get; private set; }

		internal static ConfigEntry<string> KeepOnShip { get; private set; }

		internal static ConfigEntry<bool> IncludeCruiser { get; private set; }

		internal static ConfigEntry<bool> ShowBankOnTerminal { get; private set; }

		internal static ConfigEntry<bool> ClearChatOnLaunch { get; private set; }

		internal static ConfigEntry<bool> PrivateLobbiesOnly { get; private set; }

		internal static ConfigEntry<bool> AutoDeposit { get; private set; }

		internal static ConfigEntry<bool> AllSuits { get; private set; }

		internal static void Init(ConfigFile file)
		{
			CommandPrefix = file.Bind<string>("General", "CommandPrefix", "/", "Prefix for chat commands (e.g. /bank).");
			AltCommandPrefix = file.Bind<string>("General", "AltCommandPrefix", "!", "Second prefix that always works, e.g. !bank. Use it if /bank says 'unknown command': another chat mod is taking every '/' message first. Leave empty to disable.");
			KeepOnShip = file.Bind<string>("Bank", "KeepOnShip", "Shotgun, Kitchen knife", "Scrap that /bank deposit never takes, comma separated item names. Weapons you still want to use.");
			IncludeCruiser = file.Bind<bool>("Bank", "IncludeCruiser", true, "Also deposit scrap sitting in the Company Cruiser, like /sell does.");
			AutoDeposit = file.Bind<bool>("Bank", "AutoDeposit", false, "Deposit all scrap on the ship into the bank at the end of each day, just before the game saves in orbit. Same items as /bank deposit all. Toggle in-game: /bank auto on|off.");
			ClearChatOnLaunch = file.Bind<bool>("Tournament", "ClearChatOnLaunch", true, "Wipe the chat for everyone when the lever is pulled on a tournament run, so the setup talk is not sitting over a scored landing. /clear does it at any time.");
			AllSuits = file.Bind<bool>("Tournament", "AllSuits", false, "Put every suit on the rack whenever a tournament kit is applied, even if the kit doesn't ask for it (a kit can also ask: \"suits\" in the builder). The added suits are taken back when the tournament ends and are never written to the save.");
			ShowBankOnTerminal = file.Bind<bool>("Bank", "ShowBankOnTerminal", true, "Show the bank's value beside the credits at the top right of the terminal.");
			PrivateLobbiesOnly = file.Bind<bool>("Bank", "PrivateLobbiesOnly", true, "The bank only works while the lobby is not public. Banked scrap is kept, just locked, while public.");
		}

		internal static bool IsKeptOnShip(string itemName)
		{
			if (string.IsNullOrEmpty(itemName))
			{
				return false;
			}
			IEnumerable<string> source = from s in (KeepOnShip.Value ?? "").Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s;
			return source.Any((string n) => string.Equals(n, itemName, StringComparison.OrdinalIgnoreCase));
		}
	}
	[BepInPlugin("local.simplehq", "SimpleHQ", "0.4.20")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("local.simplehq");

		public static Plugin Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		private void Awake()
		{
			Instance = this;
			Logger = ((BaseUnityPlugin)this).Logger;
			ModConfig.Init(((BaseUnityPlugin)this).Config);
			_harmony.PatchAll();
			Logger.LogInfo((object)"SimpleHQ v0.4.20 loaded.");
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "local.simplehq";

		public const string Name = "SimpleHQ";

		public const string Version = "0.4.20";
	}
	public static class TournamentInfo
	{
		public static bool Active { get; internal set; }

		public static string KitName { get; internal set; }
	}
}
namespace SimpleHQ.Patches
{
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	internal static class SessionStartPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				BankNet.Reset();
				BankNet.Register();
				ArenaMarker.Refresh();
				TournamentService.Reset();
				TournamentNet.Register();
				ItemPlaceNet.Register();
				GunStateNet.Register();
				DecorService.Register();
				ChatClear.Register();
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton != (Object)null) || !singleton.IsHost)
				{
					return;
				}
				if (ArenaMarker.Active)
				{
					Plugin.Logger.LogInfo((object)"[Arena] PVP save: the shared bank stays out of this lobby.");
					return;
				}
				BankStore.LoadForCurrentSave();
				BankNet.Publish();
				if (BankStore.RolledBack)
				{
					((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(AnnounceRollback());
				}
				else if (BankStore.HealedCount > 0)
				{
					((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(AnnounceHealed(BankStore.HealedCount, BankStore.HealedValue));
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[SessionStartPatch] {arg}");
			}
		}

		private static IEnumerator AnnounceHealed(int n, int value)
		{
			yield return (object)new WaitForSeconds(4f);
			ChatUtil.Send($"{n} item(s) (${value}) from the last end-of-day deposit were still on the ship in this save " + "(an old SimpleHQ bug). They stay on the ship and are out of the bank, so nothing counts twice. " + $"Bank: {BankStore.Items.Count} item(s), ${BankStore.Total}.", broadcast: true);
		}

		private static IEnumerator AnnounceRollback()
		{
			yield return (object)new WaitForSeconds(4f);
			ChatUtil.Send("This save was rolled back since the bank was written, so the bank is NOT loaded (it would have duplicated the scrap). The old bank file is kept in LocalLow/ZeekerssRBLX/Lethal Company/SimpleHQ.", broadcast: true);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
	internal static class PlayerJoinedPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				BankNet.Publish();
				ItemPlaceNet.Resend();
				TournamentService.OnPlayersChanged();
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[PlayerJoinedPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
	internal static class SaveCommitPatch
	{
		[HarmonyPostfix]
		private static void Postfix(GameNetworkManager __instance)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if (__instance.isHostingGame && !((Object)(object)instance == (Object)null) && !instance.isChallengeFile && instance.inShipPhase && !ArenaMarker.Active)
				{
					BankStore.Commit();
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[SaveCommitPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
	internal static class AutoDepositPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			BankService.AutoDepositEndOfDay();
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			TournamentRun.OnShipInOrbit();
		}
	}
	[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
	internal static class WipePatch
	{
		[HarmonyPrefix]
		private static void Prefix(bool despawnAllItems)
		{
			TournamentRun.NoteWipe();
			TournamentRun.BeforeMassDespawn(despawnAllItems);
			BankService.OnPropsDespawning(despawnAllItems);
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")]
	internal static class FiredPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			TournamentRun.OnFired();
			BankService.OnFired();
		}
	}
	internal static class ChatPrefix
	{
		internal static string Strip(string chatMessage)
		{
			if (string.IsNullOrEmpty(chatMessage))
			{
				return null;
			}
			string value = ModConfig.CommandPrefix.Value;
			string value2 = ModConfig.AltCommandPrefix.Value;
			if (!string.IsNullOrEmpty(value) && chatMessage.StartsWith(value))
			{
				return chatMessage.Substring(value.Length).Trim();
			}
			if (!string.IsNullOrEmpty(value2) && chatMessage.StartsWith(value2))
			{
				return chatMessage.Substring(value2.Length).Trim();
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	internal static class HostChatPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static bool Prefix(string chatMessage, int playerId)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null)
				{
					return true;
				}
				string text = ChatPrefix.Strip(chatMessage);
				if (!singleton.IsHost)
				{
					if (text == null || playerId < 0)
					{
						return true;
					}
					string[] array = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
					if (array.Length == 0 || array[0].ToLowerInvariant() != "clear")
					{
						return true;
					}
					ChatClear.Local();
					if (array.Length >= 2 && (array[1].ToLowerInvariant() == "all" || array[1].ToLowerInvariant() == "everyone"))
					{
						ChatUtil.Send("Cleared your chat. Only the host can clear everyone's.");
					}
					return false;
				}
				if (text == null || !CommandRouter.IsOurs(text))
				{
					return true;
				}
				if (!CommandRouter.IsSenderTheHost(playerId))
				{
					return true;
				}
				CommandRouter.Route(text, null);
				return false;
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[HostChatPatch] {arg}");
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	internal static class RemoteChatPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static bool Prefix(string chatMessage, int playerId)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsHost)
				{
					return true;
				}
				string text = ChatPrefix.Strip(chatMessage);
				if (text == null || !CommandRouter.IsOurs(text))
				{
					return true;
				}
				if (CommandRouter.IsSenderTheHost(playerId))
				{
					return true;
				}
				StartOfRound instance = StartOfRound.Instance;
				if (instance?.allPlayerScripts == null || playerId < 0 || playerId >= instance.allPlayerScripts.Length)
				{
					return true;
				}
				PlayerControllerB val = instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null || !val.isPlayerControlled)
				{
					return true;
				}
				ChatUtil.BroadcastReplies = true;
				try
				{
					CommandRouter.Route(text, val.playerUsername, val);
				}
				finally
				{
					ChatUtil.BroadcastReplies = false;
				}
				return false;
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[RemoteChatPatch] {arg}");
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal static class GrabBeforeStartPatch
	{
		private static bool Hide()
		{
			try
			{
				if (!TournamentNet.ActiveHere)
				{
					return false;
				}
				GameNetworkManager instance = GameNetworkManager.Instance;
				if ((Object)(object)instance == (Object)null || instance.gameHasStarted)
				{
					return false;
				}
				instance.gameHasStarted = true;
				return true;
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[GrabBeforeStartPatch.Hide] {arg}");
				return false;
			}
		}

		private static void Restore(bool hidden)
		{
			if (hidden && !((Object)(object)GameNetworkManager.Instance == (Object)null))
			{
				GameNetworkManager.Instance.gameHasStarted = false;
			}
		}

		[HarmonyPatch("BeginGrabObject")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static void GrabPrefix(out bool __state)
		{
			__state = Hide();
		}

		[HarmonyPatch("BeginGrabObject")]
		[HarmonyFinalizer]
		private static void GrabFinalizer(bool __state)
		{
			Restore(__state);
		}

		[HarmonyPatch("SetHoverTipAndCurrentInteractTrigger")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static void TipPrefix(out bool __state)
		{
			__state = Hide();
		}

		[HarmonyPatch("SetHoverTipAndCurrentInteractTrigger")]
		[HarmonyFinalizer]
		private static void TipFinalizer(bool __state)
		{
			Restore(__state);
		}
	}
	[HarmonyPatch(typeof(VehicleController), "Start")]
	internal static class MagnetStatePatch
	{
		[HarmonyPostfix]
		private static void Postfix(VehicleController __instance)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if (!((Object)(object)instance == (Object)null) && TournamentNet.ActiveHere && instance.inShipPhase && __instance.magnetedToShip)
				{
					instance.isObjectAttachedToMagnet = true;
					instance.attachedVehicle = __instance;
					instance.magnetOn = true;
					if ((Object)(object)instance.magnetLever != (Object)null)
					{
						instance.magnetLever.initialBoolState = true;
						instance.magnetLever.setInitialState = true;
						instance.magnetLever.SetInitialState();
					}
					Plugin.Logger.LogInfo((object)"[Tournament] kit cruiser on the magnet; magnet switched on.");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[MagnetStatePatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SyncScrapValuesClientRpc")]
	internal static class ScrapSyncPatch
	{
		internal struct Saved
		{
			public bool Active;

			public float Total;

			public int Collected;

			public int Found;
		}

		private const int TagA = 1397248305;

		private const int TagB = 1447248204;

		internal static int[] Tagged(int[] values, int count)
		{
			int[] array = new int[values.Length + 2];
			values.CopyTo(array, 0);
			array[values.Length] = 1397248305;
			array[values.Length + 1] = 0x5643414C ^ count;
			return array;
		}

		internal static bool IsTagged(NetworkObjectReference[] refs, int[] values)
		{
			if (refs != null && values != null && values.Length == refs.Length + 2 && values[refs.Length] == 1397248305)
			{
				return values[refs.Length + 1] == (0x5643414C ^ refs.Length);
			}
			return false;
		}

		[HarmonyPrefix]
		private static void Prefix(RoundManager __instance, NetworkObjectReference[] spawnedScrap, int[] allScrapValue, out Saved __state)
		{
			__state = default(Saved);
			try
			{
				if (!((Object)(object)__instance == (Object)null) && IsTagged(spawnedScrap, allScrapValue))
				{
					__state = new Saved
					{
						Active = true,
						Total = __instance.totalScrapValueInLevel,
						Collected = __instance.scrapCollectedInLevel,
						Found = __instance.valueOfFoundScrapItems
					};
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[ScrapSync.Prefix] {arg}");
			}
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(RoundManager __instance, Saved __state, Exception __exception)
		{
			try
			{
				if (!__state.Active || (Object)(object)__instance == (Object)null)
				{
					return __exception;
				}
				bool flag = __instance.totalScrapValueInLevel != __state.Total || __instance.scrapCollectedInLevel != __state.Collected || __instance.valueOfFoundScrapItems != __state.Found;
				__instance.totalScrapValueInLevel = __state.Total;
				__instance.scrapCollectedInLevel = __state.Collected;
				__instance.valueOfFoundScrapItems = __state.Found;
				if (flag)
				{
					Plugin.Logger.LogInfo((object)$"[ScrapSync] kept the day's scrap totals after SimpleHQ's value sync (total {__state.Total}, collected {__state.Collected}, found {__state.Found}).");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[ScrapSync.Finalizer] {arg}");
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Terminal), "Update")]
	internal static class TerminalCreditsPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Terminal __instance)
		{
			try
			{
				if (ModConfig.ShowBankOnTerminal.Value && __instance.terminalInUse && !((Object)(object)__instance.topRightText == (Object)null) && BankNet.Received && BankNet.Count != 0)
				{
					if (((TMP_Text)__instance.topRightText).enableWordWrapping)
					{
						((TMP_Text)__instance.topRightText).enableWordWrapping = false;
					}
					((TMP_Text)__instance.topRightText).text = $"${__instance.groupCredits} <size=55%><color=#ff6a33>${BankNet.Total}</color></size>";
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TerminalCreditsPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	internal static class TerminalBankPatch
	{
		private static TerminalNode _node;

		internal const int CodeLine = 1000;

		internal const int CodeGather = 1400;

		private static bool _awaitingCode;

		private static string _codeSoFar = "";

		private static int _savedCharacterLimit = -1;

		private static bool BuilderActive
		{
			get
			{
				if (KitBuilder.Current != KitBuilder.Step.Off)
				{
					return KitBuilder.Current != KitBuilder.Step.Done;
				}
				return false;
			}
		}

		private static bool EditorActive => KitEditor.Current != KitEditor.Step.Off;

		[HarmonyPrefix]
		private static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			try
			{
				string text = __instance.screenText.text;
				int num = Mathf.Clamp(__instance.textAdded, 0, text.Length);
				string text2 = text.Substring(text.Length - num).Trim();
				string text3 = __instance.RemovePunctuation(text2).Trim().ToLowerInvariant();
				switch (text3)
				{
				case "tournament edit":
				case "edit code":
				case "editcode":
					if (TournamentNet.ActiveHere)
					{
						return ShowPage(__instance, "\n\n\nEDIT A KIT CODE\n\nNot during a run.\n\n", ref __result);
					}
					SetTypingRoom(__instance, roomy: true);
					return ShowPage(__instance, "\n\n\n" + KitEditor.Start() + "\n\n", ref __result);
				default:
					if (EditorActive)
					{
						if (text3 == "cancel")
						{
							KitEditor.Cancel();
							SetTypingRoom(__instance, roomy: false);
							return ShowPage(__instance, "\n\n\nEDIT A KIT CODE\n\nCancelled.\n\n", ref __result);
						}
						string text4 = KitEditor.Answer(text2.Trim());
						if (!EditorActive)
						{
							SetTypingRoom(__instance, roomy: false);
						}
						return ShowPage(__instance, "\n\n\n" + text4 + "\n\n", ref __result);
					}
					switch (text3)
					{
					case "tournament builder":
					case "tournament build":
					case "builder":
						if (TournamentNet.ActiveHere)
						{
							return ShowPage(__instance, "\n\n\nTOURNAMENT BUILDER\n\nNot during a run: build codes between tournaments.\n\n", ref __result);
						}
						SetTypingRoom(__instance, roomy: true);
						return ShowPage(__instance, "\n\n\n" + KitBuilder.Start() + "\n\n", ref __result);
					default:
					{
						if (BuilderActive)
						{
							if (text3 == "cancel")
							{
								KitBuilder.Cancel();
								SetTypingRoom(__instance, roomy: false);
								return ShowPage(__instance, "\n\n\nTOURNAMENT BUILDER\n\nCancelled.\n\n", ref __result);
							}
							string text5 = KitBuilder.Answer(text2.Trim());
							if (!BuilderActive)
							{
								SetTypingRoom(__instance, roomy: false);
							}
							return ShowPage(__instance, "\n\n\n" + text5 + "\n\n", ref __result);
						}
						if (_awaitingCode)
						{
							string text6;
							if (text3 == "cancel")
							{
								_awaitingCode = false;
								_codeSoFar = "";
								SetTypingRoom(__instance, roomy: false);
								text6 = "\n\n\nTOURNAMENT\n\nCancelled.\n\n";
							}
							else if (text3.Length == 0)
							{
								text6 = "\n\n\nTOURNAMENT\n\nType the code (or the rest of it), or cancel.\n\n";
							}
							else
							{
								_codeSoFar += text2.Trim();
								if (TournamentService.CanDecode(_codeSoFar))
								{
									_awaitingCode = false;
									SetTypingRoom(__instance, roomy: false);
									string codeSoFar = _codeSoFar;
									_codeSoFar = "";
									Kit activeKit = TournamentService.ActiveKit;
									TournamentService.Load(codeSoFar);
									bool flag = TournamentService.ActiveKit != null && TournamentService.ActiveKit != activeKit;
									text6 = "\n\n\nTOURNAMENT\n\n" + (flag ? ("Kit loaded: " + TournamentService.ActiveKit.name + "\nRouting to " + TournamentService.ActiveKit.days[0].moon + ". Pull the lever when ready.\n\n") : "That kit can't be used here. Chat says why.\nType tournament to try again.\n\n");
								}
								else if (_codeSoFar.Length > 1400)
								{
									_awaitingCode = false;
									SetTypingRoom(__instance, roomy: false);
									_codeSoFar = "";
									text6 = "\n\n\nTOURNAMENT\n\nThat code doesn't check out.\nType tournament to start again.\n\n";
								}
								else
								{
									text6 = $"\n\n\nTOURNAMENT\n\nCode so far: {Strip(_codeSoFar).Length} characters.\n" + "Type the rest and press Enter (cancel to stop).\n\n";
								}
							}
							return ShowPage(__instance, text6, ref __result);
						}
						bool flag2 = text3 == "bank" || text3.StartsWith("bank ");
						bool flag3 = text3 == "sell" || text3.StartsWith("sell ");
						bool flag4 = text3 == "tournament" || text3.StartsWith("tournament ") || text3 == "agree";
						if (!flag2 && !flag3 && !flag4)
						{
							return true;
						}
						if (!flag4 && TournamentNet.ActiveHere)
						{
							return true;
						}
						string displayText;
						if (text3 == "tournament" && (Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsHost)
						{
							if (TournamentInfo.Active)
							{
								_awaitingCode = true;
								_codeSoFar = "";
								SetTypingRoom(__instance, roomy: true);
								displayText = "\n\n\nTOURNAMENT\n\n" + TournamentService.TerminalStatus() + "\n\nType the organisers' kit code and press Enter.\nDashes and case don't matter.\n(Type cancel to back out.)\n\n";
							}
							else if (TournamentService.Proposed)
							{
								displayText = "\n\n\nTOURNAMENT\n\n" + TournamentService.TerminalStatus() + "\n\n";
							}
							else
							{
								TournamentService.Start();
								displayText = "\n\n\nTOURNAMENT\n\n" + TournamentService.TerminalStatus() + "\n\nEveryone types /agree in chat. Then the ship\nwaits at the Company: type tournament again\nhere to enter the code.\n\n(No code yet? Type tournament builder\nto make one,\nor tournament edit to change one.)\n\n";
							}
						}
						else if (flag4)
						{
							string[] array = text2.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
							string command = ((array.Length >= 3 && array[1].ToLowerInvariant() == "load") ? ("tournament load " + array[2]) : text3);
							displayText = (SendToHost(command) ? "\n\n\nTOURNAMENT\n\nSent. The reply shows in chat.\n\n" : "\n\n\nTOURNAMENT\n\nCouldn't reach the host.\n\n");
						}
						else if (flag2)
						{
							displayText = ((text3 == "bank") ? BuildText() : RunCommand(text3));
						}
						else
						{
							string text7 = ((text3.Length > 4) ? text3.Substring(5).Trim() : "");
							if (text7 == "bank" || text7.StartsWith("bank "))
							{
								displayText = RunCommand("bank sell " + text7.Substring(4).Trim());
							}
							else
							{
								if (!BankNet.HostHasSimpleSell)
								{
									return true;
								}
								displayText = RunSell(text7);
							}
						}
						if ((Object)(object)_node == (Object)null)
						{
							_node = ScriptableObject.CreateInstance<TerminalNode>();
							_node.clearPreviousText = true;
						}
						_node.maxCharactersToType = ((_awaitingCode || BuilderActive || EditorActive) ? 1000 : 40);
						_node.displayText = displayText;
						__result = _node;
						return false;
					}
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TerminalBankPatch] {arg}");
				return true;
			}
		}

		private static string Strip(string s)
		{
			return new string(s.Where(char.IsLetterOrDigit).ToArray());
		}

		private static void SetTypingRoom(Terminal terminal, bool roomy)
		{
			try
			{
				if ((Object)(object)terminal?.screenText == (Object)null)
				{
					return;
				}
				if (roomy)
				{
					if (_savedCharacterLimit < 0)
					{
						_savedCharacterLimit = terminal.screenText.characterLimit;
					}
					terminal.screenText.characterLimit = 0;
				}
				else if (_savedCharacterLimit >= 0)
				{
					terminal.screenText.characterLimit = _savedCharacterLimit;
					_savedCharacterLimit = -1;
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("[TerminalBankPatch] typing room: " + ex.Message));
			}
		}

		private static bool ShowPage(Terminal terminal, string text, ref TerminalNode result)
		{
			if ((Object)(object)_node == (Object)null)
			{
				_node = ScriptableObject.CreateInstance<TerminalNode>();
				_node.clearPreviousText = true;
			}
			_node.maxCharactersToType = ((_awaitingCode || BuilderActive || EditorActive) ? 1000 : 40);
			_node.displayText = text;
			result = _node;
			return false;
		}

		private static string RunCommand(string typed)
		{
			string text = typed.Substring("bank ".Length).Trim();
			string command;
			string text3;
			if (text.StartsWith("deposit ") || text.StartsWith("d "))
			{
				string text2 = text.Substring(text.IndexOf(' ') + 1).Trim();
				command = "bank deposit " + text2;
				text3 = "Depositing " + text2 + ".";
			}
			else if (text.StartsWith("withdraw ") || text.StartsWith("w "))
			{
				string text4 = text.Substring(text.IndexOf(' ') + 1).Trim();
				command = "bank withdraw " + text4;
				text3 = "Withdrawing " + text4 + ".";
			}
			else if (text == "auto" || text.StartsWith("auto "))
			{
				command = "bank " + text;
				text3 = ((text == "auto") ? "Checking auto deposit." : ("Turning auto deposit " + text.Substring(5).Trim() + "."));
			}
			else
			{
				switch (text)
				{
				case "info":
					command = "bank info";
					text3 = "Telling everyone how the bank works.";
					break;
				case "list":
				case "l":
					command = "bank list";
					text3 = "Listing the bank in chat.";
					break;
				default:
					if (text.StartsWith("sell "))
					{
						string text5 = text.Substring("sell ".Length).Trim();
						command = "sell bank " + text5;
						text3 = "Selling " + text5 + " from the bank.";
						break;
					}
					return "\n\n\nSCRAP BANK\n\nbank                          show the bank\nbank deposit <amount|all>     store ship scrap\nbank deposit <item> [count]\nbank withdraw <item> [count|all] (orbit or landed)\nbank withdraw all             whole bank, by the door\nbank auto on|off              deposit at end of day\nbank list                     list it in chat\nbank info                     explain the bank to everyone\nbank sell <amount|quota|all>  at the Company\n\n";
				}
			}
			if (!SendToHost(command))
			{
				return "\n\n\nSCRAP BANK\n\nCouldn't reach the host.\n\n";
			}
			return "\n\n\nSCRAP BANK\n\n" + text3 + "\nThe result shows in chat. Type bank to see the bank.\n\n";
		}

		private static string RunSell(string rest)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)singleton == (Object)null || (Object)(object)val == (Object)null || (Object)(object)HUDManager.Instance == (Object)null)
			{
				return "\n\n\nSELL\n\nCouldn't reach the host.\n\n";
			}
			if (singleton.IsHost)
			{
				HUDManager.Instance.AddTextToChatOnServer(("/sell " + rest).Trim(), (int)val.playerClientId);
				if (rest.Length != 0)
				{
					return "\n\n\nSELL\n\nSelling " + rest + ".\nThe result shows in chat.\n\n";
				}
				return "\n\n\nSELL\n\nsell <amount>, sell quota, sell all, sell <item> [count]\nsell bank <amount|quota|all>\n\n";
			}
			HUDManager.Instance.AddTextToChatOnServer(("!sell " + rest).Trim(), (int)val.playerClientId);
			return "\n\n\nSELL\n\nSent \"sell " + rest + "\" to the host.\nIt only runs if the host lets you sell\n(SimpleSell whitelist). The result shows in chat.\n\n";
		}

		private static bool SendToHost(string command)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)singleton == (Object)null || (Object)(object)val == (Object)null)
			{
				return false;
			}
			if (singleton.IsHost)
			{
				CommandRouter.Route(command, null);
				return true;
			}
			string text = ((!string.IsNullOrEmpty(ModConfig.AltCommandPrefix.Value)) ? ModConfig.AltCommandPrefix.Value : ModConfig.CommandPrefix.Value);
			HUDManager instance = HUDManager.Instance;
			if (instance != null)
			{
				instance.AddTextToChatOnServer(text + command, (int)val.playerClientId);
			}
			return true;
		}

		private static string BuildText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("\n\n\nSCRAP BANK\n\n");
			if (!BankNet.Received)
			{
				stringBuilder.Append("No bank from the host. The host needs SimpleHQ installed.\n\n");
				return stringBuilder.ToString();
			}
			if (BankNet.Locked)
			{
				stringBuilder.Append("LOCKED: the lobby is public. Host as Friends only,\nor /lobby friends with SimpleSell.\n\n");
			}
			stringBuilder.Append($"Total value: ${BankNet.Total}\n");
			stringBuilder.Append($"Items: {BankNet.Count}\n\n");
			foreach (BankGroup group in BankNet.Groups)
			{
				stringBuilder.Append($"* {group.Name} x{group.Count}   ${group.Value}\n");
			}
			stringBuilder.Append("\nDeposit from the ship: bank deposit <amount|all>\n");
			stringBuilder.Append("Sell at the Company: bank sell <amount|quota|all>\n");
			stringBuilder.Append("(also /bank deposit and /sell bank in chat)\n\n");
			return stringBuilder.ToString();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
	internal static class TournamentApprovalPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ConnectionApprovalRequest request, ConnectionApprovalResponse response)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (response != null && response.Approved && TournamentInfo.Active)
				{
					ulong clientNetworkId = request.ClientNetworkId;
					NetworkManager singleton = NetworkManager.Singleton;
					if (clientNetworkId != ((singleton != null) ? new ulong?(singleton.LocalClientId) : ((ulong?)null)))
					{
						response.Approved = false;
						response.Reason = "A tournament run is in progress.";
						Plugin.Logger.LogInfo((object)"[Tournament] refused a join: run in progress.");
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentApprovalPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Singleton_OnClientDisconnectCallback")]
	internal static class TournamentDisconnectPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsHost)
				{
					TournamentService.OnPlayersChanged();
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentDisconnectPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	internal static class TournamentRouteLockPatch
	{
		private static TerminalNode _node;

		[HarmonyPostfix]
		private static void Postfix(ref TerminalNode __result)
		{
			try
			{
				int lockedLevelId = TournamentApply.LockedLevelId;
				if ((Object)(object)__result == (Object)null || lockedLevelId < 0 || !TournamentNet.ActiveHere)
				{
					return;
				}
				int num = ((__result.buyRerouteToMoon >= 0) ? __result.buyRerouteToMoon : ((__result.buyRerouteToMoon == -2) ? __result.displayPlanetInfo : (-1)));
				if (num >= 0)
				{
					if ((Object)(object)_node == (Object)null)
					{
						_node = ScriptableObject.CreateInstance<TerminalNode>();
						_node.clearPreviousText = true;
						_node.maxCharactersToType = 25;
					}
					SelectableLevel[] array = StartOfRound.Instance?.levels;
					string text = ((array != null && lockedLevelId < array.Length) ? TournamentApply.ShortName(array[lockedLevelId].PlanetName) : "the kit's moon");
					_node.displayText = ((num == lockedLevelId) ? ("\n\n\nTOURNAMENT\n\nThe ship is already routed to " + text + ",\nfree. No need to route.\n\n") : ("\n\n\nTOURNAMENT\n\nRouting is locked to " + text + " for this run.\n\n"));
					__result = _node;
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentRouteLockPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(StartMatchLever), "LeverAnimation")]
	internal static class TournamentLeverLockPatch
	{
		internal const string Tip = "[ Waiting for the tournament code ]";

		internal static bool Locked(StartMatchLever lever)
		{
			if (TournamentApply.LeverLocked && TournamentNet.ActiveHere && (Object)(object)lever?.playersManager != (Object)null)
			{
				return lever.playersManager.inShipPhase;
			}
			return false;
		}

		[HarmonyPrefix]
		private static bool Prefix(StartMatchLever __instance)
		{
			try
			{
				if (!Locked(__instance))
				{
					return true;
				}
				HUDManager instance = HUDManager.Instance;
				if (instance != null)
				{
					instance.DisplayTip("Tournament", "The ship waits at the Company until the host enters the tournament code.", false, false, "LC_Tip1");
				}
				return false;
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentLeverLockPatch] {arg}");
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(StartMatchLever), "Update")]
	internal static class TournamentLeverTipPatch
	{
		[HarmonyPostfix]
		private static void Postfix(StartMatchLever __instance)
		{
			if ((Object)(object)__instance.triggerScript != (Object)null && TournamentLeverLockPatch.Locked(__instance))
			{
				__instance.triggerScript.hoverTip = "[ Waiting for the tournament code ]";
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class TournamentStartGameGuardPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(StartOfRound __instance)
		{
			try
			{
				if (!TournamentInfo.Active || (!TournamentApply.LeverLocked && !TournamentApply.SettingUpDay) || !__instance.inShipPhase)
				{
					return true;
				}
				StartMatchLever obj = Object.FindObjectOfType<StartMatchLever>();
				if (obj != null)
				{
					obj.CancelStartGameClientRpc();
				}
				if (TournamentApply.SettingUpDay)
				{
					ChatUtil.Send("Wait a moment: the next day's kit is still being put on the ship.", broadcast: true);
				}
				Plugin.Logger.LogInfo((object)(TournamentApply.SettingUpDay ? "[Tournament] landing refused: circuit day still being set up." : "[Tournament] landing refused: waiting for the code."));
				return false;
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentStartGameGuardPatch] {arg}");
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "PassTimeToNextDay")]
	internal static class TournamentDayEndPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			TournamentRun.OnDayEnding();
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			TournamentRun.OnDayPassed();
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class TournamentTimerPatch
	{
		[HarmonyPostfix]
		private static void Postfix(StartOfRound __instance)
		{
			if (__instance.beganLoadingNewLevel)
			{
				TournamentRun.OnLanding();
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "KillPlayerClientRpc")]
	internal static class TournamentDeathPatch
	{
		[HarmonyPostfix]
		private static void Postfix(int playerId)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				string who = ((!((Object)(object)instance != (Object)null) || playerId < 0 || playerId >= instance.allPlayerScripts.Length) ? null : instance.allPlayerScripts[playerId]?.playerUsername);
				TournamentRun.OnPlayerDied(who);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentDeathPatch] {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class TournamentChatClearPatch
	{
		[HarmonyPostfix]
		private static void Postfix(StartOfRound __instance)
		{
			try
			{
				if (!((Object)(object)NetworkManager.Singleton == (Object)null) && NetworkManager.Singleton.IsHost && TournamentNet.ActiveHere && ModConfig.ClearChatOnLaunch.Value && __instance.beganLoadingNewLevel)
				{
					ChatClear.Everyone();
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[TournamentChatClearPatch] {arg}");
			}
		}
	}
}
namespace SimpleHQ.Features
{
	internal static class BankService
	{
		internal static void Deposit(string arg, string who)
		{
			try
			{
				if (!Ready(out var why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (!BankGate.CanMoveScrap(out why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (string.IsNullOrWhiteSpace(arg))
				{
					ChatUtil.Send("Usage: /bank deposit <amount> | all | <item> [count|all]");
					return;
				}
				List<GrabbableObject> list = FindDepositable();
				if (list.Count == 0)
				{
					ChatUtil.Send("No scrap on the ship to deposit.");
					return;
				}
				string text = arg.Trim().ToLowerInvariant();
				List<GrabbableObject> list2;
				int result;
				if (text == "all")
				{
					list2 = list;
				}
				else if (int.TryParse(text.TrimStart('$'), out result))
				{
					if (result <= 0)
					{
						ChatUtil.Send("Amount must be above 0.");
						return;
					}
					int num = list.Sum((GrabbableObject o) => o.scrapValue);
					if (num < result)
					{
						ChatUtil.Send($"Only ${num} of scrap on the ship, not ${result}.");
						return;
					}
					list2 = ((num == result) ? list : BankSelect.ClosestAtOrAbove(list, (GrabbableObject o) => o.scrapValue, result));
				}
				else
				{
					list2 = MatchByName(list, arg, out var problem);
					if (list2 == null)
					{
						ChatUtil.Send(problem);
						return;
					}
				}
				List<BankEntry> list3 = Bank(list2);
				if (list3.Count == 0)
				{
					ChatUtil.Send("Nothing could be deposited.");
					return;
				}
				int num2 = list3.Sum((BankEntry e) => e.Value);
				string text2 = (string.IsNullOrEmpty(who) ? "Deposited" : (who + " deposited"));
				ChatUtil.Send($"{text2} {list3.Count} item(s), ${num2}. Bank: {BankStore.Items.Count} item(s), ${BankStore.Total}.", broadcast: true);
				Plugin.Logger.LogInfo((object)string.Format("[Bank] {0} deposited {1} item(s) ${2} ({3})", who ?? "host", list3.Count, num2, arg));
			}
			catch (Exception arg2)
			{
				Plugin.Logger.LogError((object)$"[BankService.Deposit] {arg2}");
			}
		}

		private static List<BankEntry> Bank(List<GrabbableObject> chosen)
		{
			List<BankEntry> list = new List<BankEntry>();
			foreach (GrabbableObject item in chosen)
			{
				NetworkObject component = ((Component)item).GetComponent<NetworkObject>();
				if (!((Object)(object)component == (Object)null) && component.IsSpawned)
				{
					list.Add(new BankEntry
					{
						Name = item.itemProperties.itemName,
						Value = item.scrapValue,
						ItemId = ItemSpawner.IdOf(item.itemProperties),
						Data = ItemSpawner.SaveDataOf(item)
					});
					MarkGone(item);
					component.Despawn(true);
				}
			}
			if (list.Count > 0)
			{
				BankStore.Add(list);
				BankNet.Publish();
			}
			return list;
		}

		internal static void MarkGone(GrabbableObject o)
		{
			if (!((Object)(object)o == (Object)null))
			{
				o.deactivated = true;
				o.grabbable = false;
				o.grabbableToEnemies = false;
			}
		}

		internal static void SetAuto(string arg, string who)
		{
			string text = (arg ?? "").Trim().ToLowerInvariant();
			if (text == "on" || text == "off")
			{
				ModConfig.AutoDeposit.Value = text == "on";
				string text2 = (string.IsNullOrEmpty(who) ? "" : (" (" + who + ")"));
				ChatUtil.Send(ModConfig.AutoDeposit.Value ? ("Auto deposit ON" + text2 + ": scrap on the ship goes into the bank at the end of each day.") : ("Auto deposit OFF" + text2 + "."), broadcast: true);
			}
			else
			{
				ChatUtil.Send("Auto deposit is " + (ModConfig.AutoDeposit.Value ? "ON" : "OFF") + ". /bank auto on|off");
			}
		}

		internal static void AutoDepositEndOfDay()
		{
			try
			{
				if (!ModConfig.AutoDeposit.Value || TournamentInfo.Active)
				{
					return;
				}
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsHost)
				{
					return;
				}
				if (BankGate.IsLocked(out var reason))
				{
					Plugin.Logger.LogInfo((object)("[Bank] auto deposit skipped: " + reason));
					return;
				}
				List<GrabbableObject> list = FindDepositable();
				if (list.Count == 0)
				{
					return;
				}
				List<BankEntry> list2 = Bank(list);
				if (list2.Count != 0)
				{
					int num = list2.Sum((BankEntry e) => e.Value);
					ChatUtil.Send($"End of day: deposited {list2.Count} item(s), ${num}. Bank: {BankStore.Items.Count} item(s), ${BankStore.Total}.", broadcast: true);
					Plugin.Logger.LogInfo((object)$"[Bank] auto deposit: {list2.Count} item(s) ${num}");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[BankService.AutoDepositEndOfDay] {arg}");
			}
		}

		private static List<GrabbableObject> FindDepositable()
		{
			VehicleController vehicle = Object.FindObjectOfType<VehicleController>();
			HashSet<GrabbableObject> inBags = new HashSet<GrabbableObject>();
			BeltBagItem[] array = Object.FindObjectsByType<BeltBagItem>((FindObjectsSortMode)0);
			foreach (BeltBagItem val in array)
			{
				if (val.objectsInBag == null)
				{
					continue;
				}
				foreach (GrabbableObject item in val.objectsInBag)
				{
					if ((Object)(object)item != (Object)null)
					{
						inBags.Add(item);
					}
				}
			}
			return (from o in Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0)
				where (Object)(object)o != (Object)null && (Object)(object)o.itemProperties != (Object)null && o.itemProperties.isScrap
				where o.scrapValue > 0
				where !o.isHeld && !o.heldByPlayerOnServer && !o.isPocketed && !o.deactivated
				where !(o is RagdollGrabbableObject) && !(o is BeltBagItem) && !inBags.Contains(o)
				where !ModConfig.IsKeptOnShip(o.itemProperties.itemName)
				where o.isInShipRoom || o.isInElevator || (ModConfig.IncludeCruiser.Value && (Object)(object)vehicle != (Object)null && ((Component)o).transform.IsChildOf(((Component)vehicle).transform))
				select o).ToList();
		}

		private static List<GrabbableObject> MatchByName(List<GrabbableObject> eligible, string arg, out string problem)
		{
			problem = null;
			string[] array = arg.Trim().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			int count = int.MaxValue;
			string text = arg.Trim();
			if (array.Length >= 2)
			{
				string text2 = array[^1].ToLowerInvariant();
				int result;
				if (text2 == "all")
				{
					text = string.Join(" ", array, 0, array.Length - 1);
				}
				else if (int.TryParse(text2, out result) && result > 0)
				{
					count = result;
					text = string.Join(" ", array, 0, array.Length - 1);
				}
			}
			string norm = Normalize(text);
			List<GrabbableObject> list = (from o in eligible
				where Normalize(o.itemProperties.itemName).Contains(norm)
				orderby o.scrapValue
				select o).Take(count).ToList();
			if (list.Count == 0)
			{
				problem = (ModConfig.IsKeptOnShip(text) ? (text + " is on the KeepOnShip list and is never deposited.") : ("No scrap on the ship matching \"" + text + "\"."));
				return null;
			}
			return list;
		}

		private static string Normalize(string s)
		{
			return (s ?? "").Replace(" ", "").ToLowerInvariant();
		}

		internal static void Withdraw(string arg, string who, PlayerControllerB requester)
		{
			try
			{
				if (!Ready(out var why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (!BankGate.CanWithdraw(out why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (string.IsNullOrWhiteSpace(arg))
				{
					ChatUtil.Send("Usage: /bank withdraw <item> [count|all], or /bank withdraw all for everything");
					return;
				}
				if (BankStore.Items.Count == 0)
				{
					ChatUtil.Send("The bank is empty.");
					return;
				}
				string[] array = arg.Trim().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
				int count = 1;
				string text = arg.Trim();
				if (array.Length >= 2)
				{
					string text2 = array[^1].ToLowerInvariant();
					int result;
					if (text2 == "all")
					{
						count = int.MaxValue;
						text = string.Join(" ", array, 0, array.Length - 1);
					}
					else if (int.TryParse(text2, out result) && result > 0)
					{
						count = result;
						text = string.Join(" ", array, 0, array.Length - 1);
					}
				}
				string norm = Normalize(text);
				List<BankEntry> list = BankStore.Items.Where((BankEntry e) => Normalize(e.Name) == norm).ToList();
				if (list.Count == 0)
				{
					list = BankStore.Items.Where((BankEntry e) => Normalize(e.Name).Contains(norm)).ToList();
				}
				if (list.Count == 0)
				{
					ChatUtil.Send("Nothing in the bank matching \"" + text + "\". /bank list shows what's there.");
					return;
				}
				List<string> list2 = list.Select((BankEntry e) => e.Name).Distinct().ToList();
				if (list2.Count > 1)
				{
					ChatUtil.Send("\"" + text + "\" matches " + string.Join(", ", list2) + ". Be more specific.");
					return;
				}
				List<BankEntry> entries = list.OrderByDescending((BankEntry e) => e.Value).Take(count).ToList();
				PlayerControllerB near = requester ?? GameNetworkManager.Instance?.localPlayerController;
				List<BankEntry> list3 = ItemSpawner.SpawnOnShip(entries, near);
				if (list3.Count == 0)
				{
					ChatUtil.Send("Couldn't spawn " + list2[0] + ". It stays in the bank.");
					return;
				}
				BankStore.Remove(list3);
				BankNet.Publish();
				int num = list3.Sum((BankEntry e) => e.Value);
				string text3 = (string.IsNullOrEmpty(who) ? "Withdrew" : (who + " withdrew"));
				ChatUtil.Send($"{text3} {list3.Count} {list2[0]} (${num}). Bank: {BankStore.Items.Count} item(s), ${BankStore.Total}.", broadcast: true);
				Plugin.Logger.LogInfo((object)string.Format("[Bank] {0} withdrew {1} item(s) ${2} ({3})", who ?? "host", list3.Count, num, arg));
			}
			catch (Exception arg2)
			{
				Plugin.Logger.LogError((object)$"[BankService.Withdraw] {arg2}");
			}
		}

		internal static void WithdrawAll(string who)
		{
			try
			{
				if (!Ready(out var why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (TournamentInfo.Active)
				{
					ChatUtil.Send("Tournament mode: the bank is off until the run ends.");
					return;
				}
				if (!BankGate.CanWithdraw(out why))
				{
					ChatUtil.Send(why);
					return;
				}
				if (BankStore.Items.Count == 0)
				{
					ChatUtil.Send("The bank is empty, so there's nothing to withdraw. /bank deposit all stores the ship's scrap.");
					return;
				}
				StartOfRound instance = StartOfRound.Instance;
				int num = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0).Length;
				int num2 = (((Object)(object)instance != (Object)null) ? (instance.maxShipItemCapacity - num) : int.MaxValue);
				if (num2 <= 0)
				{
					ChatUtil.Send($"The ship already holds {num} items, the most the game saves ({instance.maxShipItemCapacity}). " + "Nothing withdrawn; the bank is unchanged.");
					return;
				}
				List<BankEntry> list = BankStore.Items.OrderByDescending((BankEntry e) => e.Value).ToList();
				int num3 = Mathf.Max(0, list.Count - num2);
				if (list.Count > num2)
				{
					list = list.Take(num2).ToList();
				}
				List<Vector3> spots = ItemSpawner.DoorwaySpots(list.Count);
				PlayerControllerB near = ((spots.Count != 0) ? null : GameNetworkManager.Instance?.localPlayerController);
				List<BankEntry> list2 = new List<BankEntry>();
				for (int num4 = 0; num4 < list.Count; num4 += 40)
				{
					List<BankEntry> range = list.GetRange(num4, Mathf.Min(40, list.Count - num4));
					List<Vector3> positions = ((spots.Count == 0) ? null : (from k in Enumerable.Range(num4, range.Count)
						select spots[k % spots.Count]).ToList());
					list2.AddRange(ItemSpawner.SpawnOnShip(range, near, null, positions));
				}
				BankStore.Remove(list2);
				BankNet.Publish();
				if (list2.Count == 0)
				{
					ChatUtil.Send("Couldn't spawn any banked items. They stay in the bank.");
					return;
				}
				int num5 = list2.Sum((BankEntry e) => e.Value);
				string text = (string.IsNullOrEmpty(who) ? "Withdrew" : (who + " withdrew"));
				string text2 = ((BankStore.Items.Count == 0) ? "The bank is empty." : $"Still banked: {BankStore.Items.Count} item(s), ${BankStore.Total}.");
				ChatUtil.Send($"{text} all {list2.Count} item(s) (${num5}) onto the ship floor by the door. {text2}", broadcast: true);
				if (num3 > 0)
				{
					ChatUtil.Send($"{num3} item(s) stayed in the bank: the game only saves {instance.maxShipItemCapacity} items " + "on the ship. Sell or deposit some, then withdraw again.", broadcast: true);
				}
				int num6 = list.Count - list2.Count;
				if (num6 > 0)
				{
					ChatUtil.Send($"{num6} item(s) don't exist in this game (a removed mod?) and stay in the bank.");
				}
				Plugin.Logger.LogInfo((object)(string.Format("[Bank] {0} withdrew all: {1} item(s) ${2} at the door ", who ?? "host", list2.Count, num5) + $"({spots.Count} spot(s)); {BankStore.Items.Count} left (cap {num3}, unknown {num6})"));
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[BankService.WithdrawAll] {arg}");
			}
		}

		internal static void SellFromBank(string arg, string who)
		{
			try
			{
				if (!Ready(out var why))
				{
					ChatUtil.Send(why);
					return;
				}
				DepositItemsDesk val = Object.FindObjectOfType<DepositItemsDesk>();
				if ((Object)(object)val == (Object)null)
				{
					ChatUtil.Send("No sell desk here. Land at the Company first.");
					return;
				}
				if (val.inSellingItemsAnimation || val.attacking)
				{
					ChatUtil.Send("The Company is busy. Wait for the current sale to finish.");
					return;
				}
				if (val.itemsOnCounter.Count > 0 || ((Component)val.deskObjectsContainer).GetComponentsInChildren<GrabbableObject>().Length != 0)
				{
					ChatUtil.Send("Items are on the counter. Sell or take them back first.");
					return;
				}
				if (BankStore.Items.Count == 0)
				{
					ChatUtil.Send("The bank is empty.");
					return;
				}
				float num = Mathf.Max(0.01f, StartOfRound.Instance.companyBuyingRate);
				string text = (arg ?? "").Trim().ToLowerInvariant();
				List<BankEntry> list;
				int num2;
				int total;
				switch (text)
				{
				case "all":
					list = BankStore.Items.ToList();
					break;
				case "quota":
				case "q":
				{
					int num3 = Mathf.Max(0, TimeOfDay.Instance.profitQuota - TimeOfDay.Instance.quotaFulfilled);
					if (num3 <= 0)
					{
						ChatUtil.Send("Quota already met.");
						return;
					}
					num2 = Mathf.CeilToInt((float)num3 / num);
					goto IL_0172;
				}
				default:
					{
						if (int.TryParse(text.TrimStart('$'), out var result) && result > 0)
						{
							num2 = Mathf.CeilToInt((float)result / num);
							goto IL_0172;
						}
						ChatUtil.Send("Usage: /sell bank <amount> | quota | all");
						return;
					}
					IL_0172:
					total = BankStore.Total;
					if (total < num2)
					{
						ChatUtil.Send($"The bank only has ${total} of scrap (${(int)((float)total * num)} at today's rate). /sell bank all sells it all.");
						return;
					}
					list = ((total == num2) ? BankStore.Items.ToList() : BankSelect.ClosestAtOrAbove(BankStore.Items, (BankEntry e) => e.Value, num2));
					break;
				}
				if (list.Count == 0)
				{
					ChatUtil.Send("Nothing to sell.");
					return;
				}
				int num4 = list.Sum((BankEntry e) => e.Value);
				float companyBuyingRate = StartOfRound.Instance.companyBuyingRate;
				int num5 = (int)((float)num4 * companyBuyingRate);
				Terminal val2 = Object.FindObjectOfType<Terminal>();
				BankStore.Remove(list);
				val.inSellingItemsAnimation = true;
				val.itemsOnCounterAmount = list.Count;
				val2.groupCredits += num5;
				val.SellItemsClientRpc(num5, val2.groupCredits, list.Count, companyBuyingRate);
				val.SellAndDisplayItemProfits(num5, val2.groupCredits);
				BankNet.Publish();
				string text2 = (string.IsNullOrEmpty(who) ? "Sold" : (who + " sold"));
				ChatUtil.Send($"{text2} {list.Count} banked item(s) (${num4}) for ${num5}. " + $"Bank: {BankStore.Items.Count} item(s), ${BankStore.Total}.", broadcast: true);
				Plugin.Logger.LogInfo((object)string.Format("[Bank] {0} sold {1} item(s) raw ${2} profit ${3} ({4})", who ?? "host", list.Count, num4, num5, arg));
			}
			catch (Exception arg2)
			{
				Plugin.Logger.LogError((object)$"[BankService.SellFromBank] {arg2}");
			}
		}

		internal static void Status()
		{
			if (BankGate.IsLocked(out var reason))
			{
				ChatUtil.Send(reason);
			}
			if (BankStore.Items.Count == 0)
			{
				ChatUtil.Send("The bank is empty. /bank deposit <amount|all> stores scrap.");
			}
			else
			{
				ChatUtil.Send(string.Format("{0} item(s), ${1}. Auto deposit {2}. /bank list, or type bank in the terminal.", BankStore.Items.Count, BankStore.Total, ModConfig.AutoDeposit.Value ? "ON" : "OFF"));
			}
		}

		internal static void Info()
		{
			ChatUtil.Send("This lobby's host runs SimpleHQ: scrap can be stored in a bank to cut ship lag. Anyone can type /bank to see the total.", broadcast: true);
			ChatUtil.Send("The host and whitelisted players can store scrap with /bank deposit <amount|all> (in orbit or at the Company), take it back with /bank withdraw <item> (in orbit or once landed), and sell it with /sell bank <amount> or /bank sell <amount>. With SimpleHQ installed, type bank in the terminal.", broadcast: true);
		}

		internal static void List()
		{
			if (BankStore.Items.Count == 0)
			{
				ChatUtil.Send("The bank is empty.");
				return;
			}
			string message = string.Join(", ", from e in BankStore.Items
				group e by e.Name into g
				orderby g.Sum((BankEntry e) => e.Value) descending
				select $"{g.Key} x{g.Count()} ${g.Sum((BankEntry e) => e.Value)}");
			ChatUtil.SendChunked(message);
		}

		private static bool Ready(out string why)
		{
			why = null;
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsHost)
			{
				why = "Only the host can do that.";
				return false;
			}
			return !BankGate.IsLocked(out why);
		}

		internal static void OnPropsDespawning(bool despawnAllItems)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsHost && (despawnAllItems || ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.allPlayersDead)) && !TournamentInfo.Active && BankStore.Items.Count != 0)
				{
					int total = BankStore.Total;
					int count = BankStore.Items.Count;
					BankStore.Clear();
					BankNet.Publish();
					ChatUtil.Send($"The crew was wiped out. The bank lost {count} item(s), ${total}.", broadcast: true);
					Plugin.Logger.LogInfo((object)$"[Bank] wiped out: lost {count} item(s) ${total}");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[BankService.OnPropsDespawning] {arg}");
			}
		}

		internal static void OnFired()
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsHost)
				{
					int count = BankStore.Items.Count;
					BankStore.Clear();
					BankStore.Commit();
					BankNet.Publish();
					if (count > 0)
					{
						Plugin.Logger.LogInfo((object)$"[Bank] fired: bank of {count} item(s) cleared");
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[BankService.OnFired] {arg}");
			}
		}
	}
	internal static class CruiserService
	{
		private static readonly HashSet<ulong> _kitCruisers = new HashSet<ulong>();

		private static int _gen;

		private static readonly List<NetworkObject> _kitExtras = new List<NetworkObject>();

		internal static bool Busy { get; private set; }

		internal static bool IsHost
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsHost;
				}
				return false;
			}
		}

		internal static void NoteKitExtra(NetworkObject no)
		{
			if ((Object)(object)no != (Object)null)
			{
				_kitExtras.Add(no);
			}
		}

		internal static void NoteKitCruiser(NetworkObject no)
		{
			if ((Object)(object)no != (Object)null)
			{
				_kitCruisers.Add(no.NetworkObjectId);
			}
		}

		internal static List<VehicleController> All()
		{
			return (from v in Object.FindObjectsByType<VehicleController>((FindObjectsInactive)1, (FindObjectsSortMode)0)
				where (Object)(object)v != (Object)null
				select v).ToList();
		}

		internal static int CountLive()
		{
			return All().Count((VehicleController v) => (Object)(object)((NetworkBehaviour)v).NetworkObject != (Object)null && ((NetworkBehaviour)v).NetworkObject.IsSpawned);
		}

		internal static void Remove(string why, bool kitOnly, bool returnItems)
		{
			if (IsHost)
			{
				int gen = ++_gen;
				Busy = true;
				((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(RemoveRoutine(gen, why, kitOnly, returnItems));
			}
		}

		private static IEnumerator RemoveRoutine(int gen, string why, bool kitOnly, bool returnItems)
		{
			try
			{
				float until = Time.realtimeSinceStartup + 10f;
				bool told = false;
				while (Time.realtimeSinceStartup < until)
				{
					List<PlayerControllerB> list = Targets(kitOnly).SelectMany(Riders).Distinct().ToList();
					if (list.Count == 0)
					{
						break;
					}
					if (!told)
					{
						told = true;
						ChatUtil.Send("The cruiser is being removed (" + why + "): " + string.Join(", ", list.Select((PlayerControllerB r) => r.playerUsername)) + ", get out of it and into the ship.", broadcast: true);
					}
					yield return (object)new WaitForSecondsRealtime(0.5f);
					if (gen != _gen)
					{
						yield break;
					}
				}
				if (gen == _gen)
				{
					RemoveNow(why, kitOnly, returnItems);
				}
			}
			finally
			{
				if (gen == _gen)
				{
					Busy = false;
				}
			}
		}

		private static IEnumerable<VehicleController> Targets(bool kitOnly)
		{
			return from v in All()
				where !kitOnly || ((Object)(object)((NetworkBehaviour)v).NetworkObject != (Object)null && _kitCruisers.Contains(((NetworkBehaviour)v).NetworkObject.NetworkObjectId))
				select v;
		}

		private static IEnumerable<PlayerControllerB> Riders(VehicleController v)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (instance?.allPlayerScripts == null)
			{
				yield break;
			}
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (!((Object)(object)val == (Object)null) && val.isPlayerControlled && !val.isPlayerDead)
				{
					Transform val2 = (((Object)(object)val.overridePhysicsParent != (Object)null) ? val.overridePhysicsParent : val.physicsParent);
					if ((Object)(object)val == (Object)(object)v.currentDriver || (Object)(object)val == (Object)(object)v.currentPassenger || ((Object)(object)val2 != (Object)null && val2.IsChildOf(((Component)v).transform)))
					{
						yield return val;
					}
				}
			}
		}

		internal static int RemoveNow(string why, bool kitOnly, bool returnItems)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			StartOfRound instance = StartOfRound.Instance;
			try
			{
				foreach (VehicleController item in Targets(kitOnly).ToList())
				{
					NetworkObject networkObject = ((NetworkBehaviour)item).NetworkObject;
					if (returnItems)
					{
						num3 += ReturnBedItems(item);
					}
					if ((Object)(object)networkObject != (Object)null && networkObject.IsSpawned)
					{
						_kitCruisers.Remove(networkObject.NetworkObjectId);
						networkObject.Despawn(true);
						num++;
					}
					else
					{
						Object.Destroy((Object)(object)((Component)item).gameObject);
						num2++;
					}
					DestroyBodies(item);
					if ((Object)(object)instance != (Object)null && (Object)(object)instance.attachedVehicle == (Object)(object)item)
					{
						instance.attachedVehicle = null;
					}
				}
				foreach (NetworkObject item2 in _kitExtras.ToList())
				{
					if ((Object)(object)item2 == (Object)null || !item2.IsSpawned)
					{
						_kitExtras.Remove(item2);
						continue;
					}
					GrabbableObject componentInChildren = ((Component)item2).GetComponentInChildren<GrabbableObject>();
					if (!((Object)(object)componentInChildren != (Object)null) || (!componentInChildren.isHeld && !componentInChildren.heldByPlayerOnServer && !componentInChildren.isInShipRoom))
					{
						item2.Despawn(true);
						_kitExtras.Remove(item2);
					}
				}
				if (num + num2 > 0 && (Object)(object)instance != (Object)null)
				{
					instance.attachedVehicle = null;
					instance.isObjectAttachedToMagnet = false;
					if (!kitOnly || CountLive() == 0)
					{
						((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(MagnetOffSoon(instance));
					}
					ClearSavedVehicle();
					Plugin.Logger.LogInfo((object)($"[Cruiser] removed {num} vehicle(s)" + ((num2 > 0) ? $" and {num2} leftover copy(ies)" : "") + ((num3 > 0) ? $", {num3} item(s) from the bed put on the ship" : "") + " (" + why + ")."));
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[CruiserService.RemoveNow] {arg}");
			}
			return num + num2;
		}

		private static int ReturnBedItems(VehicleController v)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return 0;
			}
			List<GrabbableObject> list = (from o in Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0)
				where (Object)(object)o != (Object)null && (Object)(object)((NetworkBehaviour)o).NetworkObject != (Object)null && ((NetworkBehaviour)o).NetworkObject.IsSpawned && !o.isHeld && !o.isHeldByEnemy && !o.heldByPlayerOnServer && ((Component)o).transform.IsChildOf(((Component)v).transform)
				select o).ToList();
			if (list.Count == 0)
			{
				return 0;
			}
			Vector3 val;
			if (!((Object)(object)instance.shipInnerRoomBounds != (Object)null))
			{
				val = instance.elevatorTransform.position;
			}
			else
			{
				Bounds bounds = instance.shipInnerRoomBounds.bounds;
				val = ((Bounds)(ref bounds)).center;
			}
			Vector3 val2 = val;
			List<ItemPlaceNet.Placement> list2 = new List<ItemPlaceNet.Placement>();
			int num = 0;
			foreach (GrabbableObject item in list)
			{
				float num2 = (float)num++ * 2.39996f;
				float num3 = 0.3f * Mathf.Sqrt((float)num);
				Vector3 worldPos = ItemSpawner.SnapToFloor(val2 + new Vector3(Mathf.Cos(num2) * num3, 0f, Mathf.Sin(num2) * num3));
				ItemSpawner.PlaceOnShipSynced(item, worldPos);
				list2.Add(new ItemPlaceNet.Placement(((NetworkBehaviour)item).NetworkObjectId, item.targetFloorPosition, item.floorYRot));
			}
			ItemPlaceNet.Broadcast(list2);
			return list.Count;
		}

		internal static void DestroyBodies(VehicleController v)
		{
			if ((Object)(object)v == (Object)null)
			{
				return;
			}
			Rigidbody[] array = (Rigidbody[])(object)new Rigidbody[3] { v.ragdollPhysicsBody, v.windwiperPhysicsBody1, v.windwiperPhysicsBody2 };
			foreach (Rigidbody val in array)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).transform.parent != (Object)(object)((Component)v).transform && !((Component)val).transform.IsChildOf(((Component)v).transform))
				{
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
			}
		}

		private static IEnumerator MagnetOffSoon(StartOfRound sor)
		{
			yield return (object)new WaitForSecondsRealtime(0.5f);
			if ((Object)(object)sor != (Object)null && CountLive() == 0)
			{
				MagnetOffEverywhere(sor);
			}
		}

		private static void MagnetOffEverywhere(StartOfRound sor)
		{
			sor.attachedVehicle = null;
			sor.isObjectAttachedToMagnet = false;
			if ((Object)(object)sor.magnetLever != (Object)null)
			{
				sor.magnetLever.initialBoolState = false;
				sor.magnetLever.setInitialState = true;
				sor.magnetLever.SetInitialState();
				sor.magnetLever.UpdateAnimClientRpc(false, false, -1);
			}
			sor.magnetOn = false;
			sor.SetMagnetOnClientRpc(false);
		}

		private static void ClearSavedVehicle()
		{
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				StartOfRound instance2 = StartOfRound.Instance;
				if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance2 == (Object)null) && !instance2.isChallengeFile && !string.IsNullOrEmpty(instance.currentSaveFileName) && ES3.KeyExists("AttachedVehicleID", instance.currentSaveFileName) && ES3.Load<int>("AttachedVehicleID", instance.currentSaveFileName, -1) != -1)
				{
					ES3.Save<int>("AttachedVehicleID", -1, instance.currentSaveFileName);
					Plugin.Logger.LogInfo((object)"[Cruiser] save no longer has an attached vehicle.");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[CruiserService.ClearSavedVehicle] {arg}");
			}
		}

		internal static void OnTournamentEnd()
		{
			if (IsHost && _kitCruisers.Count != 0)
			{
				((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(WhenInOrbit(++_gen));
			}
		}

		private static IEnumerator WhenInOrbit(int gen)
		{
			StartOfRound sor = StartOfRound.Instance;
			while ((Object)(object)sor != (Object)null && (!sor.inShipPhase || sor.travellingToNewLevel))
			{
				yield return (object)new WaitForSecondsRealtime(1f);
				if (gen != _gen || TournamentInfo.Active)
				{
					yield break;
				}
			}
			if (gen == _gen && !TournamentInfo.Active)
			{
				Remove("the tournament ended", kitOnly: true, returnItems: true);
			}
		}

		internal static void ResetSession()
		{
			_kitCruisers.Clear();
			_kitExtras.Clear();
			_gen++;
			Busy = false;
		}
	}
	[HarmonyPatch(typeof(VehicleController), "OnDisable")]
	internal static class VehicleBodiesPatch
	{
		[HarmonyPostfix]
		private static void Postfix(VehicleController __instance)
		{
			try
			{
				if ((Object)(object)__instance != (Object)null && ((Object)(object)((NetworkBehaviour)__instance).NetworkObject == (Object)null || !((NetworkBehaviour)__instance).NetworkObject.IsSpawned))
				{
					CruiserService.DestroyBodies(__instance);
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[VehicleBodiesPatch] {arg}");
			}
		}
	}
	internal static class DecorService
	{
		internal sealed class Hidden
		{
			internal readonly List<(int i, bool unlocked, bool moved, bool stored)> Flags = new List<(int, bool, bool, bool)>();

			internal readonly List<int> Lucky = new List<int>();
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnMessage;
		}

		internal const string Msg = "SimpleHQ.Decor";

		private static readonly List<int> _added = new List<int>();

		private static readonly Dictionary<int, HashSet<int>> _builtIn = new Dictionary<int, HashSet<int>>();

		private static int _gen;

		private static bool IsHost
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsHost;
				}
				return false;
			}
		}

		internal static bool Granted => _added.Count > 0;

		internal static IReadOnlyList<int> Added => _added;

		internal static void Register()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (((singleton != null) ? singleton.CustomMessagingManager : null) != null && !singleton.IsHost)
				{
					CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
					object obj = <>O.<0>__OnMessage;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = OnMessage;
						<>O.<0>__OnMessage = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("SimpleHQ.Decor", (HandleNamedMessageDelegate)obj);
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorService.Register] {arg}");
			}
		}

		internal static void ResetSession()
		{
			_added.Clear();
			_builtIn.Clear();
			_gen++;
		}

		internal static void Apply(Kit kit)
		{
			if (!IsHost)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if (instance?.unlockablesList?.unlockables == null)
			{
				return;
			}
			try
			{
				HashSet<int> want = Wanted(kit);
				_gen++;
				List<int> list = _added.Where((int i) => !want.Contains(i)).ToList();
				Grant(instance, want);
				if (list.Count > 0)
				{
					((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(RevertInOrbit(++_gen, list, "the new kit doesn't include them"));
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorService.Apply] {arg}");
			}
		}

		internal static void Revert(string why)
		{
			if (IsHost && Granted)
			{
				((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(RevertInOrbit(++_gen, _added.ToList(), why));
			}
		}

		private static HashSet<int> Wanted(Kit kit)
		{
			HashSet<int> hashSet = new HashSet<int>();
			if (kit == null || !kit.HasDecor)
			{
				return hashSet;
			}
			if (kit.decorAll)
			{
				foreach (KeyValuePair<int, UnlockableItem> item in DecorCatalog.All())
				{
					hashSet.Add(item.Key);
				}
				return hashSet;
			}
			string[] decor = kit.decor;
			foreach (string text in decor)
			{
				int num = DecorCatalog.IndexOf(text);
				if (num >= 0)
				{
					hashSet.Add(num);
				}
				else
				{
					Plugin.Logger.LogWarning((object)("[DecorService] the kit's decoration \"" + text + "\" isn't in this game; skipped."));
				}
			}
			return hashSet;
		}

		private static bool Owned(StartOfRound sor, UnlockableItem u, int i, HashSet<int> inScene)
		{
			if (!u.alreadyUnlocked && !u.hasBeenUnlockedByPlayer && !u.inStorage && !sor.SpawnedShipUnlockables.ContainsKey(i))
			{
				return inScene.Contains(i);
			}
			return true;
		}

		private static void Grant(StartOfRound sor, HashSet<int> want)
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			List<UnlockableItem> unlockables = sor.unlockablesList.unlockables;
			HashSet<int> inScene = new HashSet<int>(from p in Object.FindObjectsOfType<PlaceableShipObject>()
				where (Object)(object)p != (Object)null
				select p.unlockableID);
			List<string> list = new List<string>();
			int num = 0;
			foreach (int item in want.OrderBy((int x) => x))
			{
				if (_added.Contains(item) || item < 0 || item >= unlockables.Count)
				{
					continue;
				}
				UnlockableItem val = unlockables[item];
				if (Owned(sor, val, item, inScene))
				{
					num++;
					continue;
				}
				try
				{
					val.placedPosition = Vector3.zero;
					val.placedRotation = Vector3.zero;
					val.hasBeenMoved = false;
					val.inStorage = false;
					val.hasBeenUnlockedByPlayer = true;
					sor.SpawnUnlockable(item, false);
					if (sor.SpawnedShipUnlockables.TryGetValue(item, out var value) && (Object)(object)value != (Object)null)
					{
						_added.Add(item);
						_builtIn[item] = new HashSet<int>(from g in value.GetComponentsInChildren<GrabbableObject>(true)
							select ((Object)g).GetInstanceID());
						list.Add(val.unlockableName);
					}
					else
					{
						val.hasBeenUnlockedByPlayer = false;
						Plugin.Logger.LogWarning((object)("[DecorService] " + val.unlockableName + " didn't spawn; left out."));
					}
				}
				catch (Exception arg)
				{
					val.hasBeenUnlockedByPlayer = false;
					Plugin.Logger.LogError((object)$"[DecorService] spawning {val.unlockableName}: {arg}");
				}
			}
			if (list.Count > 0 || num > 0)
			{
				Plugin.Logger.LogInfo((object)(string.Format("[DecorService] added {0} decoration(s) for the run: {1}", list.Count, string.Join(", ", list)) + ((num > 0) ? $" ({num} already the crew's, left as they are)" : "")));
			}
			if (list.Count > 0)
			{
				ChatUtil.Send((list.Count == 1) ? (list[0] + " is on the ship for this tournament (it goes back when it ends).") : $"{list.Count} decorations are on the ship for this tournament (they go back when it ends).", broadcast: true);
			}
		}

		private static IEnumerator RevertInOrbit(int gen, List<int> ids, string why)
		{
			StartOfRound sor = StartOfRound.Instance;
			bool told = false;
			bool warned = false;
			while (true)
			{
				if ((Object)(object)sor != (Object)null && (!sor.inShipPhase || sor.travellingToNewLevel))
				{
					yield return (object)new WaitForSecondsRealtime(1f);
					if (gen != _gen)
					{
						break;
					}
					continue;
				}
				if (gen != _gen || (Object)(object)sor == (Object)null)
				{
					break;
				}
				List<int> pending = ids.Where(_added.Contains).ToList();
				if (pending.Count == 0)
				{
					break;
				}
				if (!told)
				{
					Send(0, pending);
					CancelBuild(pending);
					told = true;
					yield return (object)new WaitForSecondsRealtime(0.3f);
					if (gen != _gen)
					{
						break;
					}
				}
				List<int> list = new List<int>();
				List<int> list2 = new List<int>();
				List<string> list3 = new List<string>();
				foreach (int item in pending)
				{
					try
					{
						bool wasStored;
						string text = RemoveOne(sor, item, out wasStored);
						if (text != null)
						{
							list3.Add(text);
							continue;
						}
						list.Add(item);
						if (wasStored)
						{
							list2.Add(item);
						}
					}
					catch (Exception arg)
					{
						Plugin.Logger.LogError((object)$"[DecorService.Revert] #{item}: {arg}");
						_added.Remove(item);
					}
				}
				if (list.Count > 0)
				{
					Send(1, list);
					foreach (int item2 in list2)
					{
						try
						{
							sor.ReturnUnlockableFromStorageClientRpc(item2);
						}
						catch (Exception ex)
						{
							Plugin.Logger.LogWarning((object)$"[DecorService] storage clear #{item2}: {ex.Message}");
						}
					}
					Plugin.Logger.LogInfo((object)($"[DecorService] took back {list.Count} decoration(s) ({why}): " + string.Join(", ", list.Select((int i) => sor.unlockablesList.unlockables[i].unlockableName))));
					ChatUtil.Send($"The tournament's decorations are off the ship ({list.Count}).", broadcast: true);
				}
				if (list3.Count == 0)
				{
					break;
				}
				if (!warned)
				{
					warned = true;
					Plugin.Logger.LogInfo((object)("[DecorService] waiting: " + string.Join("; ", list3)));
					ChatUtil.Send("Take the items off " + string.Join(", ", list3.Take(3)) + " so the tournament's decorations can go back.", broadcast: true);
				}
				yield return (object)new WaitForSecondsRealtime(5f);
				if (gen != _gen)
				{
					break;
				}
			}
		}

		private static string RemoveOne(StartOfRound sor, int i, out bool wasStored)
		{
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			UnlockableItem val = sor.unlockablesList.unlockables[i];
			wasStored = val.inStorage;
			GameObject value;
			GameObject val2 = (sor.SpawnedShipUnlockables.TryGetValue(i, out value) ? value : null);
			if ((Object)(object)val2 == (Object)null)
			{
				PlaceableShipObject? obj = ((IEnumerable<PlaceableShipObject>)Object.FindObjectsOfType<PlaceableShipObject>()).FirstOrDefault((Func<PlaceableShipObject, bool>)((PlaceableShipObject p) => (Object)(object)p != (Object)null && p.unlockableID == i));
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					AutoParentToShip parentObject = obj.parentObject;
					obj2 = ((parentObject != null) ? ((Component)parentObject).gameObject : null);
				}
				val2 = (GameObject)obj2;
			}
			if ((Object)(object)val2 != (Object)null)
			{
				HashSet<int> value2;
				HashSet<int> own = (_builtIn.TryGetValue(i, out value2) ? value2 : new HashSet<int>());
				if (val2.GetComponentsInChildren<GrabbableObject>().Any((GrabbableObject x) => (Object)(object)x != (Object)null && !own.Contains(((Object)x).GetInstanceID())))
				{
					return val.unlockableName + " (scrap on it)";
				}
				PlayerControllerB[] allPlayerScripts = sor.allPlayerScripts;
				foreach (PlayerControllerB val3 in allPlayerScripts)
				{
					if ((Object)(object)val3 != (Object)null && val3.isPlayerControlled && (Object)(object)val3.currentTriggerInAnimationWith != (Object)null && ((Component)val3.currentTriggerInAnimationWith).transform.IsChildOf(val2.transform))
					{
						return val.unlockableName + " (" + val3.playerUsername + " is using it)";
					}
				}
			}
			sor.SpawnedShipUnlockables.Remove(i);
			NetworkObject val4 = (((Object)(object)val2 != (Object)null) ? (val2.GetComponent<NetworkObject>() ?? val2.GetComponentInParent<NetworkObject>()) : null);
			if ((Object)(object)val4 != (Object)null && val4.IsSpawned)
			{
				val4.Despawn(true);
			}
			val.hasBeenUnlockedByPlayer = false;
			val.inStorage = false;
			val.hasBeenMoved = false;
			val.placedPosition = Vector3.zero;
			val.placedRotation = Vector3.zero;
			TimeOfDay.Instance?.furniturePlacedAtQuotaStart?.RemoveAll((int x) => x == i);
			_added.Remove(i);
			_builtIn.Remove(i);
			return null;
		}

		private static void CancelBuild(List<int> ids)
		{
			try
			{
				ShipBuildModeManager instance = ShipBuildModeManager.Instance;
				if ((Object)(object)instance != (Object)null && instance.InBuildMode && (Object)(object)instance.placingObject != (Object)null && ids.Contains(instance.placingObject.unlockableID))
				{
					instance.CancelBuildMode(true);
					Plugin.Logger.LogInfo((object)"[DecorService] build mode cancelled: that decoration is going back.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("[DecorService] cancel build: " + ex.Message));
			}
		}

		internal static void OnShipFurnitureReset()
		{
			if (_added.Count != 0)
			{
				Plugin.Logger.LogInfo((object)$"[DecorService] the ship's furniture was reset by the game; {_added.Count} tournament decoration(s) already gone.");
				_added.Clear();
				_builtIn.Clear();
				_gen++;
			}
		}

		internal unsafe static void Send(byte phase, List<int> ids)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (((singleton != null) ? singleton.CustomMessagingManager : null) == null || !singleton.IsHost || ids.Count == 0 || singleton.ConnectedClientsIds.Count <= 1)
				{
					return;
				}
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(8 + ids.Count * 4, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref phase, default(ForPrimitives));
					int count = ids.Count;
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives));
					foreach (int id in ids)
					{
						int current = id;
						((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref current, default(ForPrimitives));
					}
					singleton.CustomMessagingManager.SendNamedMessageToAll("SimpleHQ.Decor", val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorService.Send] {arg}");
			}
		}

		private static void OnMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				List<int> list = new List<int>();
				int item = default(int);
				for (int i = 0; i < num; i++)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref item, default(ForPrimitives));
					list.Add(item);
				}
				if (b == 0)
				{
					CancelBuild(list);
					return;
				}
				List<UnlockableItem> list2 = StartOfRound.Instance?.unlockablesList?.unlockables;
				if (list2 == null)
				{
					return;
				}
				foreach (int item2 in list)
				{
					if (item2 >= 0 && item2 < list2.Count && list2[item2] != null)
					{
						list2[item2].hasBeenUnlockedByPlayer = false;
						if (list2[item2].unlockableType == 1)
						{
							list2[item2].inStorage = false;
							list2[item2].hasBeenMoved = false;
							list2[item2].placedPosition = Vector3.zero;
							list2[item2].placedRotation = Vector3.zero;
						}
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorService.OnMessage] {arg}");
			}
		}

		internal static Hidden HideForSave()
		{
			if (!Granted)
			{
				return null;
			}
			List<UnlockableItem> list = StartOfRound.Instance?.unlockablesList?.unlockables;
			if (list == null)
			{
				return null;
			}
			Hidden hidden = new Hidden();
			foreach (int item in _added)
			{
				if (item >= 0 && item < list.Count)
				{
					UnlockableItem val = list[item];
					hidden.Flags.Add((item, val.hasBeenUnlockedByPlayer, val.hasBeenMoved, val.inStorage));
					val.hasBeenUnlockedByPlayer = false;
					val.hasBeenMoved = false;
					val.inStorage = false;
				}
			}
			List<int> list2 = TimeOfDay.Instance?.furniturePlacedAtQuotaStart;
			if (list2 != null)
			{
				hidden.Lucky.AddRange(list2.Where((int x) => _added.Contains(x)));
				list2.RemoveAll((int x) => _added.Contains(x));
			}
			return hidden;
		}

		internal static void RestoreAfterSave(Hidden h)
		{
			if (h == null)
			{
				return;
			}
			List<UnlockableItem> list = StartOfRound.Instance?.unlockablesList?.unlockables;
			if (list == null)
			{
				return;
			}
			foreach (var flag in h.Flags)
			{
				if (_added.Contains(flag.i))
				{
					list[flag.i].hasBeenUnlockedByPlayer = flag.unlocked;
					list[flag.i].hasBeenMoved = flag.moved;
					list[flag.i].inStorage = flag.stored;
				}
			}
			(TimeOfDay.Instance?.furniturePlacedAtQuotaStart)?.AddRange(h.Lucky.Where((int x) => _added.Contains(x)));
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
	internal static class DecorSaveGuardPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static void Prefix(out DecorService.Hidden __state)
		{
			__state = null;
			try
			{
				__state = DecorService.HideForSave();
				if (__state != null && __state.Flags.Count > 0)
				{
					Plugin.Logger.LogInfo((object)$"[DecorService] save: {__state.Flags.Count} tournament decoration(s) kept out of the file.");
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorSaveGuardPatch] {arg}");
			}
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception, DecorService.Hidden __state)
		{
			try
			{
				DecorService.RestoreAfterSave(__state);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorSaveGuardPatch.Finalizer] {arg}");
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ResetShipFurniture")]
	internal static class DecorFurnitureResetPatch
	{
		[HarmonyPostfix]
		private static void Postfix(StartOfRound __instance)
		{
			try
			{
				if (((NetworkBehaviour)__instance).IsServer)
				{
					DecorService.OnShipFurnitureReset();
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[DecorFurnitureResetPatch] {arg}");
			}
		}
	}
	internal static class SuitService
	{
		private static readonly List<int> _added = new List<int>();

		private static readonly List<int> _luckAdded = new List<int>();

		private static readonly Dictionary<ulong, int> _before = new Dictionary<ulong, int>();

		private static int _gen;

		private static bool IsHost
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsHost;
				}
				return false;
			}
		}

		internal static bool Granted => _added.Count > 0;

		internal static IReadOnlyList<int> Added => _added;

		internal static void Apply(bool want)
		{
			if (IsHost)
			{
				if (want)
				{
					Grant();
				}
				else if (Granted)
				{
					Revert("the new kit doesn't include them");
				}
			}
		}

		private static void Grant()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (instance?.unlockablesList?.unlockables == null)
			{
				return;
			}
			_gen++;
			if (Granted)
			{
				return;
			}
			try
			{
				_before.Clear();
				PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
				foreach (PlayerControllerB val in allPlayerScripts)
				{
					if ((Object)(object)val != (Object)null)
					{
						_before[val.playerClientId] = val.currentSuitID;
					}
				}
				List<int> lucky = ((TimeOfDay.Instance?.furniturePlacedAtQuotaStart != null) ? new List<int>(TimeOfDay.Instance.furniturePlacedAtQuotaStart) : null);
				HashSet<int> hashSet = new HashSet<int>(from s in Object.FindObjectsOfType<UnlockableSuit>()
					select s.syncedSuitID.Value);
				List<UnlockableItem> list = instance.unlockablesList.unlockables;
				for (int num = 0; num < list.Count; num++)
				{
					UnlockableItem val2 = list[num];
					if (val2 != null && val2.unlockableType == 0 && !val2.alreadyUnlocked && !val2.hasBeenUnlockedByPlayer && !instance.SpawnedShipUnlockables.ContainsKey(num) && !hashSet.Contains(num) && !((Object)(object)val2.suitMaterial == (Object)null))
					{
						instance.UnlockShipObject(num);
						if (instance.SpawnedShipUnlockables.ContainsKey(num))
						{
							_added.Add(num);
						}
						else
						{
							val2.hasBeenUnlockedByPlayer = false;
						}
					}
				}
				_luckAdded.Clear();
				if (lucky != null)
				{
					_luckAdded.AddRange(TimeOfDay.Instance.furniturePlacedAtQuotaStart.Where((int x) => !lucky.Contains(x)));
				}
				Plugin.Logger.LogInfo((object)($"[SuitService] added {_added.Count} suit(s) for the run: " + string.Join(", ", _added.Select((int index) => list[index].unlockableName))));
				if (_added.Count > 0)
				{
					ChatUtil.Send($"Every suit is on the rack for this tournament ({_added.Count} added; they go back when it ends).", broadcast: true);
				}
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"[SuitService.Grant] {arg}");
			}
		}

		internal static void Revert(string why)
		{
			if (IsHost && Granted)
			{
				((MonoBehaviour)CoroutineRunner.Instance).StartCoroutine(RevertInOrbit