Decompiled source of StartCreditsPlus v1.3.0

StartCreditsPlus.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using StartCreditsPlus.Patches.StartCredits;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("StartCreditsPlus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StartCreditsPlus")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b3121461-c216-47e1-be21-59b8a01cae66")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace StartCreditsPlus
{
	internal class ConfigManager
	{
		internal ConfigEntry<bool> enableStartingCredits;

		internal ConfigEntry<int> startingCredits;

		internal ConfigEntry<bool> enableRandomStartCredits;

		internal ConfigEntry<int> minRandomStartCredits;

		internal ConfigEntry<int> maxRandomStartCredits;

		internal ConfigEntry<bool> enableDynamicStartCredits;

		internal ConfigEntry<int> dynamicStartCreditIncreasePerPlayer;

		internal ConfigEntry<int> minPlayersForDynamicCredits;

		internal ConfigEntry<int> maxPlayersForDynamicCredits;

		internal ConfigEntry<int> dynamicStartCreditMinIncrease;

		internal ConfigEntry<int> dynamicStartCreditMaxIncrease;

		internal ConfigEntry<int> dynamicStartCreditAdditiveChange;

		internal ConfigEntry<float> dynamicStartCreditMultiplicativeChange;

		internal ConfigEntry<bool> resetOnFirstDayUponReHost;

		internal ConfigEntry<bool> terminalCommandsEnabled;

		internal ConfigEntry<string> terminalCommandPrefix;

		internal ConfigEntry<string> terminalCommandHelp;

		internal ConfigEntry<string> terminalCommandReload;

		internal ConfigEntry<bool> allocateStartCreditsAfterLanding;

		private const string generalSection = "General";

		private const string staticStartCreditsSection = "Static Start Credits";

		private const string dynamicStartCreditsSection = "Dynamic Start Credits";

		private const string changingDynamicStartCreditsSection = "Changing Dynamic Start Credits";

		private const string randomStartCreditsSection = "Random Start Credits";

		private const string terminalCommandsSection = "Terminal Commands";

		private const string enabledKey = "Enabled";

		private const string resetOnFirstDayUponReHostKey = "Reset on First Day Upon Re-Host";

		private const string allocateStartCreditsAfterLandingKey = "Allocate Start Credits After Landing";

		private const string startCreditsKey = "Start Credits";

		private const string startCreditIncreasePerPlayerKey = "Start Credit Increase Per Player";

		private const string minDynamicCreditPlayersKey = "Min Players";

		private const string maxDynamicCreditPlayersKey = "Max Players";

		private const string minRandomCreditsKey = "Min Additional Start Credits";

		private const string maxRandomCreditsKey = "Max Additional Start Credits";

		private const string dynamicStartCreditMinIncreaseKey = "Min Increase";

		private const string dynamicStartCreditMaxIncreaseKey = "Max Increase";

		private const string dynamicStartCreditAdditiveChangeKey = "Additive Change";

		private const string dynamicStartCreditMultiplicativeChangeKey = "Multiplicative Change";

		private const string terminalCommandPrefixKey = "Prefix For All Commands";

		private const string terminalCommandHelpKey = "Help Command Keyword";

		private const string terminalCommandReloadKey = "Reload Command Keyword";

		private readonly string staticStartCreditsEnabledDescription = "If true, \"Static Start Credits\" is applied. Turn this off if you want some other mod to manage start credits.";

		private readonly string staticStartCreditsAmountDescription = "Modifies how many credits the crew starts with.\n\nEx. \"1000\" means that you have 1000 credits when you start a new run.\n\nDynamic Start Credits are applied on top of this.\n\nEx. if this setting is 60, Dynamic Start Credits is 15 and there are 3 players, then you would start with 60 + 15 * 3 = 105 credits. \n\nBy default you start with 60 credits in vanilla Lethal Company.";

		private readonly string dynamicStartCreditsEnabledDescription = "If true, \"Dynamic Start Credits\" is applied. Turn this off if you want some other mod to manage start credits.";

		private readonly string dynamicStartCreditIncreasePerPlayerDescription = "Gives extra credits when someone joins the game for the first time and the crew hasn't landed yet.\n\nHost is included.\n\nThis is based on player count rather than WHO joins. If 2 people join, then it adds the bonus twice and until there are more than 3 people (host + 2), it won't apply the bonus again.";

		private readonly string minPlayersForDynamicCreditsDescription = "How many players have to be present in the lobby for dynamic credits to be applied.\n\nEx. 0 means that host counts and this will be applied to the host and any other who joins.\n\nEx. 2 means that 2 players other than the host would need to join before we apply the \"Start Credit Increase Per Player\" increase at all. This would also mean that the counting starts from the third player with host being ignored meaning the bonus is applied ONCE in this scenario.";

		private readonly string maxPlayersForDynamicCreditsDescription = "How many players can be in the lobby before we stop applying the \"Start Credit Increase Per Player\" increase.\n\nEx. 4 would mean that the bonus is applied 4 times, host included. If a 5th person joined, host included, then the bonus would NOT be applied.\n\n-1 Means there is no maximum cap.";

		private readonly string dynamicStartCreditMinIncreaseDescription = "Minimum start credit increase value per player.\n\nUsed for when reducing/increasing player based start credits.\n\nIf this is less than 0, the starting credits could go DOWN if too many join.";

		private readonly string dynamicStartCreditMaxIncreaseDescription = "Maximum start credit increase value per player.\n\nUsed for when reducing/increasing player based start credits.\n\n-1 means there is no maximum cap.";

		private readonly string dynamicStartCreditAdditiveChangeDescription = "When someone joins, this is added to the Dynamic Start Credits per player.\n\nThis is applied BEFORE the multiplicative change.\n\nEx. Dynamic Start Credits = 100. Additive Change = -10. Multiplicative Change = 0.5. 1 players join. First the credits are 100 for the first player, aka. host. Then the Dynamic Start Credits are applied again for the second player. (100 + (-10)) * 0.5 = 45. The next credit increase would be 45 and we would have 145 credits with host and 1 other.";

		private readonly string dynamicStartCreditMultiplicativeChangeDescription = "When someone joins, Dynamic Start Credits are multiplied by this PER PLAYER.\n\nThis is applied BEFORE the multiplicative change.\n\nEx. Dynamic Start Credits = 100. Additive Change = -10. Multiplicative Change = 0.5. 2 players join. First the credits are 100 for the first player, aka. host. Then the Dynamic Start Credits are applied again for the second player. (100 + (-10)) * 0.5 = 45. The next credit increase would be 45 and we would have 145 credits with host and 1 other. Then the Dynamic Start Credits are applied again for the third player. (45 + (-10)) * 0.5) = 17.5. Now we have 162.5 credits with host and 2 others.";

		private readonly string randomCreditsEnabledDescription = "If true, the crew will get a random amount of credits.\n\nThis will be applied IN ADDITION to any other credits like \"Static Start Credits\".\n\nIf you just want any random amount, you should set \"Static Start Credits\" to 0.\n\nEx. if \"Static Start Credits\" is 200 and this is in range of -100 to 150, then the start credits could be from 100 (200 - 100) to 350 (200 + 150).";

		private readonly string minRandomCreditsDescription = "Minimum amount of credits the crew starts with.\n\nOnly applies to random credits.";

		private readonly string maxRandomCreditsDescription = "Maximum amount of credits the crew starts with.\n\nOnly applies to random credits.";

		private readonly string resetOnFirstDayUponReHostDescription = "When you create a lobby (or get fired), you can buy items and then save and exit. When you re-host, the bought items are not saved but you have still lost the credits. This is a \"fix\" for that.\n\nIf this is enabled, you will get your start credits back if you re-host the game on your first day (day 0).\n\nThis is disabled by default because some mods still save purchases on day 0 so this setting could be \"abused\" in that sense.";

		private readonly string terminalCommandsEnabledDescription = "If any of the terminal commands from this mod are enabled. \n\nCurrent terminal commands are:\n\"reload\"\n\"help\"\n\nSpaces are NOT allowed.\n\nYou can disable individual commands by leaving them empty.";

		private readonly string terminalCommandPrefixDescription = "Every terminal command from this mod needs to have this keyword before them. Case doesn't matter.\n\nEx. if this setting is StartCreditsPlus, you can reload credits by typing \"STARTcreditsPLUS REload\" or \"StartCreditsPlus reload\", etc.\n\nYou can leave the prefix empty and still run commands but it isn't recommended due to possible overlapping commands.";

		private readonly string terminalCommandHelpDescription = "Shows all available terminal commands and their descriptions.\n\nThis is useful if you forget what a command does or if you want to see all available commands.";

		private readonly string terminalCommandReloadDescription = "Resets start credits. Removes every bought item. Only works on day 0.\n\nThis is useful is some other mod overwrites some aspect of this mod. This is a sort of manual activation of this mod's features.";

		private readonly string allocateStartCreditsAfterLandingDescription = "If true, starting credits will be allocated after landing instead of at the start.\n\nStart credits will be 0 before you land.";

		public ConfigManager()
		{
			StartCreditsPlusPlugin.logger.LogDebug((object)"Loading config...");
			ConfigFile config = ((BaseUnityPlugin)StartCreditsPlusPlugin.Instance).Config;
			resetOnFirstDayUponReHost = config.Bind<bool>("General", "Reset on First Day Upon Re-Host", false, resetOnFirstDayUponReHostDescription);
			allocateStartCreditsAfterLanding = config.Bind<bool>("General", "Allocate Start Credits After Landing", false, allocateStartCreditsAfterLandingDescription);
			enableStartingCredits = config.Bind<bool>("Static Start Credits", "Enabled", true, staticStartCreditsEnabledDescription);
			startingCredits = config.Bind<int>("Static Start Credits", "Start Credits", 60, staticStartCreditsAmountDescription);
			enableRandomStartCredits = config.Bind<bool>("Random Start Credits", "Enabled", false, randomCreditsEnabledDescription);
			minRandomStartCredits = config.Bind<int>("Random Start Credits", "Min Additional Start Credits", -60, minRandomCreditsDescription);
			maxRandomStartCredits = config.Bind<int>("Random Start Credits", "Max Additional Start Credits", 60, maxRandomCreditsDescription);
			enableDynamicStartCredits = config.Bind<bool>("Dynamic Start Credits", "Enabled", true, dynamicStartCreditsEnabledDescription);
			dynamicStartCreditIncreasePerPlayer = config.Bind<int>("Dynamic Start Credits", "Start Credit Increase Per Player", 15, dynamicStartCreditIncreasePerPlayerDescription);
			minPlayersForDynamicCredits = config.Bind<int>("Dynamic Start Credits", "Min Players", 0, minPlayersForDynamicCreditsDescription);
			maxPlayersForDynamicCredits = config.Bind<int>("Dynamic Start Credits", "Max Players", -1, maxPlayersForDynamicCreditsDescription);
			dynamicStartCreditMinIncrease = config.Bind<int>("Changing Dynamic Start Credits", "Min Increase", 0, dynamicStartCreditMinIncreaseDescription);
			dynamicStartCreditMaxIncrease = config.Bind<int>("Changing Dynamic Start Credits", "Max Increase", -1, dynamicStartCreditMaxIncreaseDescription);
			dynamicStartCreditAdditiveChange = config.Bind<int>("Changing Dynamic Start Credits", "Additive Change", -5, dynamicStartCreditAdditiveChangeDescription);
			dynamicStartCreditMultiplicativeChange = config.Bind<float>("Changing Dynamic Start Credits", "Multiplicative Change", 1f, dynamicStartCreditMultiplicativeChangeDescription);
			terminalCommandsEnabled = config.Bind<bool>("Terminal Commands", "Enabled", true, terminalCommandsEnabledDescription);
			terminalCommandPrefix = config.Bind<string>("Terminal Commands", "Prefix For All Commands", "StartCreditsPlus", terminalCommandPrefixDescription);
			terminalCommandHelp = config.Bind<string>("Terminal Commands", "Help Command Keyword", "help", terminalCommandHelpDescription);
			terminalCommandReload = config.Bind<string>("Terminal Commands", "Reload Command Keyword", "reload", terminalCommandReloadDescription);
			((BaseUnityPlugin)StartCreditsPlusPlugin.Instance).Config.SettingChanged += OnSettingChanged;
			StartCreditsPlusPlugin.logger.LogDebug((object)"Config loaded!");
		}

		private void OnSettingChanged(object sender = null, SettingChangedEventArgs args = null)
		{
			StartCreditsPlusPlugin.logger.LogDebug((object)$"Reloading a config value... [Section: {args.ChangedSetting.Definition.Section}, Value: {args.ChangedSetting.BoxedValue}]");
			if (args == null || args.ChangedSetting == null)
			{
				return;
			}
			if (args.ChangedSetting.Definition.Section == "Static Start Credits")
			{
				string key = args.ChangedSetting.Definition.Key;
				string text = key;
				if (!(text == "Enabled"))
				{
					if (text == "Start Credits")
					{
						startingCredits.Value = (int)args.ChangedSetting.BoxedValue;
					}
				}
				else
				{
					enableStartingCredits.Value = (bool)args.ChangedSetting.BoxedValue;
				}
			}
			else if (args.ChangedSetting.Definition.Section == "Dynamic Start Credits")
			{
				switch (args.ChangedSetting.Definition.Key)
				{
				case "Enabled":
					enableDynamicStartCredits.Value = (bool)args.ChangedSetting.BoxedValue;
					break;
				case "Start Credit Increase Per Player":
					dynamicStartCreditIncreasePerPlayer.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Min Players":
					minPlayersForDynamicCredits.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Max Players":
					maxPlayersForDynamicCredits.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Min Increase":
					dynamicStartCreditMinIncrease.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Max Increase":
					dynamicStartCreditMaxIncrease.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Additive Change":
					dynamicStartCreditAdditiveChange.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Multiplicative Change":
					dynamicStartCreditMultiplicativeChange.Value = (float)args.ChangedSetting.BoxedValue;
					break;
				}
			}
			else if (args.ChangedSetting.Definition.Section == "Random Start Credits")
			{
				switch (args.ChangedSetting.Definition.Key)
				{
				case "Enabled":
					enableRandomStartCredits.Value = (bool)args.ChangedSetting.BoxedValue;
					break;
				case "Min Additional Start Credits":
					minRandomStartCredits.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				case "Max Additional Start Credits":
					maxRandomStartCredits.Value = (int)args.ChangedSetting.BoxedValue;
					break;
				}
			}
			else if (args.ChangedSetting.Definition.Section == "General")
			{
				string key2 = args.ChangedSetting.Definition.Key;
				string text2 = key2;
				if (!(text2 == "Reset on First Day Upon Re-Host"))
				{
					if (text2 == "Allocate Start Credits After Landing")
					{
						allocateStartCreditsAfterLanding.Value = (bool)args.ChangedSetting.BoxedValue;
					}
				}
				else
				{
					resetOnFirstDayUponReHost.Value = (bool)args.ChangedSetting.BoxedValue;
				}
			}
			else if (args.ChangedSetting.Definition.Section == "Terminal Commands")
			{
				switch (args.ChangedSetting.Definition.Key)
				{
				case "Enabled":
					terminalCommandsEnabled.Value = (bool)args.ChangedSetting.BoxedValue;
					break;
				case "Prefix For All Commands":
					terminalCommandPrefix.Value = (string)args.ChangedSetting.BoxedValue;
					break;
				case "Help Command Keyword":
					terminalCommandHelp.Value = (string)args.ChangedSetting.BoxedValue;
					break;
				case "Reload Command Keyword":
					terminalCommandReload.Value = (string)args.ChangedSetting.BoxedValue;
					break;
				}
			}
			StartCreditsPlusPlugin.logger.LogDebug((object)"Reloading complete!");
		}
	}
	[BepInPlugin("pizzagamer777.StartCreditsPlus", "Start Credits Plus", "1.3.0")]
	public class StartCreditsPlusPlugin : BaseUnityPlugin
	{
		public const string modGUID = "pizzagamer777.StartCreditsPlus";

		private const string modName = "Start Credits Plus";

		private const string modVersion = "1.3.0";

		private readonly Harmony harmony = new Harmony("pizzagamer777.StartCreditsPlus");

		private static StartCreditsPlusPlugin _instance;

		internal static ManualLogSource logger;

		internal static ConfigManager configManager;

		internal static StartCreditsPlusPlugin Instance
		{
			get
			{
				return _instance;
			}
			set
			{
				_instance = value;
			}
		}

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("pizzagamer777.StartCreditsPlus");
			configManager = new ConfigManager();
			harmony.PatchAll(typeof(StartCreditsPlusPlugin));
			StartCredits.patch(harmony);
		}
	}
}
namespace StartCreditsPlus.Patches.StartCredits
{
	internal class TerminalCommandManager
	{
		private static string terminalMessageOverride = "";

		private static string terminalMessageAddition = "";

		public static bool canRunTerminalCommands()
		{
			if (!StartCreditsPlusPlugin.configManager.terminalCommandsEnabled.Value)
			{
				return false;
			}
			return true;
		}

		public static void handleTerminalCommand(string[] typedWords)
		{
			if (typedWords.Length == 0 || !canRunTerminalCommands())
			{
				return;
			}
			string text = StartCreditsPlusPlugin.configManager.terminalCommandPrefix.Value.ToLower();
			string text2 = typedWords[0].ToLower();
			string text3 = StartCreditsPlusPlugin.configManager.terminalCommandHelp.Value.ToLower();
			if (typedWords.Length < 2)
			{
				if (text2 == "help")
				{
					handleVanillaHelpCommand();
				}
			}
			else if (!(text != "") || !(text2 != text))
			{
				string text4 = typedWords[1].ToLower();
				string text5 = StartCreditsPlusPlugin.configManager.terminalCommandReload.Value.ToLower();
				if (text3 != "" && text4 == text3)
				{
					handleHelpCommand();
				}
				else if (text5 != "" && text4 == text5)
				{
					handleReloadCommand();
				}
			}
		}

		private static void handleReloadCommand()
		{
			StartCreditsPlusPlugin.logger.LogDebug((object)"\"reload\" command was typed...");
			if (!StartCredits.canModifyStartCredits())
			{
				terminalMessageOverride = "You are not allowed to reset start credits!";
				return;
			}
			StartCreditsPlusPlugin.logger.LogDebug((object)"Reloading start credits...");
			StartCredits.Terminal.groupCredits = TimeOfDay.Instance.quotaVariables.startingCredits;
			StartCredits.Terminal.ClearBoughtItems();
			StartCredits.Terminal.SyncGroupCreditsServerRpc(StartCredits.Terminal.groupCredits, StartCredits.Terminal.numberOfItemsInDropship);
			StartCredits.reset();
			StartCredits.calculateStartGroupCredits();
			terminalMessageOverride = "Start credits have been reset!";
		}

		private static void handleHelpCommand()
		{
			StartCreditsPlusPlugin.logger.LogDebug((object)"\"help\" command was typed...");
			string value = StartCreditsPlusPlugin.configManager.terminalCommandPrefix.Value;
			string value2 = StartCreditsPlusPlugin.configManager.terminalCommandHelp.Value;
			string value3 = StartCreditsPlusPlugin.configManager.terminalCommandReload.Value;
			terminalMessageOverride = "Available commands:\n\n>" + value + " " + value2 + "\nShows all commands\n\n>" + value + " " + value3 + "\nResets start credits and bought items";
		}

		public static void handleVanillaHelpCommand()
		{
			StartCreditsPlusPlugin.logger.LogDebug((object)"Handling vanilla help command...");
			string value = StartCreditsPlusPlugin.configManager.terminalCommandPrefix.Value;
			string value2 = StartCreditsPlusPlugin.configManager.terminalCommandHelp.Value;
			terminalMessageAddition = ">" + value + " " + value2 + "\nShows all commands from \"Start Credits Plus\"!";
		}

		public static void showPendingTerminalMessage()
		{
			string text = StartCredits.Terminal.currentText ?? "";
			bool flag = false;
			if (terminalMessageOverride != "")
			{
				text = "\n\n\n" + terminalMessageOverride;
				terminalMessageOverride = "";
				flag = true;
			}
			if (terminalMessageAddition != "")
			{
				text += terminalMessageAddition;
				terminalMessageAddition = "";
				flag = true;
			}
			if (flag)
			{
				if (!text.EndsWith("\n\n"))
				{
					text += "\n\n";
				}
				StartCredits.Terminal.currentText = text;
				StartCredits.Terminal.screenText.text = StartCredits.Terminal.currentText;
			}
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch()
		{
			StartCredits.calculateStartGroupCredits();
		}

		[HarmonyPatch("OnSubmit")]
		[HarmonyPrefix]
		private static void OnSubmitPrePatch(ref Terminal __instance)
		{
			if (TerminalCommandManager.canRunTerminalCommands())
			{
				string text = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
				MethodInfo method = typeof(Terminal).GetMethod("RemovePunctuation", BindingFlags.Instance | BindingFlags.NonPublic);
				if (method == null)
				{
					StartCreditsPlusPlugin.logger.LogError((object)"Could not find RemovePunctuation method in Terminal class! Can't run terminal commands.");
					return;
				}
				text = (string)method.Invoke(__instance, new object[1] { text });
				string[] typedWords = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
				TerminalCommandManager.handleTerminalCommand(typedWords);
			}
		}

		[HarmonyPatch("OnSubmit")]
		[HarmonyPostfix]
		private static void OnSubmitPostPatch()
		{
			if (TerminalCommandManager.canRunTerminalCommands())
			{
				TerminalCommandManager.showPendingTerminalMessage();
			}
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPostfix]
		private static void BeginUsingTerminalPatch()
		{
			if (TerminalCommandManager.canRunTerminalCommands())
			{
				TerminalCommandManager.handleVanillaHelpCommand();
				TerminalCommandManager.showPendingTerminalMessage();
			}
		}
	}
	internal class StartCredits
	{
		private static Terminal _terminal;

		private static StartMatchLever _startMatchLever;

		private static bool appliedStaticCredits = false;

		private static bool appliedRandomCredits = false;

		private static int dynamicCreditsPlayerAmount = 0;

		private static int temporaryStartCreditAmount = -1;

		public static Terminal Terminal
		{
			get
			{
				if ((Object)(object)_terminal == (Object)null)
				{
					_terminal = Object.FindObjectOfType<Terminal>();
				}
				return _terminal;
			}
			set
			{
				_terminal = value;
			}
		}

		public static StartMatchLever StartMatchLever
		{
			get
			{
				if ((Object)(object)_startMatchLever == (Object)null)
				{
					_startMatchLever = Object.FindObjectOfType<StartMatchLever>();
				}
				return _startMatchLever;
			}
			set
			{
				_startMatchLever = value;
			}
		}

		internal static void patch(Harmony harmony)
		{
			harmony.PatchAll(typeof(TerminalPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
		}

		public static void loadSaveFileConfigurations()
		{
			if (StartCreditsPlusPlugin.configManager.resetOnFirstDayUponReHost.Value)
			{
				reset();
				return;
			}
			string text = "pizzagamer777.StartCreditsPlus.dynamicCreditsPlayerAmount";
			dynamicCreditsPlayerAmount = ES3.Load<int>(text, GameNetworkManager.Instance.currentSaveFileName, 0);
			text = "pizzagamer777.StartCreditsPlus.appliedStaticCredits";
			appliedStaticCredits = ES3.Load<bool>(text, GameNetworkManager.Instance.currentSaveFileName, false);
			text = "pizzagamer777.StartCreditsPlus.appliedRandomCredits";
			appliedRandomCredits = ES3.Load<bool>(text, GameNetworkManager.Instance.currentSaveFileName, false);
			text = "pizzagamer777.StartCreditsPlus.temporaryStartCreditAmount";
			temporaryStartCreditAmount = ES3.Load<int>(text, GameNetworkManager.Instance.currentSaveFileName, -1);
		}

		private static int getAppliedDynamicCreditPlayerAmount()
		{
			return dynamicCreditsPlayerAmount;
		}

		public static bool canModifyStartCredits()
		{
			if (!GameNetworkManager.Instance.isHostingGame)
			{
				return false;
			}
			if (StartOfRound.Instance.gameStats.daysSpent != 0)
			{
				return false;
			}
			bool value = StartCreditsPlusPlugin.configManager.allocateStartCreditsAfterLanding.Value;
			bool leverHasBeenPulled = StartMatchLever.leverHasBeenPulled;
			if (value && !leverHasBeenPulled)
			{
				StartCreditsPlusPlugin.logger.LogDebug((object)"Ship hasn't landed yet. Can't modify start credits.");
				return false;
			}
			if (!StartOfRound.Instance.inShipPhase && !value)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)Terminal))
			{
				StartCreditsPlusPlugin.logger.LogWarning((object)"Terminal not found! Can't modify start credits.");
				return false;
			}
			return true;
		}

		private static bool canApplyStaticCredits()
		{
			if (!StartCreditsPlusPlugin.configManager.enableStartingCredits.Value)
			{
				return false;
			}
			return !appliedStaticCredits;
		}

		private static bool canApplyRandomCredits()
		{
			if (!StartCreditsPlusPlugin.configManager.enableRandomStartCredits.Value)
			{
				return false;
			}
			return !appliedRandomCredits;
		}

		private static bool canApplyDynamicCredits()
		{
			if (!StartCreditsPlusPlugin.configManager.enableDynamicStartCredits.Value)
			{
				return false;
			}
			int value = StartCreditsPlusPlugin.configManager.minPlayersForDynamicCredits.Value;
			int value2 = StartCreditsPlusPlugin.configManager.maxPlayersForDynamicCredits.Value;
			bool flag = value2 > -1;
			int num = Mathf.Max(0, GameNetworkManager.Instance.connectedPlayers - value);
			if (flag)
			{
				num = Mathf.Min(value2 - value, num);
			}
			if (getAppliedDynamicCreditPlayerAmount() >= num)
			{
				return false;
			}
			return true;
		}

		internal static void reset()
		{
			if (GameNetworkManager.Instance.isHostingGame)
			{
				appliedStaticCredits = false;
				appliedRandomCredits = false;
				dynamicCreditsPlayerAmount = 0;
				temporaryStartCreditAmount = -1;
				ES3.Save<bool>("pizzagamer777.StartCreditsPlus.appliedStaticCredits", appliedStaticCredits, GameNetworkManager.Instance.currentSaveFileName);
				ES3.Save<bool>("pizzagamer777.StartCreditsPlus.appliedRandomCredits", appliedRandomCredits, GameNetworkManager.Instance.currentSaveFileName);
				ES3.Save<int>("pizzagamer777.StartCreditsPlus.dynamicCreditsPlayerAmount", dynamicCreditsPlayerAmount, GameNetworkManager.Instance.currentSaveFileName);
				ES3.Save<int>("pizzagamer777.StartCreditsPlus.temporaryStartCreditAmount", temporaryStartCreditAmount, GameNetworkManager.Instance.currentSaveFileName);
			}
		}

		private static int applyStaticCredits(int _)
		{
			int value = StartCreditsPlusPlugin.configManager.startingCredits.Value;
			int result = value;
			appliedStaticCredits = true;
			ES3.Save<bool>("pizzagamer777.StartCreditsPlus.appliedStaticCredits", appliedStaticCredits, GameNetworkManager.Instance.currentSaveFileName);
			return result;
		}

		private static int applyRandomCredits(int creditsToModify)
		{
			int value = StartCreditsPlusPlugin.configManager.minRandomStartCredits.Value;
			int value2 = StartCreditsPlusPlugin.configManager.maxRandomStartCredits.Value;
			int num = Random.Range(value, value2);
			creditsToModify += num;
			appliedRandomCredits = true;
			ES3.Save<bool>("pizzagamer777.StartCreditsPlus.appliedRandomCredits", appliedRandomCredits, GameNetworkManager.Instance.currentSaveFileName);
			return creditsToModify;
		}

		private static float getNextDynamicCreditAmount(float currentAmount)
		{
			int value = StartCreditsPlusPlugin.configManager.dynamicStartCreditAdditiveChange.Value;
			float value2 = StartCreditsPlusPlugin.configManager.dynamicStartCreditMultiplicativeChange.Value;
			return (currentAmount + (float)value) * value2;
		}

		private static int applyDynamicCredits(int creditsToModify)
		{
			int value = StartCreditsPlusPlugin.configManager.dynamicStartCreditIncreasePerPlayer.Value;
			int value2 = StartCreditsPlusPlugin.configManager.minPlayersForDynamicCredits.Value;
			int value3 = StartCreditsPlusPlugin.configManager.maxPlayersForDynamicCredits.Value;
			bool flag = value3 > -1;
			int num = Mathf.Max(0, GameNetworkManager.Instance.connectedPlayers - value2);
			if (flag)
			{
				num = Mathf.Min(value3 - value2, num);
			}
			int value4 = StartCreditsPlusPlugin.configManager.dynamicStartCreditMinIncrease.Value;
			int value5 = StartCreditsPlusPlugin.configManager.dynamicStartCreditMaxIncrease.Value;
			bool flag2 = value5 != -1;
			int appliedDynamicCreditPlayerAmount = getAppliedDynamicCreditPlayerAmount();
			float num2 = value;
			StartCreditsPlusPlugin.logger.LogDebug((object)$"Applying dynamic credits to {num} players. Applied to {appliedDynamicCreditPlayerAmount} players.");
			for (int i = 1; i <= num; i++)
			{
				if (i <= appliedDynamicCreditPlayerAmount)
				{
					num2 = getNextDynamicCreditAmount(num2);
					continue;
				}
				int num3 = Mathf.RoundToInt(num2);
				num3 = Mathf.Max(value4, num3);
				if (flag2)
				{
					num3 = Mathf.Min(value5, num3);
				}
				creditsToModify += num3;
				num2 = getNextDynamicCreditAmount(num2);
			}
			dynamicCreditsPlayerAmount = appliedDynamicCreditPlayerAmount + num;
			ES3.Save<int>("pizzagamer777.StartCreditsPlus.dynamicCreditsPlayerAmount", dynamicCreditsPlayerAmount, GameNetworkManager.Instance.currentSaveFileName);
			return creditsToModify;
		}

		internal static void calculateStartGroupCredits()
		{
			if (!canModifyStartCredits())
			{
				StartCreditsPlusPlugin.logger.LogDebug((object)"Can't modify start credits. Skipping...");
				if (temporaryStartCreditAmount == -1)
				{
					temporaryStartCreditAmount = Terminal.groupCredits;
					Terminal.groupCredits = 0;
					ES3.Save<int>("pizzagamer777.StartCreditsPlus.temporaryStartCreditAmount", temporaryStartCreditAmount, GameNetworkManager.Instance.currentSaveFileName);
					StartCreditsPlusPlugin.logger.LogDebug((object)$"Stored temporary start credit amount: {temporaryStartCreditAmount}");
				}
				return;
			}
			int num = Terminal.groupCredits + Mathf.Max(0, temporaryStartCreditAmount);
			temporaryStartCreditAmount = 0;
			StartCreditsPlusPlugin.logger.LogDebug((object)$"Calculating start group credits... Current credits: {Terminal.groupCredits}");
			ES3.Save<int>("pizzagamer777.StartCreditsPlus.temporaryStartCreditAmount", temporaryStartCreditAmount, GameNetworkManager.Instance.currentSaveFileName);
			if (canApplyStaticCredits())
			{
				num = applyStaticCredits(num);
			}
			if (canApplyRandomCredits())
			{
				num = applyRandomCredits(num);
			}
			if (canApplyDynamicCredits())
			{
				num = applyDynamicCredits(num);
			}
			if (num != Terminal.groupCredits)
			{
				Terminal.SyncGroupCreditsServerRpc(num, Terminal.numberOfItemsInDropship);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch()
		{
			StartCredits.loadSaveFileConfigurations();
		}

		[HarmonyPatch("OnClientConnect")]
		[HarmonyPostfix]
		private static void OnClientConnectPatch()
		{
			StartCredits.calculateStartGroupCredits();
		}

		[HarmonyPatch("ResetShip")]
		[HarmonyPostfix]
		private static void ResetShipPatch()
		{
			StartCredits.reset();
			StartCredits.calculateStartGroupCredits();
		}

		[HarmonyPatch("StartGame")]
		[HarmonyPrefix]
		private static void StartGamePatch()
		{
			StartCredits.calculateStartGroupCredits();
		}
	}
}