Decompiled source of QualityCompany v1.5.0

QualityCompany.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
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.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using QualityCompany.Assets;
using QualityCompany.Events;
using QualityCompany.Manager;
using QualityCompany.Manager.Saves;
using QualityCompany.Manager.ShipTerminal;
using QualityCompany.Modules.Core;
using QualityCompany.Modules.HUD;
using QualityCompany.Modules.Ship;
using QualityCompany.NetcodePatcher;
using QualityCompany.Network;
using QualityCompany.Service;
using QualityCompany.Utils;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("QualityCompany")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
[assembly: AssemblyProduct("QualityCompany")]
[assembly: AssemblyTitle("QualityCompany")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 QualityCompany
{
	[BepInPlugin("umno.QualityCompany", "QualityCompany", "1.5.0")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("umno.QualityCompany");

		internal static Plugin Instance;

		internal ManualLogSource Log;

		internal PluginConfig PluginConfig;

		internal string PluginPath;

		private void Awake()
		{
			Instance = this;
			Log = Logger.CreateLogSource("QualityCompany");
			PluginPath = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			PluginConfig = new PluginConfig();
			PluginConfig.Bind(((BaseUnityPlugin)this).Config);
			NetcodePatcher();
			Patch();
			LoadAssets();
			ModNetworkManager.Init();
			Log.LogMessage((object)"Plugin QualityCompany v1.5.0 is loaded!");
		}

		private void Patch()
		{
			AdvancedTerminalRegistry.Register(Assembly.GetExecutingAssembly(), createPrimaryCommand: true, addToHelp: true, null, null, "QualityCompany provides auto-sell functionality with a few commands.");
			ModuleRegistry.Register(Assembly.GetExecutingAssembly());
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
		}

		private static void NetcodePatcher()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void LoadAssets()
		{
			AssetManager.LoadModBundle(PluginPath);
		}
	}
	[Serializable]
	internal class PluginConfig
	{
		[JsonIgnore]
		public bool ShowDebugLogs { get; set; }

		[JsonIgnore]
		public bool ExperimentalFeaturesEnabled { get; set; }

		[JsonIgnore]
		public bool InventoryShowScrapUI { get; set; }

		[JsonIgnore]
		public bool InventoryShowTotalScrapUI { get; set; }

		[JsonIgnore]
		public bool InventoryScrapForceRefresh { get; set; }

		[JsonIgnore]
		public bool InventoryShowShotgunAmmoCounterUI { get; set; }

		[JsonIgnore]
		public bool InventoryForceUpdateAllSlotsOnDiscard { get; set; }

		[JsonIgnore]
		public float InventoryStartupDelay { get; set; }

		[JsonIgnore]
		public bool HudLatencyEnabled { get; set; }

		[JsonIgnore]
		public float HudLatencyUpdateInterval { get; set; }

		[JsonIgnore]
		public string HudLatencyAnchor { get; set; }

		[JsonIgnore]
		public float HudLatencyHorizontalPadding { get; set; }

		[JsonIgnore]
		public float HudLatencyVerticalPadding { get; set; }

		[JsonIgnore]
		public bool MonitorLootCreditsEnabled { get; set; }

		[JsonIgnore]
		public bool MonitorInfoEnabled { get; set; }

		[JsonIgnore]
		public bool MonitorTimeEnabled { get; set; }

		[JsonIgnore]
		public bool NetworkingEnabled { get; set; }

		public string SellIgnoreList { get; set; }

		public bool TerminalMiscCommandsEnabled { get; set; }

		public bool TerminalSellCommandsEnabled { get; set; }

		public bool TerminalTargetCommandsEnabled { get; set; }

		public bool TerminalDebugCommandsEnabled { get; set; }

		public bool TerminalPatchFixScanEnabled { get; set; }

		public bool TerminalPatchFixScanItemsListEnabled { get; set; }

		public void Bind(ConfigFile configFile)
		{
			ShowDebugLogs = configFile.Bind<bool>("Debug", "ShowDebugLogs", false, "[CLIENT] Turn on/off debug logs.").Value;
			ExperimentalFeaturesEnabled = configFile.Bind<bool>("Debug", "ExperimentalFeaturesEnabled", false, "[CLIENT] Turn on/off experimental features.").Value;
			InventoryShowScrapUI = configFile.Bind<bool>("HUD", "ShowScrapUI", true, "[CLIENT] Turn on/off scrap value on the item slots UI.").Value;
			InventoryShowTotalScrapUI = configFile.Bind<bool>("HUD", "ShowTotalScrapUI", true, "[CLIENT] Turn on/off total held items scrap value UI.").Value;
			InventoryScrapForceRefresh = configFile.Bind<bool>("HUD", "ScrapForceRefresh", false, "[CLIENT] Turn on/off force refreshing the Scrap UI every second.").Value;
			InventoryShowShotgunAmmoCounterUI = configFile.Bind<bool>("HUD", "ShowShotgunAmmoCounterUI", true, "[CLIENT] Turn on/off shotgun ammo counter on the item slots UI.").Value;
			InventoryForceUpdateAllSlotsOnDiscard = configFile.Bind<bool>("HUD", "ForceUpdateAllSlotsOnDiscard", false, "[CLIENT] Turn on/off force updating all item slots scrap & shotgun ui on discarding of a held item.").Value;
			InventoryStartupDelay = configFile.Bind<float>("HUD", "StartupDelay", 4.5f, "[CLIENT] Delay before creating inventory UI components for scrap value & shotgun ammo. Minimum value will be set to 3 seconds.\nNOTE: Useful if you have mod compatibility issues with mods that affect the players' inventory slots such as HotBarPlus, GeneralImprovements, ReservedItemSlot (Flashlight, Weapon, etc)").Value;
			HudLatencyEnabled = configFile.Bind<bool>("HUD", "Show latency to host", true, "[CLIENT] Whether to show the latency HUD or not. Disabled for the host by default. Requires networking.").Value;
			HudLatencyUpdateInterval = configFile.Bind<float>("HUD", "Latency Update Interval", 5f, "[CLIENT] How often to do latency update checks. Will be set to a minimum of 2 seconds.").Value;
			HudLatencyAnchor = configFile.Bind<string>("HUD", "Latency Anchor Position", "BottomLeft", "[CLIENT] Anchor position to place the latency display.\nPossible values: TopLeft, TopRight, BottomLeft, BottomRight").Value;
			HudLatencyHorizontalPadding = configFile.Bind<int>("HUD", "Latency Horizontal Padding", 5, "[CLIENT] Horizontal padding for the latency hud display away from the horizontal (left/right) edge of the screen.").Value;
			HudLatencyVerticalPadding = configFile.Bind<int>("HUD", "Latency Vertical Padding", 5, "[CLIENT] Vertical padding for the latency hud display away from the vertical (top/bottom) edge of the screen.").Value;
			MonitorLootCreditsEnabled = configFile.Bind<bool>("Monitor", "LootCreditsEnabled", true, "[CLIENT] Turn on/off the ship loot & game credit balance monitor in the ship.").Value;
			MonitorInfoEnabled = configFile.Bind<bool>("Monitor", "InfoEnabled", true, "[CLIENT] Turn on/off the info monitor in the ship.").Value;
			MonitorTimeEnabled = configFile.Bind<bool>("Monitor", "TimeEnabled", true, "[CLIENT] Turn on/off the time monitor in the ship.").Value;
			NetworkingEnabled = configFile.Bind<bool>("Networking", "NetworkingEnabled", true, "[EXPERIMENTAL!!!] [CLIENT] Turn on/off networking capabilities.\nNOTE: This will MOST LIKELY cause de-sync issues with a couple of things, primarily for non-host clients.").Value;
			SellIgnoreList = configFile.Bind<string>("Terminal", "SellIgnoreList", "shotgun,gunammo,gift", "[HOST] A comma separated list of items to ignore in the ship. Does not have to be the exact name but at least a matching portion. e.g. 'trag' for 'tragedy'").Value;
			TerminalMiscCommandsEnabled = configFile.Bind<bool>("Terminal", "MiscCommandsEnabled", true, "[HOST] Turn on/off the additional misc terminal commands. This includes: launch, door, lights, tp, time").Value;
			TerminalSellCommandsEnabled = configFile.Bind<bool>("Terminal", "SellCommandsEnabled", true, "[HOST] Turn on/off the additional 'sell <command>' terminal commands. This includes: all, quota, target, 2h, <amount>, <item>.\nNOTE: The 'target' sub command will be disabled if TargetCommandsEnabled is disabled.").Value;
			TerminalTargetCommandsEnabled = configFile.Bind<bool>("Terminal", "TargetCommandsEnabled", true, "[HOST] Turn on/off the additional 'target' terminal command.").Value;
			TerminalDebugCommandsEnabled = configFile.Bind<bool>("Terminal", "DebugCommandsEnabled", true, "[HOST] Turn on/off the additional 'hack' terminal command. This allows to spawn <amount> of items at your foot.\nNOTE: This is primary for mod testing purposes, but may come in use ;)").Value;
			TerminalPatchFixScanEnabled = configFile.Bind<bool>("Terminal", "PatchFixScanEnabled", true, "[HOST] Turn on/off patch fixing the games' 'scan' command where it occasionally does not work.").Value;
			TerminalPatchFixScanItemsListEnabled = configFile.Bind<bool>("Terminal", "PatchFixScanItemsListEnabled", false, "[HOST] Turn on/off scan command showing list of scrap on the moon.").Value;
		}

		public void ApplyHostConfig(PluginConfig hostConfig)
		{
			SellIgnoreList = hostConfig.SellIgnoreList;
			TerminalMiscCommandsEnabled = hostConfig.TerminalMiscCommandsEnabled;
			TerminalSellCommandsEnabled = hostConfig.TerminalSellCommandsEnabled;
			TerminalTargetCommandsEnabled = hostConfig.TerminalTargetCommandsEnabled;
			TerminalDebugCommandsEnabled = hostConfig.TerminalDebugCommandsEnabled;
			TerminalPatchFixScanEnabled = hostConfig.TerminalPatchFixScanEnabled;
			TerminalPatchFixScanItemsListEnabled = hostConfig.TerminalPatchFixScanItemsListEnabled;
		}

		public void DebugPrintConfig(ModLogger logger)
		{
			foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
			{
				string name = property.Name;
				object value = property.GetValue(this);
				logger.LogDebug($"{name}={value}");
			}
		}
	}
	internal class PluginMetadata
	{
		public const string PLUGIN_GUID = "umno.QualityCompany";

		public const string PLUGIN_NAME = "QualityCompany";

		public const string PLUGIN_VERSION = "1.5.0";
	}
}
namespace QualityCompany.Utils
{
	public static class GameUtils
	{
		private static ModLogger Logger = new ModLogger("GameUtils");

		public static TimeOfDay? TimeOfDay { get; private set; }

		public static StartOfRound? StartOfRound { get; private set; }

		public static Terminal? Terminal { get; internal set; }

		public static GameObject? ShipGameObject { get; private set; }

		internal static void Init()
		{
			TimeOfDay = TimeOfDay.Instance;
			StartOfRound = StartOfRound.Instance;
			ShipGameObject = GameObject.Find("Environment/HangarShip");
		}

		internal static void Reset()
		{
			TimeOfDay = null;
			StartOfRound = null;
			Terminal = null;
			ShipGameObject = null;
		}

		public static bool IsCompanyBuyingAtFullRate()
		{
			if (TimeOfDay == null)
			{
				return false;
			}
			return TimeOfDay.daysUntilDeadline == 0;
		}

		public static string CurrentLevel()
		{
			if (TimeOfDay == null)
			{
				return "";
			}
			return ((Object)TimeOfDay.currentLevel).name;
		}

		public static string CurrentPlanet()
		{
			if (TimeOfDay == null)
			{
				return "";
			}
			return TimeOfDay.currentLevel?.PlanetName ?? "Unknown";
		}

		public static bool IsOnCompany()
		{
			return CurrentPlanet() == "71 Gordion";
		}

		public static bool IsLanded()
		{
			return StartOfRound.shipHasLanded;
		}

		public static bool IsOrbiting()
		{
			return StartOfRound.inShipPhase;
		}

		public static bool IsLandedOnCompany()
		{
			if (StartOfRound == null)
			{
				return false;
			}
			if (IsOnCompany())
			{
				return !IsOrbiting();
			}
			return false;
		}
	}
	public class HudUtils
	{
		public static void DisplayNotification(string message)
		{
			HUDManager.Instance.globalNotificationAnimator.SetTrigger("TriggerNotif");
			((TMP_Text)HUDManager.Instance.globalNotificationText).text = message;
			HUDManager.Instance.UIAudio.PlayOneShot(HUDManager.Instance.globalNotificationSFX);
		}
	}
	public static class ScrapUtils
	{
		private static readonly ModLogger Logger = new ModLogger("ScrapUtils");

		public static List<GrabbableObject> GetAllScrapInShip()
		{
			try
			{
				return (from scrap in GameUtils.ShipGameObject.GetComponentsInChildren<GrabbableObject>()
					where scrap.itemProperties.isScrap && scrap.scrapValue > 0
					select scrap).ToList();
			}
			catch
			{
				return new List<GrabbableObject>();
			}
		}

		public static List<GrabbableObject> GetAllIncludedScrapInShip(string includeList)
		{
			string includeList2 = includeList;
			return (from scrap in GetAllScrapInShip()
				where scrap.CanIncludeItem(includeList2)
				select scrap).ToList();
		}

		public static int GetShipTotalRawScrapValue()
		{
			return GetAllScrapInShip().ScrapValueOfCollection();
		}

		public static int GetShipTotalIncludedScrapValue(string includeList)
		{
			return GetAllIncludedScrapInShip(includeList).ActualScrapValueOfCollection();
		}

		public static int GetShipSettledTotalRawScrapValue()
		{
			return (from scrap in GetAllScrapInShip()
				where !scrap.isHeld
				select scrap).ScrapValueOfCollection();
		}

		public static int SumScrapListSellValue(IEnumerable<GrabbableObject> scraps)
		{
			return scraps.Where((GrabbableObject item) => item.itemProperties.isScrap).ActualScrapValueOfCollection();
		}

		public static int ActualSellValue(this GrabbableObject scrap)
		{
			return (int)Math.Round((float)scrap.scrapValue * GameUtils.StartOfRound.companyBuyingRate);
		}

		public static int ScrapValueOfCollection(this IEnumerable<GrabbableObject> scraps)
		{
			return scraps.Sum((GrabbableObject go) => go.scrapValue);
		}

		public static int ActualScrapValueOfCollection(this IEnumerable<GrabbableObject> scraps)
		{
			return (int)((float)scraps.Sum((GrabbableObject go) => go.scrapValue) * GameUtils.StartOfRound.companyBuyingRate);
		}

		public static bool CanIncludeItem(this GrabbableObject? item, string includeList)
		{
			GrabbableObject item2 = item;
			if (item2 == null)
			{
				Logger.LogWarning("CanIncludeItem: Trying to evaluate a null item");
				return false;
			}
			if (Utility.IsNullOrWhiteSpace(includeList))
			{
				Logger.LogWarning("CanIncludeItem: includeList is empty");
				return false;
			}
			bool num = item2.itemProperties.isScrap && item2 != null && item2.scrapValue > 0 && !item2.isHeld;
			bool flag = (from x in includeList.Split(",")
				select x.Trim() into x
				select Regex.Match(((Object)item2.itemProperties).name, x, RegexOptions.IgnoreCase)).Any((Match match) => match.Success);
			if (num)
			{
				return !flag;
			}
			return false;
		}

		internal static List<GrabbableObject> GetAllSellableScrapInShip()
		{
			return GetAllIncludedScrapInShip(Plugin.Instance.PluginConfig.SellIgnoreList);
		}

		internal static int GetShipTotalSellableScrapValue()
		{
			return GetAllSellableScrapInShip().ActualScrapValueOfCollection();
		}

		internal static List<GrabbableObject> GetScrapForAmount(int amount)
		{
			if (GetShipTotalSellableScrapValue() < amount)
			{
				return new List<GrabbableObject>();
			}
			int count = 0;
			List<GrabbableObject> list = (from scrap in GetAllSellableScrapInShip()
				orderby scrap.itemProperties.twoHanded descending, scrap.scrapValue descending
				select scrap).ToList();
			List<GrabbableObject> list2 = new List<GrabbableObject>();
			while (amount > 300)
			{
				GrabbableObject val = list[count++];
				list2.Add(val);
				amount -= val.ActualSellValue();
			}
			list = (from scrap in list.Skip(count)
				orderby scrap.scrapValue
				select scrap).ToList();
			count = 0;
			if (amount < list.Last().ActualSellValue())
			{
				list2.Add(list.Last());
				return list2;
			}
			while (amount > 0)
			{
				List<(GrabbableObject, GrabbableObject)> list3 = new List<(GrabbableObject, GrabbableObject)>();
				for (int i = count; i < list.Count; i++)
				{
					for (int j = i + 1; j < list.Count; j++)
					{
						list3.Add((list[i], list[j]));
					}
				}
				(GrabbableObject, GrabbableObject) tuple = list3.FirstOrDefault<(GrabbableObject, GrabbableObject)>(((GrabbableObject First, GrabbableObject Second) combo) => combo.First.ActualSellValue() + combo.Second.ActualSellValue() >= amount);
				var (val2, val3) = tuple;
				if ((Object)(object)val2 != (Object)null || (Object)(object)val3 != (Object)null)
				{
					list2.Add(tuple.Item1);
					list2.Add(tuple.Item2);
					return list2;
				}
				GrabbableObject val4 = list[count++];
				list2.Add(val4);
				amount -= val4.ActualSellValue();
			}
			return list2;
		}
	}
}
namespace QualityCompany.TerminalCommands
{
	internal class Commands1Sell
	{
		private static List<GrabbableObject> _recommendedScraps = new List<GrabbableObject>();

		private static int _sellScrapFor;

		private static int _sellScrapActualTarget;

		private static readonly Regex RemoveWhitespaceRegex = new Regex("\\s+");

		[TerminalCommand]
		private static TerminalCommandBuilder Run()
		{
			if (!Plugin.Instance.PluginConfig.TerminalSellCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("sell").WithHelpDescription("To sell items on the ship. Will not sell ignored items from config except when selling a specific item.").WithSubCommand(CreateAllSubCommand()).WithSubCommand(CreateQuotaSubCommand())
				.WithSubCommand(CreateTargetSubCommand())
				.WithSubCommand(Create2HandedSubCommand())
				.WithSubCommand(CreateAmountSubCommand())
				.WithSubCommand(CreateItemSubCommand())
				.AddTextReplacement("[sellScrapFor]", () => $"${_sellScrapFor}")
				.AddTextReplacement("[sellScrapTarget]", () => $"${_sellScrapActualTarget}")
				.AddTextReplacement("[numScrapSold]", () => _recommendedScraps.Count)
				.AddTextReplacement("[sellScrapActualTotal]", () => GameUtils.IsCompanyBuyingAtFullRate() ? $"${_recommendedScraps.ScrapValueOfCollection()}" : $"${_recommendedScraps.ActualScrapValueOfCollection()} (${_recommendedScraps.ScrapValueOfCollection()})")
				.AddTextReplacement("[shipScrapActualTotal]", delegate
				{
					List<GrabbableObject> allSellableScrapInShip = ScrapUtils.GetAllSellableScrapInShip();
					return GameUtils.IsCompanyBuyingAtFullRate() ? $"${allSellableScrapInShip.ScrapValueOfCollection()}" : $"${allSellableScrapInShip.ActualScrapValueOfCollection()} (${allSellableScrapInShip.ScrapValueOfCollection()})";
				})
				.AddTextReplacement("[companyBuyItemsCombo]", (Func<string>)GenerateBuyItemsComboText)
				.WithCondition("landedAtCompany", "ERROR: Usage of this feature is only permitted within Company bounds\n\nPlease land at 71-Gordion and repeat command.", GameUtils.IsLandedOnCompany)
				.WithCondition("hasScrapItems", "Bruh, you don't even have any items.", () => ScrapUtils.GetAllSellableScrapInShip().Count > 0)
				.WithCondition("notEnoughScrap", "Not enough scrap to meet [sellScrapFor] credits.\nTotal value: [shipScrapActualTotal].", () => _sellScrapFor <= ScrapUtils.GetShipTotalSellableScrapValue())
				.WithCondition("quotaAlreadyMet", "Quota has already been met.", () => TimeOfDay.Instance.profitQuota - TimeOfDay.Instance.quotaFulfilled > 0)
				.WithCondition("hasMatchingScrapItems", "No matching items found for input.", () => _recommendedScraps.Count > 0)
				.WithCondition("targetCommandDisabled", "Target command has been disabled", () => Plugin.Instance.PluginConfig.TerminalTargetCommandsEnabled)
				.WithCondition("targetAlreadyMet", "Target has already been met.", () => InfoMonitor.Instance.CalculatedNeededToReachTarget > 0);
			static string GenerateBuyItemsComboText()
			{
				if (_recommendedScraps == null || _recommendedScraps.Count == 0)
				{
					return "No items";
				}
				if (GameUtils.IsCompanyBuyingAtFullRate())
				{
					return _recommendedScraps.Select((GrabbableObject x) => $"{((Object)x.itemProperties).name}: {x.scrapValue}").Aggregate((string first, string next) => first + "\n" + next);
				}
				return _recommendedScraps.Select((GrabbableObject x) => $"{((Object)x.itemProperties).name}: ${x.ActualSellValue()} (${x.scrapValue})").Aggregate((string first, string next) => first + "\n" + next);
			}
		}

		private static TerminalSubCommandBuilder CreateAllSubCommand()
		{
			return new TerminalSubCommandBuilder("all").WithDescription("Sell ALL items on the ship.").WithMessage("[companyBuyingRateWarning]Requesting to sell ALL scrap ([numScrapSold]) for [sellScrapActualTotal] credits.").EnableConfirmDeny("Transaction complete. Sold [numScrapSold] scrap for [sellScrapActualTotal] credits.\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("landedAtCompany", "hasScrapItems")
				.WithPreAction((Action)delegate
				{
					_recommendedScraps = ScrapUtils.GetAllSellableScrapInShip();
					_sellScrapFor = _recommendedScraps.ActualScrapValueOfCollection();
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllScrap();
				});
		}

		private static TerminalSubCommandBuilder CreateQuotaSubCommand()
		{
			return new TerminalSubCommandBuilder("quota").WithDescription("Sell only to meet the current quota.").WithMessage("[companyBuyingRateWarning]Requesting to sell scrap as close to current quota ([sellScrapFor] credits) as possible...\nThe Company wants the follow items for a total of [sellScrapActualTotal]:\n[companyBuyItemsCombo]").EnableConfirmDeny("Transaction complete. Sold [numScrapSold] scrap for [sellScrapActualTotal] credits.\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("landedAtCompany", "hasScrapItems", "notEnoughScrap", "quotaAlreadyMet")
				.WithPreAction((Action)delegate
				{
					_sellScrapFor = TimeOfDay.Instance.profitQuota - TimeOfDay.Instance.quotaFulfilled;
					_recommendedScraps = ScrapUtils.GetScrapForAmount(_sellScrapFor);
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllTargetedScrap(_recommendedScraps);
				});
		}

		private static TerminalSubCommandBuilder CreateTargetSubCommand()
		{
			return new TerminalSubCommandBuilder("target").WithDescription("Sell only to meet the current set target. Will sell quota if target is below target.").WithMessage("[companyBuyingRateWarning]Requesting to sell scrap as close to current target ($[sellScrapTarget], needing [sellScrapFor]) as possible...\nThe Company wants the follow items for a total of [sellScrapActualTotal]:\n[companyBuyItemsCombo]").EnableConfirmDeny("Transaction complete. Sold [numScrapSold] scrap for [sellScrapActualTotal] credits.\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("targetCommandDisabled", "landedAtCompany", "hasScrapItems", "notEnoughScrap", "targetAlreadyMet")
				.WithPreAction((Action)delegate
				{
					_sellScrapActualTarget = SaveManager.SaveData.TargetForSelling;
					_sellScrapFor = InfoMonitor.Instance.CalculatedNeededToReachTarget;
					_recommendedScraps = (from x in ScrapUtils.GetScrapForAmount(_sellScrapFor)
						orderby ((Object)x.itemProperties).name, x.scrapValue descending
						select x).ToList();
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllTargetedScrap(_recommendedScraps);
				});
		}

		private static TerminalSubCommandBuilder CreateAmountSubCommand()
		{
			return new TerminalSubCommandBuilder("<amount>").WithDescription("Sell as close as possible to input amount").WithMessage("[companyBuyingRateWarning]Requesting to sell scrap as close to [sellScrapFor] as possible...\n\nThe Company wants the follow items for a total of $[sellScrapActualTotal]:\n[companyBuyItemsCombo]").EnableConfirmDeny("Sold [numScrapSold] scrap for $[sellScrapActualTotal].\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("landedAtCompany", "hasScrapItems", "notEnoughScrap")
				.WithInputMatch("^(\\d+)$")
				.WithPreAction(delegate(string? input)
				{
					_sellScrapFor = Convert.ToInt32(input);
					_recommendedScraps = (from x in ScrapUtils.GetScrapForAmount(_sellScrapFor)
						orderby ((Object)x.itemProperties).name, x.scrapValue descending
						select x).ToList();
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllTargetedScrap(_recommendedScraps);
				});
		}

		private static TerminalSubCommandBuilder Create2HandedSubCommand()
		{
			return new TerminalSubCommandBuilder("2h").WithDescription("Sell all 2handed items").WithMessage("[companyBuyingRateWarning]Requesting to sell all two-handed scrap.\n\nThe Company wants the follow items for a total of [sellScrapActualTotal]:\n[companyBuyItemsCombo]").EnableConfirmDeny("Transaction complete. Sold [numScrapSold] scrap for [sellScrapActualTotal] credits.\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("landedAtCompany", "hasScrapItems", "notEnoughScrap")
				.WithPreAction((Action)delegate
				{
					_recommendedScraps = (from x in ScrapUtils.GetAllSellableScrapInShip()
						where x.itemProperties.twoHanded
						orderby ((Object)x.itemProperties).name, x.scrapValue descending
						select x).ToList();
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllTargetedScrap(_recommendedScraps);
				});
		}

		private static TerminalSubCommandBuilder CreateItemSubCommand()
		{
			return new TerminalSubCommandBuilder("<item>").WithDescription("Sell all items matching the input. You can also use conditional value checks after the item name.\r\nNote: This will bypass the ignore list.\r\nExamples:\r\n> sell mask      - sells 'ComedyMask' and 'TragedyMask'\r\n> sell shot>50   - sells shotguns with a value of more than 50\r\n> sell lamp<=100 - lamps less than or equal to 100").WithMessage("[companyBuyingRateWarning]Requesting to sell all matching items.\n\nThe Company wants the follow items for a total of [sellScrapActualTotal]:\n[companyBuyItemsCombo]").EnableConfirmDeny("Transaction complete. Sold [numScrapSold] scrap for [sellScrapActualTotal] credits.\n\nThe company is not responsible for any calculation errors.")
				.WithConditions("landedAtCompany", "hasScrapItems", "hasMatchingScrapItems")
				.WithInputMatch("^(.+)$")
				.WithPreAction(delegate(string? input)
				{
					string input2 = input;
					input2 = RemoveWhitespaceRegex.Replace(input2, "");
					Match match = new Regex("^(\\w+)(>|<|>=|<=|=)(\\d+)$").Match(input2);
					if (!match.Success)
					{
						_recommendedScraps = (from x in ScrapUtils.GetAllScrapInShip()
							where ((Object)x.itemProperties).name.ToLower().Contains(input2)
							select x).ToList();
					}
					else
					{
						string itemName = match.Groups[1].Value;
						bool greaterThan = match.Groups[2].Value == ">";
						bool smallerThan = match.Groups[2].Value == "<";
						bool greaterThanEqualTo = match.Groups[2].Value == ">=";
						bool smallerThanEqualTo = match.Groups[2].Value == ">=";
						int amount = int.Parse(match.Groups[3].Value);
						_recommendedScraps = (from x in (from x in ScrapUtils.GetAllScrapInShip()
								where ((Object)x.itemProperties).name.ToLower().Contains(itemName)
								select x).Where(delegate(GrabbableObject x)
							{
								int num = x.ActualSellValue();
								return (!greaterThan) ? ((!smallerThan) ? ((!greaterThanEqualTo) ? ((!smallerThanEqualTo) ? (num == amount) : (num <= amount)) : (num >= amount)) : (num < amount)) : (num > amount);
							})
							orderby x.ActualSellValue() descending
							select x).ToList();
					}
				})
				.WithAction((Action)delegate
				{
					TargetManager.SellAllTargetedScrap(_recommendedScraps);
				});
		}
	}
	internal class Commands2Target
	{
		private static readonly ModLogger Logger = new ModLogger("Commands2Target");

		[TerminalCommand]
		private static TerminalCommandBuilder CreateTargetCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalTargetCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("target").WithHelpDescription("Set a target sell requirement for the target monitor.").WithCommandDescription("Please enter an amount.\neg: target 2000\n\n[targetExplanation]").WithSubCommand(new TerminalSubCommandBuilder("<amount>").WithDescription("The desired target wanted upon leaving The Company Building.").WithMessage("[companyBuyingRateWarning]Target has been set to [targetSetTo].\nMonitor Values:\n[targetMonitorValues]\n\n[targetExplanation]").WithInputMatch("^(\\d+$)$")
				.WithPreAction(delegate(string input)
				{
					if (!int.TryParse(input, out var result))
					{
						return "Pls enter a positive number";
					}
					TargetManager.UpdateTarget(result, GameNetworkManager.Instance.localPlayerController.playerUsername);
					return null;
				})
				.WithAction((Action)delegate
				{
				}))
				.WithCondition("landedAtCompany", "ERROR: Usage of this feature is only permitted within Company bounds\n\nPlease land at 71-Gordion and repeat command.", GameUtils.IsLandedOnCompany)
				.AddTextReplacement("[targetMonitorValues]", (Func<string>)InfoMonitor.GetText)
				.AddTextReplacement("[targetExplanation]", (Func<string>)GetTargetExplanation)
				.AddTextReplacement("[targetSetTo]", () => InfoMonitor.Instance.TargetTotalCredits.ToString());
		}

		private static string GetTargetExplanation()
		{
			return $"You want a target of [targetSetTo], so how do we do this? The target, in a nutshell, is how many credits you want AFTER leaving the company.\r\nThis includes overtime bonus for selling over and beyond the current Profit Quota. So, the InfoMonitor tries to take all of this into consideration:\r\n* Group credits = ${GameUtils.Terminal.groupCredits}\r\n* Profit Quota = ${GameUtils.TimeOfDay.profitQuota}\r\n* Amount fulfilled (sold) = ${GameUtils.TimeOfDay.quotaFulfilled}\r\n* Overtime bonus (on leaving) = ${InfoMonitor.Instance.CalculatedOvertime}\r\n\r\nThis is done in order to calculate a correct \"NEEDED\" amount as close as possible. This is sitting at ${InfoMonitor.Instance.CalculatedNeededToReachTarget}.\r\nIf this is at $0 then you do not need to sell more, unless you now choose to set a NEW target amount.\r\n\r\nThis does not (yet) account for:\r\n* Value of scrap on the desk = ${InfoMonitor.Instance.CalculatedDeskTotal}\r\n* Fees of deaths whilst at The Company\r\n\r\nHope this helps!";
		}
	}
	internal class Commands3Misc
	{
		private static readonly ModLogger Logger = new ModLogger("Commands3Misc");

		private static string? _playerSwitchName;

		private static int _playerSwitchIndex = -1;

		[TerminalCommand]
		private static TerminalCommandBuilder LaunchCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalMiscCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("launch").WithHelpDescription("To launch or land the ship. Host needs to do the very first launch.").WithCondition("inTransitLandedOrLeaving", "Unable to comply. The ship is landing or taking off.", () => StartOfRound.Instance.shipDoorsEnabled && !StartOfRound.Instance.shipHasLanded && !StartOfRound.Instance.shipIsLeaving).WithCondition("inTransitToMoon", "Unable to comply. The ship is already in transit to another moon.", () => !StartOfRound.Instance.shipDoorsEnabled && StartOfRound.Instance.travellingToNewLevel)
				.WithAction(delegate
				{
					StartMatchLever component = GameObject.Find("StartGameLever").GetComponent<StartMatchLever>();
					bool num = !component.leverHasBeenPulled;
					component.PullLever();
					component.LeverAnimation();
					if (num)
					{
						component.StartGame();
					}
					else
					{
						component.EndGame();
					}
					return "Initiating " + (component.leverHasBeenPulled ? "landing" : "launch") + " sequence.";
				});
		}

		[TerminalCommand]
		private static TerminalCommandBuilder DoorCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalMiscCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("door").WithHelpDescription("Toggle the ship door.").WithAction(delegate
			{
				((UnityEvent<PlayerControllerB>)(object)GameObject.Find(StartOfRound.Instance.hangarDoorsClosed ? "StartButton" : "StopButton").GetComponentInChildren<InteractTrigger>().onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
				return "Toggled door.";
			});
		}

		[TerminalCommand]
		private static TerminalCommandBuilder TeleportCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalMiscCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("tp").WithHelpDescription("Teleport the currently active player on the view monitor to the ship. Must have a teleporter.").WithAction(delegate
			{
				GameObject val = GameObject.Find("Teleporter(Clone)");
				if (val == null)
				{
					return "ERROR: You don't have a teleporter!";
				}
				ShipTeleporter component = val.GetComponent<ShipTeleporter>();
				if (component == null)
				{
					return "ERROR: Can't find ShipTeleporter component";
				}
				if (!component.buttonTrigger.interactable)
				{
					return "Teleporter is on cooldown!";
				}
				((UnityEvent<PlayerControllerB>)(object)component.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
				return "Teleporting active viewing player";
			});
		}

		[TerminalCommand]
		private static TerminalCommandBuilder LightsCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalMiscCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("lights").WithHelpDescription("Toggle the lights.").WithAction(delegate
			{
				((UnityEvent<PlayerControllerB>)(object)GameObject.Find("LightSwitch").GetComponent<InteractTrigger>().onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
				return "Toggled lights";
			});
		}

		[TerminalCommand]
		private static TerminalCommandBuilder TimeCommand()
		{
			if (!Plugin.Instance.PluginConfig.TerminalMiscCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("time").WithHelpDescription("Get the current time whilst on a moon.").WithAction((Func<string>)GetTime);
			static string GetTime()
			{
				if (StartOfRound.Instance.currentLevel.planetHasTime && StartOfRound.Instance.shipDoorsEnabled)
				{
					return "The time is currently " + ((TMP_Text)HUDManager.Instance.clockNumber).text.Replace('\n', ' ') + ".\n";
				}
				return "You're not on a moon. There is no time here.\n";
			}
		}

		[TerminalCommand]
		private static TerminalCommandBuilder QuickSwitchCommand()
		{
			if (!Plugin.Instance.PluginConfig.ExperimentalFeaturesEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("vs").WithHelpDescription("Execute 'switch' but easier.").WithAction(delegate
			{
				GameObject val = GameObject.Find("CameraMonitorSwitchButton");
				if (val == null)
				{
					return "ERROR: Failed to find CameraMonitorSwitchButton :/";
				}
				InteractTrigger component = ((Component)val.transform.GetChild(0)).GetComponent<InteractTrigger>();
				if (component == null)
				{
					return "ERROR: Failed to find CameraMonitorSwitchButton InteractTrigger";
				}
				if (!component.interactable)
				{
					return "Teleporter is on cooldown!";
				}
				((UnityEvent<PlayerControllerB>)(object)component.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
				return $"Switched to {GameUtils.StartOfRound.mapScreenPlayerName}!";
			});
		}

		[TerminalCommand]
		private static TerminalCommandBuilder Command()
		{
			if (!Plugin.Instance.PluginConfig.ExperimentalFeaturesEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("vw").WithHelpDescription("Execute 'switch' to a player but easier.").WithSubCommand(new TerminalSubCommandBuilder("<player>").WithMessage("Switched to [playerSwitchName]").WithConditions("validPlayer").WithInputMatch("^(\\w+)$")
				.WithPreAction(delegate(string input)
				{
					input = input.ToLower();
					_playerSwitchName = null;
					_playerSwitchIndex = -1;
					List<string> list = new List<string>();
					for (int i = 0; i < GameUtils.StartOfRound.mapScreen.radarTargets.Count; i++)
					{
						string name = GameUtils.StartOfRound.mapScreen.radarTargets[i].name;
						Logger.TryLogDebug($"view cmd: player {i}: {name}");
						list.Add(name.ToLower());
					}
					for (int j = 0; j < list.Count; j++)
					{
						if (!(list[j] != input) || list[j].StartsWith(input))
						{
							_playerSwitchName = list[j];
							_playerSwitchIndex = j;
							break;
						}
					}
					if (_playerSwitchName == null)
					{
						_playerSwitchName = input;
					}
					return null;
				})
				.WithAction((Action)delegate
				{
					Logger.TryLogDebug($"view command: {_playerSwitchName} @ {_playerSwitchIndex}");
					GameUtils.StartOfRound.mapScreen.SwitchRadarTargetAndSync(_playerSwitchIndex);
				})).AddTextReplacement("[playerSwitchName]", () => _playerSwitchName ?? "unknown")
				.WithCondition("validPlayer", "Invalid player: [playerSwitchName]", () => _playerSwitchIndex >= 0);
		}
	}
	internal class Commands4Debug
	{
		private static readonly ModLogger Logger = new ModLogger("Commands4Debug");

		private static int scrapCountToHack;

		[TerminalCommand]
		private static TerminalCommandBuilder Run()
		{
			if (!Plugin.Instance.PluginConfig.TerminalDebugCommandsEnabled)
			{
				return null;
			}
			return new TerminalCommandBuilder("hack").WithHelpDescription("Spawn some ez lewt.").WithCommandDescription("Please enter a number of scrap items to spawn.\neg: hack 5").WithCondition("isHost", "You are not host.", () => NetworkManager.Singleton.IsHost)
				.WithSubCommand(new TerminalSubCommandBuilder("<count>").WithDescription("Hack in <count> number of items.").WithMessage("Hacked in XYZ items").WithConditions("isHost")
					.WithInputMatch("^(\\d+$)$")
					.WithAction(delegate(string input)
					{
						Logger.TryLogDebug("Hack: WithAction?");
						scrapCountToHack = Convert.ToInt32(input);
						scrapCountToHack = Math.Min(100, scrapCountToHack);
						HackInScrap();
						return $"Hack in {scrapCountToHack} items";
					}));
		}

		private static void HackInScrap()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
			Vector3 position = ((Component)GameNetworkManager.Instance.localPlayerController).transform.position;
			for (int i = 0; i < scrapCountToHack; i++)
			{
				Item val = itemsList[ServiceRegistry.Randomizer.GetInt(0, itemsList.Count)];
				while (!val.isScrap)
				{
					val = itemsList[ServiceRegistry.Randomizer.GetInt(0, itemsList.Count)];
				}
				GameObject spawnPrefab = val.spawnPrefab;
				GameObject val2 = Object.Instantiate<GameObject>(spawnPrefab, position, Quaternion.identity);
				GrabbableObject component = val2.GetComponent<GrabbableObject>();
				if (component == null)
				{
					Logger.TryLogDebug(((Object)spawnPrefab).name + ": did not have a GrabbableObject component");
					continue;
				}
				int scrapValue = GetScrapValue(component.itemProperties);
				Logger.TryLogDebug($"HACK: #{i + 1} - {((Object)spawnPrefab).name} for {scrapValue}");
				val2.GetComponent<NetworkObject>().Spawn(false);
				NetworkHandler.Instance.SyncValuesClientRpc(scrapValue, new NetworkBehaviourReference((NetworkBehaviour)(object)component));
			}
		}

		private static int GetScrapValue(Item itemProps)
		{
			int num = itemProps.minValue;
			int num2 = itemProps.maxValue;
			if (num == 0 || num2 == 0)
			{
				num = 1;
				num2 = 100;
			}
			else if (num > num2)
			{
				num = itemProps.maxValue;
				num2 = itemProps.minValue;
			}
			return ServiceRegistry.Randomizer.GetInt(num, num2) / 2;
		}
	}
}
namespace QualityCompany.Service
{
	internal class ModLogger
	{
		private readonly string _moduleName;

		internal ModLogger(string moduleName)
		{
			_moduleName = moduleName;
		}

		internal void TryLogDebug(object message)
		{
			if (Plugin.Instance.PluginConfig.ShowDebugLogs)
			{
				Plugin.Instance.Log.LogDebug((object)$"[{_moduleName}] {message}");
			}
		}

		internal void LogDebug(object message)
		{
			Plugin.Instance.Log.LogDebug((object)$"[{_moduleName}] {message}");
		}

		internal void LogDebugMode(object message)
		{
		}

		internal void LogMessage(object message)
		{
			Plugin.Instance.Log.LogMessage((object)$"[{_moduleName}] {message}");
		}

		internal void LogWarning(object message)
		{
			Plugin.Instance.Log.LogWarning((object)$"[{_moduleName}] {message}");
		}

		internal void LogInfo(object message)
		{
			Plugin.Instance.Log.LogInfo((object)$"[{_moduleName}] {message}");
		}

		internal void LogError(object message)
		{
			Plugin.Instance.Log.LogError((object)$"[{_moduleName}] {message}");
		}

		internal void LogFatal(object message)
		{
			Plugin.Instance.Log.LogFatal((object)$"[{_moduleName}] {message}");
		}
	}
	internal class RandomizerService
	{
		private readonly Random _random = new Random();

		public RandomizerService()
		{
			Plugin.Instance.Log.LogMessage((object)"RandomizerService.Start");
		}

		public int GetInt(int min, int max)
		{
			return _random.Next(min, max);
		}
	}
	internal class ServiceRegistry
	{
		public static RandomizerService Randomizer = new RandomizerService();
	}
}
namespace QualityCompany.Patch
{
	[HarmonyPatch(typeof(DepositItemsDesk))]
	internal class DepositItemsDeskPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("PlaceItemOnCounter")]
		private static void PlaceItemOnCounterPatch()
		{
			if (Plugin.Instance.PluginConfig.NetworkingEnabled)
			{
				CompanyNetworkHandler.Instance.SyncDepositDeskTotalValueServerRpc();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("AddObjectToDeskClientRpc")]
		private static void CalculateTotalOnDesk()
		{
			InfoMonitor.UpdateMonitor();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		public static void AwakePatch(GameNetworkManager __instance)
		{
			GameEvents.OnGameNetworkManagerAwake(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		public static void StartPatch(GameNetworkManager __instance)
		{
			GameEvents.OnGameNetworkManagerStart(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("Disconnect")]
		private static void DisconnectPatch(GameNetworkManager __instance)
		{
			GameEvents.OnDisconnected(__instance);
			GameUtils.Reset();
		}

		[HarmonyPrefix]
		[HarmonyPatch("SaveGame")]
		private static bool SaveGamePatch(GameNetworkManager __instance)
		{
			SaveManager.Save();
			GameEvents.OnSaveGame(__instance);
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HudManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void Start(HUDManager __instance)
		{
			GameEvents.OnHudManagerStart(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("ApplyPenalty")]
		private static void ApplyPenalty()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("DisplayCreditsEarning")]
		private static void DisplayCreditsEarning()
		{
			InfoMonitor.UpdateMonitor();
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("DisplayDaysLeft")]
		private static void DisplayDaysLeft(HUDManager __instance)
		{
			SaveManager.SaveData.TotalDaysPlayedForCurrentQuota++;
			SaveManager.Save();
			InfoMonitor.UpdateMonitor();
			GameEvents.OnDisplayDaysLeft(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("ConnectClientToPlayerObject")]
		private static void OnPlayerConnect()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("SwitchToItemSlot")]
		private static void SwitchToItemSlotPatch(PlayerControllerB __instance)
		{
			GameEvents.OnPlayerSwitchToItemSlot(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("GrabObjectClientRpc")]
		private static void RefreshLootOnPickupClient(PlayerControllerB __instance, ref NetworkObjectReference grabbedObject)
		{
			NetworkObject val = default(NetworkObject);
			if (((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
			{
				GrabbableObject componentInChildren = ((Component)val).gameObject.GetComponentInChildren<GrabbableObject>();
				GameEvents.OnPlayerGrabObjectClientRpc(__instance, componentInChildren);
				if (componentInChildren.isInShipRoom || componentInChildren.isInElevator)
				{
					InfoMonitor.UpdateMonitor();
				}
				LootMonitor.UpdateMonitor();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("ThrowObjectClientRpc")]
		private static void RefreshLootOnThrowClient(PlayerControllerB __instance, bool droppedInElevator, bool droppedInShipRoom)
		{
			GameEvents.OnPlayerThrowObjectClientRpc(__instance);
			if (droppedInShipRoom || droppedInElevator)
			{
				InfoMonitor.UpdateMonitor();
			}
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("DiscardHeldObject")]
		private static void DiscardHeldObjectPatch(PlayerControllerB __instance)
		{
			GameEvents.OnPlayerDiscardHeldObject(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("KillPlayer")]
		private static void KillPlayerPatch(PlayerControllerB __instance)
		{
			GameEvents.OnPlayerDeath(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("DropAllHeldItems")]
		private static void DropAllHeldItemsPatch(PlayerControllerB __instance)
		{
			GameEvents.OnPlayerDropAllHeldItems(__instance);
		}
	}
	[HarmonyPatch(typeof(ShotgunItem))]
	internal class ShotgunItemPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("ShootGun")]
		private static void ShootGunPatch()
		{
			GameEvents.OnPlayerShotgunShoot(GameNetworkManager.Instance.localPlayerController);
		}

		[HarmonyPostfix]
		[HarmonyPatch("ReloadGunEffectsClientRpc")]
		private static void ReloadGunEffectsClientRpcPatch()
		{
			GameEvents.OnPlayerShotgunReload(GameNetworkManager.Instance.localPlayerController);
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatcher
	{
		private static readonly ModLogger Logger = new ModLogger("StartOfRoundPatcher");

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		public static void AwakePatch(StartOfRound __instance)
		{
			GameEvents.OnStartOfRoundAwake(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		public static void StartPatch(StartOfRound __instance)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			GameUtils.Init();
			GameEvents.OnStartOfRoundStart(__instance);
			SaveManager.Load();
			new GameObject("QualityCompanyLoader").AddComponent<ModuleLoader>();
		}

		[HarmonyPostfix]
		[HarmonyPatch("ReviveDeadPlayers")]
		private static void ReviveDeadPlayersPatch()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("playersFiredGameOver")]
		private static void PlayersFiredGameOverPatch(StartOfRound __instance)
		{
			GameEvents.OnPlayersFired(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("EndOfGame")]
		private static void EndOfGamePatch(StartOfRound __instance)
		{
			GameEvents.OnEndOfGame(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("SyncShipUnlockablesClientRpc")]
		private static void SyncShipUnlockablesClientRpcPatch()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("ChangeLevelClientRpc")]
		private static void ChangeLevelClientRpcPatch()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("StartGame")]
		private static void StartGamePatch()
		{
			InfoMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("ArriveAtLevel")]
		private static void ArriveAtLevelPatch()
		{
			InfoMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("SetMapScreenInfoToCurrentLevel")]
		private static void SetMapScreenInfoToCurrentLevelPatch(ref TextMeshProUGUI ___screenLevelDescription, ref SelectableLevel ___currentLevel)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Orbiting: " + ___currentLevel.PlanetName + "\n");
			stringBuilder.Append("Weather: " + FormatWeather(___currentLevel.currentWeather) + "\n");
			stringBuilder.Append(___currentLevel.LevelDescription ?? "");
			((TMP_Text)___screenLevelDescription).text = stringBuilder.ToString();
		}

		private static string FormatWeather(LevelWeatherType currentWeather)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected I4, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			return string.Format("<color=#{0}>{1}</color>", (currentWeather - -1) switch
			{
				0 => "69FF6B", 
				1 => "69FF6B", 
				2 => "FFDC00", 
				4 => "FFDC00", 
				3 => "FF9300", 
				5 => "FF9300", 
				6 => "FF0000", 
				_ => "FFFFFF", 
			}, currentWeather);
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		private static readonly ModLogger Logger = new ModLogger("TerminalPatch");

		private static string? _currentInput;

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePatch(Terminal __instance)
		{
			GameUtils.Terminal = __instance;
			AdvancedTerminal.Init();
			GameEvents.OnTerminalAwakeEvent(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("SyncGroupCreditsClientRpc")]
		private static void SyncGroupCreditsClientRpcPatch()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("ParsePlayerSentence")]
		public static TerminalNode ParsePlayerSentencePatch(TerminalNode __result, Terminal __instance)
		{
			Logger.LogDebugMode("ParsePlayerSentencePatch.start");
			if ((Object)(object)__result == (Object)null)
			{
				return null;
			}
			Logger.LogDebugMode($" > {__result} | {((Object)__result).name} | {__result.terminalEvent}");
			if (__result.terminalEvent != null && __result.terminalEvent.StartsWith("qc:") && __result.terminalEvent.EndsWith("_help"))
			{
				return __result;
			}
			string text = __instance.screenText.text;
			int textAdded = __instance.textAdded;
			int length = text.Length;
			int num = length - textAdded;
			string text2 = text.Substring(num, length - num).ToLower().Trim();
			string inputCommand = (text2.Contains(" ") ? text2.Substring(0, text2.LastIndexOf(' ')) : text2);
			object currentInput;
			if (!text2.Contains(" "))
			{
				currentInput = null;
			}
			else
			{
				string text3 = text2;
				num = text2.LastIndexOf(' ') + 1;
				currentInput = text3.Substring(num, text3.Length - num);
			}
			_currentInput = (string?)currentInput;
			Logger.LogDebugMode(" > input: " + text2 + " | " + inputCommand + " | " + _currentInput);
			List<TerminalCommandBuilder> list = AdvancedTerminal.Commands.Where((TerminalCommandBuilder x) => (inputCommand.Length >= 3) ? x.CommandText.StartsWith(inputCommand) : (x.CommandText == inputCommand)).ToList();
			if (!list.Any())
			{
				Logger.LogDebugMode(" > No commands found matching input '" + text2 + "' | '" + inputCommand + "' with args '" + _currentInput + "'");
				return __result;
			}
			if (list.Count > 1)
			{
				Logger.LogError(" > Found multiple commands! HOW? Only using first one. Found: " + list.Select((TerminalCommandBuilder x) => x.CommandText).Aggregate((string first, string second) => first + ", " + second));
			}
			TerminalCommandBuilder terminalCommandBuilder = list.First();
			Logger.LogDebugMode(" > command: " + terminalCommandBuilder.CommandText + " | event: /" + (__result.terminalEvent ?? "empty") + "/");
			if (!terminalCommandBuilder.IsSimpleCommand)
			{
				return ExecuteComplexCommand(terminalCommandBuilder, __result, inputCommand, _currentInput);
			}
			return ExecuteSimpleCommand(terminalCommandBuilder);
		}

		private static TerminalNode ExecuteSimpleCommand(TerminalCommandBuilder command)
		{
			Logger.LogDebugMode(" > executing SimpleCommand");
			Logger.LogDebugMode("  > checking conditions");
			foreach (ConditionNode conditionNode in command.ConditionNodes)
			{
				Logger.LogDebugMode("   > condition: " + ((Object)conditionNode.Node).name);
				if (conditionNode.Condition())
				{
					Logger.LogDebugMode("    > FAILED");
					return conditionNode.Node;
				}
			}
			Logger.LogDebugMode("  > returning " + ((Object)command.Node).name);
			return command.Node;
		}

		private static TerminalNode ExecuteComplexCommand(TerminalCommandBuilder command, TerminalNode __result, string inputCommand, string inputCommandArgs)
		{
			string inputCommandArgs2 = inputCommandArgs;
			string inputCommand2 = inputCommand;
			Logger.LogDebugMode(" > executing ComplexCommand");
			TerminalSubCommand terminalSubCommand = command.SubCommands.FirstOrDefault((TerminalSubCommand subCmd) => !subCmd.IsVariableCommand && subCmd.Name == inputCommandArgs2);
			if (terminalSubCommand != null)
			{
				string text = terminalSubCommand.PreConditionAction?.Invoke();
				if (text != null)
				{
					__result.displayText = text;
					return __result;
				}
			}
			else
			{
				if (Utility.IsNullOrWhiteSpace(inputCommandArgs2))
				{
					return command.Node;
				}
				terminalSubCommand = command.SubCommands.FirstOrDefault(delegate(TerminalSubCommand subCmd)
				{
					if (!subCmd.IsVariableCommand)
					{
						return false;
					}
					Logger.LogDebugMode("  > INPUT: '" + inputCommand2 + "' | '" + inputCommandArgs2 + "' | REGEX: " + subCmd.VariableRegexMatchPattern);
					return new Regex(subCmd.VariableRegexMatchPattern).Match(inputCommandArgs2).Success;
				});
				string text2 = terminalSubCommand?.VariablePreAction?.Invoke(inputCommandArgs2);
				if (text2 != null)
				{
					__result.displayText = text2;
					return __result;
				}
			}
			if (terminalSubCommand == null)
			{
				Logger.LogDebugMode("  > No matching sub command found for input: '" + inputCommand2 + "' | '" + inputCommandArgs2 + "'");
				return command.Node;
			}
			Logger.LogDebugMode("  > checking special conditions");
			foreach (string conditionString in terminalSubCommand.Conditions)
			{
				ConditionNode conditionNode = command.ConditionNodes.FirstOrDefault((ConditionNode x) => ((Object)x.Node).name.EndsWith(conditionString));
				if (conditionNode == null)
				{
					Logger.LogError("> SubCommand " + terminalSubCommand.Name + " has special criteria for '" + conditionString + "' but it is not found as part of the commands' special conditions list.");
					break;
				}
				Logger.LogDebugMode($"   > {conditionString} = {conditionNode.Condition()}");
				if (!conditionNode.Condition())
				{
					Logger.LogDebugMode("   > FAILED: " + ((Object)conditionNode.Node).name);
					return conditionNode.Node;
				}
			}
			return terminalSubCommand.Node;
		}

		[HarmonyPostfix]
		[HarmonyPatch("TextPostProcess")]
		public static string TextPostProcessPatch(string mod, TerminalNode node, string __result)
		{
			Logger.LogDebugMode("TextPostProcessPatch.start: " + ((Object)node).name + " | " + node.terminalEvent);
			if (node.terminalEvent == null)
			{
				return __result;
			}
			if (!node.terminalEvent.StartsWith("qc:"))
			{
				return __result;
			}
			string key;
			Func<string> value;
			foreach (KeyValuePair<string, Func<string>> globalTextReplacement in AdvancedTerminal.GlobalTextReplacements)
			{
				globalTextReplacement.Deconstruct(out key, out value);
				string text = key;
				Func<string> func = value;
				if (__result.Contains(text))
				{
					Logger.LogDebugMode(" > found global: " + text);
					__result = __result.Replace(text, func());
				}
			}
			if (!TryGetCommandByEvent(node.terminalEvent, out TerminalCommandBuilder command, out TerminalSubCommand _))
			{
				return __result;
			}
			foreach (KeyValuePair<string, Func<string>> textProcessPlaceholder in command.TextProcessPlaceholders)
			{
				textProcessPlaceholder.Deconstruct(out key, out value);
				string text2 = key;
				Func<string> func2 = value;
				if (__result.Contains(text2))
				{
					Logger.LogDebugMode(" > found replacement: " + command.CommandText + "." + text2);
					__result = __result.Replace(text2, func2());
				}
			}
			Logger.LogDebugMode("TextPostProcessPatch.end\n");
			return __result;
		}

		[HarmonyPostfix]
		[HarmonyPatch("RunTerminalEvents")]
		public static void RunTerminalEventsPatch(TerminalNode node)
		{
			Logger.LogDebugMode("RunTerminalEvents: | node.name: " + (((Object)node).name ?? "null") + " | node.terminalEvent: " + (node.terminalEvent ?? "empty") + " | " + $"node.isConfirm: {node.isConfirmationNode}");
			if (ShouldSkipNode(node))
			{
				return;
			}
			Logger.LogDebugMode(" > Checking " + ((Object)node).name);
			if (!TryGetCommandByEvent(node.terminalEvent, out TerminalCommandBuilder command, out TerminalSubCommand subCommand))
			{
				return;
			}
			Logger.LogDebugMode("  > Checking " + ((Object)command.Node).name);
			if (command.IsSimpleCommand)
			{
				Logger.LogDebugMode("  > IsSimpleCommand, SKIP??");
				Logger.LogDebugMode(" > EXEC simple command: " + ((Object)command.Node).name);
				string text = command.Action();
				node.displayText = text + AdvancedTerminal.EndOfMessage;
				return;
			}
			if (subCommand == null)
			{
				Logger.LogError("Have a complex command but failed to find sub command for " + ((Object)command.Node).name);
				return;
			}
			Logger.LogDebugMode("  > Found " + ((Object)subCommand.Node).name);
			Logger.LogDebugMode($"   > ActionInputResult {subCommand.ActionInputResult == null}");
			Logger.LogDebugMode($"   > ActionResult {subCommand.ActionResult == null}");
			if (subCommand.ActionInputResult != null)
			{
				string text2 = subCommand.ActionInputResult(_currentInput);
				if (text2 != null)
				{
					node.displayText = text2 + AdvancedTerminal.EndOfMessage;
				}
			}
			else if (subCommand.ActionResult != null)
			{
				string text3 = subCommand.ActionResult();
				if (text3 != null)
				{
					node.displayText = text3 + AdvancedTerminal.EndOfMessage;
				}
			}
		}

		private static bool ShouldSkipNode(TerminalNode node)
		{
			if (node.terminalEvent == null)
			{
				return true;
			}
			if (!node.terminalEvent.StartsWith("qc:"))
			{
				return true;
			}
			if (node.isConfirmationNode)
			{
				return true;
			}
			if (node.terminalEvent.EndsWith("_condition"))
			{
				return true;
			}
			if (node.terminalEvent.EndsWith("_help"))
			{
				return true;
			}
			if (node.terminalEvent.EndsWith("_deny_event"))
			{
				return true;
			}
			return false;
		}

		private static bool TryGetCommandByEvent(string terminalEvent, out TerminalCommandBuilder command, out TerminalSubCommand? subCommand)
		{
			string terminalEvent2 = terminalEvent;
			command = null;
			subCommand = null;
			foreach (TerminalCommandBuilder command2 in AdvancedTerminal.Commands)
			{
				if (command2.IsSimpleCommand && command2.ActionEvent == terminalEvent2)
				{
					command = command2;
					return true;
				}
				TerminalSubCommand terminalSubCommand = command2.SubCommands.FirstOrDefault((TerminalSubCommand x) => x.ActionEvent == terminalEvent2);
				if (terminalSubCommand != null)
				{
					command = command2;
					subCommand = terminalSubCommand;
					return true;
				}
				if (command2.ConditionNodes.FirstOrDefault((ConditionNode x) => x.Node.terminalEvent == terminalEvent2) != null)
				{
					command = command2;
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("SyncNewProfitQuotaClientRpc")]
		private static void SyncNewProfitQuotaClientRpcPatch()
		{
			SaveManager.SaveData.TotalShipLootAtStartForCurrentQuota = ScrapUtils.GetShipTotalRawScrapValue();
			SaveManager.SaveData.TotalDaysPlayedForCurrentQuota = 0;
			SaveManager.Save();
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch("MoveTimeOfDay")]
		private static void MoveTimeOfDayPatch()
		{
			TimeMonitor.UpdateMonitor();
			GameEvents.OnGameTimeUpdate();
		}

		[HarmonyPostfix]
		[HarmonyPatch("UpdateProfitQuotaCurrentTime")]
		private static void UpdateProfitQuotaCurrentTimePatch()
		{
			InfoMonitor.UpdateMonitor();
		}
	}
}
namespace QualityCompany.Network
{
	internal class CompanyNetworkHandler : NetworkBehaviour
	{
		private readonly ModLogger Logger = new ModLogger("CompanyNetworkHandler");

		private bool _retrievedPluginConfig;

		private bool _retrievedSaveFile;

		public static CompanyNetworkHandler Instance { get; private set; }

		private void Start()
		{
			Instance = this;
			if (!((NetworkBehaviour)this).IsHost)
			{
				Logger.TryLogDebug("CLIENT: Requesting hosts config...");
				RequestPluginConfigServerRpc();
				RequestSaveDataServerRpc();
				((MonoBehaviour)this).StartCoroutine(ClientSanityCheck());
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void RequestPluginConfigServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2054575850u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2054575850u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Logger.TryLogDebug("HOST: A client is requesting plugin config");
					string json = JsonConvert.SerializeObject((object)Plugin.Instance.PluginConfig);
					SendPluginConfigClientRpc(json);
				}
			}
		}

		[ClientRpc]
		private void SendPluginConfigClientRpc(string json)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2944123196u, val, (RpcDelivery)0);
				bool flag = json != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(json, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2944123196u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || ((NetworkBehaviour)this).IsHost || ((NetworkBehaviour)this).IsServer)
			{
				return;
			}
			if (_retrievedPluginConfig)
			{
				Logger.TryLogDebug("CLIENT: Config has already been received from host, disregarding.");
				return;
			}
			_retrievedPluginConfig = true;
			PluginConfig pluginConfig = JsonConvert.DeserializeObject<PluginConfig>(json);
			if (pluginConfig == null)
			{
				Logger.LogError("CLIENT: failed to deserialize plugin config from host, disregarding. raw json: " + json);
				return;
			}
			Logger.TryLogDebug("Config received, deserializing and constructing...");
			Plugin.Instance.PluginConfig.ApplyHostConfig(pluginConfig);
		}

		[ServerRpc(RequireOwnership = false)]
		private void RequestSaveDataServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(933660961u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 933660961u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Logger.TryLogDebug("HOST: A client is requesting save data");
					string json = JsonConvert.SerializeObject((object)SaveManager.SaveData);
					SendSaveDataClientRpc(json);
				}
			}
		}

		[ClientRpc]
		private void SendSaveDataClientRpc(string json)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(715264659u, val, (RpcDelivery)0);
				bool flag = json != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(json, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 715264659u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsHost && !((NetworkBehaviour)this).IsServer && !_retrievedSaveFile)
			{
				_retrievedSaveFile = true;
				SaveManager.ClientLoadFromString(json);
				InfoMonitor.UpdateMonitor();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void SyncDepositDeskTotalValueServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2710218534u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2710218534u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Logger.TryLogDebug("UpdateSellTargetServerRpc");
					SyncDepositDeskTotalValueClientRpc();
				}
			}
		}

		[ClientRpc]
		private void SyncDepositDeskTotalValueClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1186880063u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1186880063u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Logger.TryLogDebug("SyncDepositDeskTotalValueClientRpc");
					InfoMonitor.UpdateMonitor();
				}
			}
		}

		private IEnumerator ClientSanityCheck()
		{
			yield return (object)new WaitForSeconds(5f);
			if (!_retrievedPluginConfig)
			{
				Logger.LogError("CLIENT: Still have not received plugin config from host, something is wrong!");
			}
			if (!_retrievedSaveFile)
			{
				Logger.LogError("CLIENT: Still have not received game save data from host, something is wrong!");
			}
		}

		public override void OnNetworkSpawn()
		{
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_CompanyNetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2054575850u, new RpcReceiveHandler(__rpc_handler_2054575850));
			NetworkManager.__rpc_func_table.Add(2944123196u, new RpcReceiveHandler(__rpc_handler_2944123196));
			NetworkManager.__rpc_func_table.Add(933660961u, new RpcReceiveHandler(__rpc_handler_933660961));
			NetworkManager.__rpc_func_table.Add(715264659u, new RpcReceiveHandler(__rpc_handler_715264659));
			NetworkManager.__rpc_func_table.Add(2710218534u, new RpcReceiveHandler(__rpc_handler_2710218534));
			NetworkManager.__rpc_func_table.Add(1186880063u, new RpcReceiveHandler(__rpc_handler_1186880063));
		}

		private static void __rpc_handler_2054575850(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((CompanyNetworkHandler)(object)target).RequestPluginConfigServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2944123196(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string json = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref json, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((CompanyNetworkHandler)(object)target).SendPluginConfigClientRpc(json);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_933660961(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((CompanyNetworkHandler)(object)target).RequestSaveDataServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_715264659(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string json = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref json, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((CompanyNetworkHandler)(object)target).SendSaveDataClientRpc(json);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2710218534(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((CompanyNetworkHandler)(object)target).SyncDepositDeskTotalValueServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1186880063(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((CompanyNetworkHandler)(object)target).SyncDepositDeskTotalValueClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "CompanyNetworkHandler";
		}
	}
	internal class LatencyHandler : NetworkBehaviour
	{
		public static LatencyHandler Instance { get; private set; }

		[ServerRpc(RequireOwnership = false)]
		internal void PingServerRpc(ulong playerClientId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2110549348u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerClientId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2110549348u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					PingClientRpc(playerClientId);
				}
			}
		}

		[ClientRpc]
		private void PingClientRpc(ulong playerClientId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3166242878u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerClientId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3166242878u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).NetworkManager.IsHost && GameNetworkManager.Instance.localPlayerController.playerClientId == playerClientId)
				{
					LatencyModule.Instance.UpdateLatency();
				}
			}
		}

		public override void OnNetworkSpawn()
		{
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_LatencyHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2110549348u, new RpcReceiveHandler(__rpc_handler_2110549348));
			NetworkManager.__rpc_func_table.Add(3166242878u, new RpcReceiveHandler(__rpc_handler_3166242878));
		}

		private static void __rpc_handler_2110549348(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong playerClientId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerClientId);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LatencyHandler)(object)target).PingServerRpc(playerClientId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3166242878(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong playerClientId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerClientId);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LatencyHandler)(object)target).PingClientRpc(playerClientId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "LatencyHandler";
		}
	}
	internal class ModNetworkManager
	{
		private static GameObject? _networkPrefab;

		private static bool hasInit;

		internal static void Init()
		{
			GameEvents.GameNetworkManagerStart += delegate
			{
				Start();
			};
			GameEvents.StartOfRoundAwake += delegate
			{
				Load();
			};
		}

		private static void Start()
		{
			if (Plugin.Instance.PluginConfig.NetworkingEnabled && _networkPrefab == null && !hasInit)
			{
				hasInit = true;
				_networkPrefab = AssetManager.CustomAssets.LoadAsset<GameObject>("ExampleNetworkHandler");
				_networkPrefab.AddComponent<NetworkHandler>();
				_networkPrefab.AddComponent<CompanyNetworkHandler>();
				_networkPrefab.AddComponent<LatencyHandler>();
				NetworkManager.Singleton.AddNetworkPrefab(_networkPrefab);
			}
		}

		private static void Load()
		{
			//IL_0038: 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)
			if (Plugin.Instance.PluginConfig.NetworkingEnabled && (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) && _networkPrefab != null)
			{
				Object.Instantiate<GameObject>(_networkPrefab, Vector3.zero, Quaternion.identity).GetComponent<NetworkObject>().Spawn(false);
			}
		}
	}
	internal class NetworkHandler : NetworkBehaviour
	{
		private readonly ModLogger Logger = new ModLogger("NetworkHandler");

		internal static NetworkHandler Instance { get; private set; }

		[ClientRpc]
		internal void SyncValuesClientRpc(int value, NetworkBehaviourReference netRef)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2537888088u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, value);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref netRef, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2537888088u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			GrabbableObject val3 = default(GrabbableObject);
			((NetworkBehaviourReference)(ref netRef)).TryGet<GrabbableObject>(ref val3, (NetworkManager)null);
			if (val3 == null)
			{
				Logger.LogError("Unable to resolve net ref for SyncValuesClientRpc!");
				return;
			}
			((Component)val3).transform.parent = GameUtils.ShipGameObject.transform;
			if (value != 0)
			{
				val3.scrapValue = value;
				val3.itemProperties.creditsWorth = value;
				((Component)val3).GetComponentInChildren<ScanNodeProperties>().subText = $"Value: ${value}";
				Logger.TryLogDebug("Successfully synced values of " + val3.itemProperties.itemName);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void UpdateSellTargetServerRpc(int newTarget, string playerName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1805328622u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, newTarget);
				bool flag = playerName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(playerName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1805328622u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				UpdateSellTargetClientRpc(newTarget, playerName);
			}
		}

		[ClientRpc]
		internal void UpdateSellTargetClientRpc(int newTarget, string playerName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3766407419u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, newTarget);
				bool flag = playerName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(playerName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3766407419u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				TargetManager.UpdateTargetClient(newTarget, playerName);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void SellAllScrapServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3299288901u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3299288901u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					SellAllScrapClientRpc();
				}
			}
		}

		[ClientRpc]
		internal void SellAllScrapClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1012720758u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1012720758u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					TargetManager.SellAllScrapClient();
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		internal void TargetSellForNetworkObjectsServerRpc(ulong[] networkObjectId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(319406093u, val, (RpcDelivery)0);
				bool flag = networkObjectId != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<ulong>(networkObjectId, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 319406093u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				TargetSellForNetworkObjectsClientRpc(networkObjectId);
			}
		}

		[ClientRpc]
		internal void TargetSellForNetworkObjectsClientRpc(ulong[] networkObjectId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1353345096u, val, (RpcDelivery)0);
				bool flag = networkObjectId != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<ulong>(networkObjectId, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1353345096u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				TargetManager.MoveNetworkObjectsToDepositDeskClient(networkObjectId);
			}
		}

		public override void OnNetworkSpawn()
		{
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2537888088u, new RpcReceiveHandler(__rpc_handler_2537888088));
			NetworkManager.__rpc_func_table.Add(1805328622u, new RpcReceiveHandler(__rpc_handler_1805328622));
			NetworkManager.__rpc_func_table.Add(3766407419u, new RpcReceiveHandler(__rpc_handler_3766407419));
			NetworkManager.__rpc_func_table.Add(3299288901u, new RpcReceiveHandler(__rpc_handler_3299288901));
			NetworkManager.__rpc_func_table.Add(1012720758u, new RpcReceiveHandler(__rpc_handler_1012720758));
			NetworkManager.__rpc_func_table.Add(319406093u, new RpcReceiv