Decompiled source of MoonTiers v2.0.4

BepInEx\plugins\MoonTiers\MoonTiers.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("MoonTiers")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.4.0")]
[assembly: AssemblyInformationalVersion("2.0.4")]
[assembly: AssemblyProduct("MoonTiers")]
[assembly: AssemblyTitle("MoonTiers")]
[assembly: AssemblyVersion("2.0.4.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MoonTiers
{
	public enum CountScaling
	{
		LowHigh,
		FollowInteriorSize
	}
	public enum TotalScaling
	{
		LowHigh,
		Curve
	}
	public enum CurveShape
	{
		Linear,
		Exponential
	}
	internal static class AutoScaling
	{
		private class Setup
		{
			public MoonEntry Base;

			public MoonEntry Peak;

			public SelectableLevel BaseLevel;

			public SelectableLevel PeakLevel;

			public bool TwoAnchors => Peak != null;
		}

		private const string S = "Auto Scaling";

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> BaseMoon;

		internal static ConfigEntry<string> PeakMoon;

		internal static ConfigEntry<float> Growth;

		internal static ConfigEntry<float> FullTierBonus;

		internal static ConfigEntry<float> SizePerTier;

		internal static ConfigEntry<float> MaxInteriorSize;

		internal static ConfigEntry<float> PowerPerTier;

		internal static ConfigEntry<int> PricePerTier;

		internal static ConfigEntry<int> MaxScrapCount;

		internal static ConfigEntry<bool> StayBetweenAnchors;

		internal static ConfigEntry<CountScaling> CountMode;

		internal static ConfigEntry<TotalScaling> TotalMode;

		internal static ConfigEntry<CurveShape> CountCurve;

		internal static ConfigEntry<CurveShape> TotalCurve;

		internal static ConfigEntry<int> HighMinCount;

		internal static ConfigEntry<int> HighMaxCount;

		internal static ConfigEntry<int> HighMinTotal;

		internal static ConfigEntry<int> HighMaxTotal;

		internal static ConfigEntry<bool> ScaleScrapCount;

		internal static ConfigEntry<bool> ScaleValueMultiplier;

		internal static ConfigEntry<bool> ScaleTotalValue;

		internal static ConfigEntry<bool> ScalePower;

		internal static ConfigEntry<bool> ScaleInteriorSize;

		internal static ConfigEntry<bool> ScaleRoutePrice;

		internal static bool Busy;

		private static bool dirty;

		private static string lastStatus;

		private static string lastWarning;

		internal static void Bind(ConfigFile c)
		{
			Enabled = c.Bind<bool>("Auto Scaling", "Enabled", false, "true = every moon with \"Auto Scale = true\" has its values worked out from its Tier and written into its section.\nTo hand-tune one moon, set its Auto Scale to false.");
			BaseMoon = c.Bind<string>("Auto Scaling", "Base Moon", "Experimentation", "The reference moon. Tune its section by hand; every other moon is worked out from it. It is never changed itself.\nUse the moon's name as shown in the moons config, e.g. Experimentation.");
			PeakMoon = c.Bind<string>("Auto Scaling", "Peak Moon", "", "Optional. Leave EMPTY to scale everything up from the Base Moon alone (recommended).\nSet it to a moon's name (e.g. Lua) to instead place every moon's values between the Base Moon's and that moon's hand-tuned values.");
			Growth = c.Bind<float>("Auto Scaling", "Growth Per Tier", 1.3f, "Scrap value grows by this, compounding, for every 1.00 of tier above the Base Moon (6.28 counts as 6.28). 1.3 = +30% per tier.");
			FullTierBonus = c.Bind<float>("Auto Scaling", "Full Tier Bonus", 1.25f, "Extra scrap value multiplier every time a moon reaches a new FULL tier (2.00, 3.00...). 1 = no bonus.");
			SizePerTier = c.Bind<float>("Auto Scaling", "Interior Size Per Tier", 0.2f, "One anchor only: Interior Size added per 1.00 of tier above the Base Moon (linear). 0.2 with a 1.0 base -> tier 6 = 2.0.");
			MaxInteriorSize = c.Bind<float>("Auto Scaling", "Max Interior Size", 3f, "Interior Size never goes above this. Vanilla's biggest is about 2.35.");
			CountMode = c.Bind<CountScaling>("Auto Scaling", "Scrap Count Scaling", CountScaling.FollowInteriorSize, "One anchor only.\nLowHigh            = Base Moon's Min/Max Scrap Count is the low end, High Min/Max Scrap Count below is what the HIGHEST-tier moon gets,\n                     and every moon in between climbs from low to high by tier.\nFollowInteriorSize = scrap count grows with interior size so scrap density matches the Base Moon (42-48 at 1.0 -> 84-96 at 2.0).");
			HighMinCount = c.Bind<int>("Auto Scaling", "High Min Scrap Count", 120, "LowHigh: the highest-tier moon's Min Scrap Count.");
			HighMaxCount = c.Bind<int>("Auto Scaling", "High Max Scrap Count", 139, "LowHigh: the highest-tier moon's Max Scrap Count.");
			CountCurve = c.Bind<CurveShape>("Auto Scaling", "Scrap Count Curve", CurveShape.Linear, "LowHigh: Linear = even steps per tier. Exponential = small steps low, big steps near the top (uses Growth Per Tier / Full Tier Bonus).");
			TotalMode = c.Bind<TotalScaling>("Auto Scaling", "Total Scrap Value Scaling", TotalScaling.Curve, "One anchor only, used when Scale Min/Max Total Scrap Value is on.\nCurve   = Base Moon's Min/Max Total Scrap Value x the exponential value curve (Growth Per Tier / Full Tier Bonus).\n          1000 at tier 1 -> ~29,921 at tier 8 with 1.3 / 1.25.\nLowHigh = Base Moon's total is the low end, High Min/Max Total Scrap Value is what the HIGHEST-tier moon gets, in between climbs by tier.");
			HighMinTotal = c.Bind<int>("Auto Scaling", "High Min Total Scrap Value", -1, "LowHigh: the highest-tier moon's Min Total Scrap Value. -1 = not set.");
			HighMaxTotal = c.Bind<int>("Auto Scaling", "High Max Total Scrap Value", -1, "LowHigh: the highest-tier moon's Max Total Scrap Value. -1 = not set.");
			TotalCurve = c.Bind<CurveShape>("Auto Scaling", "Total Scrap Value Curve", CurveShape.Exponential, "LowHigh: Linear = even steps per tier. Exponential = small steps low, big steps near the top (uses Growth Per Tier / Full Tier Bonus).");
			MaxScrapCount = c.Bind<int>("Auto Scaling", "Max Scrap Count", 300, "Scrap count never goes above this.");
			PowerPerTier = c.Bind<float>("Auto Scaling", "Enemy Power Per Tier", 0.25f, "One anchor only: enemy power added per 1.00 of tier, as a share of the Base Moon's (0.25 = +25% of base per tier, linear).");
			PricePerTier = c.Bind<int>("Auto Scaling", "Route Price Per Tier", 0, "One anchor only: credits added to the Base Moon's route price per 1.00 of tier. 0 = prices aren't touched.");
			StayBetweenAnchors = c.Bind<bool>("Auto Scaling", "Stay Between Anchors", true, "Two anchors only: moons outside the two tiers get the nearest anchor's values instead of going past them.");
			ScaleValueMultiplier = c.Bind<bool>("Auto Scaling", "Scale Value Multiplier", true, "Fill in each moon's Scrap Value Multiplier.\nWith Scale Min/Max Total Scrap Value on, it's locked to the totals: it shows the resulting value PER PIECE vs the Base Moon\n(total growth / extra scrap from size), and the totals do the actual work.\nWith totals off, it's the exponential curve itself and every piece rolls that much higher.");
			ScaleTotalValue = c.Bind<bool>("Auto Scaling", "Scale Min/Max Total Scrap Value", true, "Fill in each moon's Min/Max Total Scrap Value (Base Moon's total x value curve x extra scrap from size; two anchors: between the anchors' totals).\nEvery piece's value is then filled in automatically so the moon adds up to exactly that. Needs the Base Moon's Min/Max Total Scrap Value set.\nWhen a moon has a total range, the total REPLACES the multiplier's effect (pieces are rescaled to hit the total).\nTurn this off to let Scale Value Multiplier decide value; scaled moons' totals are then reset to -1.");
			ScaleScrapCount = c.Bind<bool>("Auto Scaling", "Scale Scrap Count", true, "Fill in Min/Max Scrap Count.");
			ScaleInteriorSize = c.Bind<bool>("Auto Scaling", "Scale Interior Size", true, "Fill in Interior Size.");
			ScalePower = c.Bind<bool>("Auto Scaling", "Scale Enemy Power", true, "Fill in Interior, Exterior and Daytime Power.");
			ScaleRoutePrice = c.Bind<bool>("Auto Scaling", "Scale Route Price", false, "Fill in Route Price.");
		}

		private static MoonEntry Find(string name, out SelectableLevel level)
		{
			string text = (name ?? "").Trim();
			level = null;
			if (text.Length == 0)
			{
				return null;
			}
			foreach (KeyValuePair<SelectableLevel, MoonEntry> entry in MoonManager.Entries)
			{
				if (string.Equals(entry.Value.Section, text, StringComparison.OrdinalIgnoreCase) || string.Equals(entry.Key.PlanetName, text, StringComparison.OrdinalIgnoreCase) || string.Equals(TerminalControl.ShortName(entry.Key.PlanetName), text, StringComparison.OrdinalIgnoreCase))
				{
					level = entry.Key;
					return entry.Value;
				}
			}
			return null;
		}

		private static Setup GetSetup(out string problem)
		{
			problem = null;
			if (Enabled == null || !Enabled.Value)
			{
				problem = "off (Enabled = false in [Auto Scaling])";
				return null;
			}
			SelectableLevel level;
			MoonEntry moonEntry = Find(BaseMoon.Value, out level);
			if (moonEntry == null)
			{
				problem = "waiting: no moon called \"" + BaseMoon.Value + "\" (Base Moon) has a section yet";
				return null;
			}
			if (moonEntry.Tier.Value < 0f)
			{
				problem = "not running: the Base Moon needs a Tier of 0 or more (-1 means no tier)";
				return null;
			}
			Setup setup = new Setup
			{
				Base = moonEntry,
				BaseLevel = level
			};
			if (!string.IsNullOrWhiteSpace(PeakMoon.Value))
			{
				SelectableLevel level2;
				MoonEntry moonEntry2 = Find(PeakMoon.Value, out level2);
				if (moonEntry2 == null)
				{
					problem = "waiting: no moon called \"" + PeakMoon.Value + "\" (Peak Moon) has a section yet. Empty Peak Moon to scale from the Base Moon alone";
					return null;
				}
				if ((Object)(object)level2 == (Object)(object)level || moonEntry2.Tier.Value < 0f || Mathf.Approximately(moonEntry2.Tier.Value, moonEntry.Tier.Value))
				{
					problem = "not running: the Peak Moon needs its own Tier, 0 or more and different from the Base Moon's";
					return null;
				}
				setup.Peak = moonEntry2;
				setup.PeakLevel = level2;
			}
			return setup;
		}

		internal static float ValueCurve(float tier, float baseTier)
		{
			int num = Mathf.FloorToInt(tier + 0.0001f) - Mathf.FloorToInt(baseTier + 0.0001f);
			return Mathf.Pow(Mathf.Max(0.01f, Growth.Value), tier - baseTier) * Mathf.Pow(Mathf.Max(0.01f, FullTierBonus.Value), (float)num);
		}

		internal static float LowHighProgress(float tier, float lowTier, float highTier, CurveShape shape)
		{
			if (highTier <= lowTier)
			{
				return 0f;
			}
			return Mathf.Clamp01((shape == CurveShape.Linear) ? ((tier - lowTier) / (highTier - lowTier)) : ((ValueCurve(tier, 0f) - ValueCurve(lowTier, 0f)) / (ValueCurve(highTier, 0f) - ValueCurve(lowTier, 0f))));
		}

		internal static float TopTier()
		{
			float num = 0f;
			foreach (MoonEntry value in MoonManager.Entries.Values)
			{
				if (value.Enabled.Value && value.Tier.Value > num)
				{
					num = value.Tier.Value;
				}
			}
			return num;
		}

		private static float TwoAnchorProgress(float tier, float lowTier, float highTier)
		{
			float num = (g(tier) - g(lowTier)) / (g(highTier) - g(lowTier));
			if (!StayBetweenAnchors.Value)
			{
				return num;
			}
			return Mathf.Clamp01(num);
			static float g(float t)
			{
				return ValueCurve(t, 0f);
			}
		}

		internal static void Scale(SelectableLevel level, MoonEntry e)
		{
			string problem;
			Setup setup = GetSetup(out problem);
			Report(setup, problem);
			if (setup != null && e.Enabled.Value && e.AutoScale.Value && !(e.Tier.Value <= 0f) && !((Object)(object)level == (Object)(object)setup.BaseLevel) && !((Object)(object)level == (Object)(object)setup.PeakLevel))
			{
				if (setup.TwoAnchors)
				{
					ScaleBetween(level, e, setup);
				}
				else
				{
					ScaleFromBase(level, e, setup.Base, setup.BaseLevel);
				}
			}
		}

		private static void ScaleFromBase(SelectableLevel level, MoonEntry e, MoonEntry b, SelectableLevel baseLevel)
		{
			float num = e.Tier.Value - b.Tier.Value;
			float valueCurve = ValueCurve(e.Tier.Value, b.Tier.Value);
			float value = b.InteriorSize.Value;
			if (ScaleInteriorSize.Value)
			{
				value = (float)Math.Round(Mathf.Clamp(b.InteriorSize.Value + SizePerTier.Value * num, 0.1f, MaxInteriorSize.Value), 2);
				Set(e.InteriorSize, value);
			}
			else
			{
				value = e.InteriorSize.Value;
			}
			float num2 = TopTier();
			float num3 = ((b.InteriorSize.Value > 0f) ? (value / b.InteriorSize.Value) : 1f);
			if (ScaleScrapCount.Value)
			{
				int num6;
				int num5;
				if (CountMode.Value == CountScaling.LowHigh)
				{
					float num4 = LowHighProgress(e.Tier.Value, b.Tier.Value, num2, CountCurve.Value);
					num5 = Mathf.RoundToInt(Mathf.Lerp((float)b.MinScrapCount.Value, (float)HighMinCount.Value, num4));
					num6 = Mathf.RoundToInt(Mathf.Lerp((float)b.MaxScrapCount.Value, (float)HighMaxCount.Value, num4));
					float num7 = (float)(b.MinScrapCount.Value + b.MaxScrapCount.Value) / 2f;
					num3 = ((num7 > 0f) ? ((float)(num5 + num6) / 2f / num7) : 1f);
				}
				else
				{
					num5 = Mathf.RoundToInt((float)b.MinScrapCount.Value * num3);
					num6 = Mathf.RoundToInt((float)b.MaxScrapCount.Value * num3);
				}
				num5 = Mathf.Clamp(num5, 0, MaxScrapCount.Value);
				Set(e.MinScrapCount, num5);
				Set(e.MaxScrapCount, Mathf.Clamp(num6, num5, MaxScrapCount.Value));
			}
			ApplyValue(e, b, valueCurve, num3, num2);
			if (ScalePower.Value)
			{
				float num8 = Mathf.Max(0f, 1f + PowerPerTier.Value * num);
				Set(e.InsidePower, Mathf.RoundToInt((float)b.InsidePower.Value * num8));
				Set(e.OutsidePower, Mathf.RoundToInt((float)b.OutsidePower.Value * num8));
				Set(e.DaytimePower, Mathf.RoundToInt((float)b.DaytimePower.Value * num8));
			}
			if (ScaleRoutePrice.Value && PricePerTier.Value != 0)
			{
				Set(e.RoutePrice, Math.Max(0, Mathf.RoundToInt((float)TerminalControl.BasePrice(baseLevel) + (float)PricePerTier.Value * num)));
			}
		}

		private static void ApplyValue(MoonEntry e, MoonEntry b, float valueCurve, float countFactor, float top)
		{
			if (!ScaleTotalValue.Value)
			{
				if (ScaleValueMultiplier.Value)
				{
					Set(e.ScrapValueMultiplier, (float)Math.Round(b.ScrapValueMultiplier.Value * valueCurve, 2));
				}
				Set(e.MinTotalScrapValue, -1);
				Set(e.MaxTotalScrapValue, -1);
				return;
			}
			if (b.MinTotalScrapValue.Value < 0 || b.MaxTotalScrapValue.Value < 0)
			{
				WarnOnce("Scale Min/Max Total Scrap Value is on, but the Base Moon's Min/Max Total Scrap Value are -1. Set them (e.g. 800 / 1000) to give the curve a starting total.");
				return;
			}
			int num2;
			int num3;
			float num5;
			if (TotalMode.Value == TotalScaling.LowHigh)
			{
				if (HighMinTotal.Value < 0 || HighMaxTotal.Value < 0)
				{
					WarnOnce("Total Scrap Value Scaling is LowHigh, but High Min/Max Total Scrap Value are -1. Set what the highest-tier moon should be worth.");
					return;
				}
				float num = LowHighProgress(e.Tier.Value, b.Tier.Value, top, TotalCurve.Value);
				num2 = Mathf.RoundToInt(Mathf.Lerp((float)b.MinTotalScrapValue.Value, (float)HighMinTotal.Value, num));
				num3 = Mathf.RoundToInt(Mathf.Lerp((float)b.MaxTotalScrapValue.Value, (float)HighMaxTotal.Value, num));
				float num4 = (float)(b.MinTotalScrapValue.Value + b.MaxTotalScrapValue.Value) / 2f;
				num5 = ((num4 > 0f) ? ((float)(num2 + num3) / 2f / num4) : 1f);
			}
			else
			{
				num2 = Mathf.RoundToInt((float)b.MinTotalScrapValue.Value * valueCurve);
				num3 = Mathf.RoundToInt((float)b.MaxTotalScrapValue.Value * valueCurve);
				num5 = valueCurve;
			}
			Set(e.MinTotalScrapValue, num2);
			Set(e.MaxTotalScrapValue, Math.Max(num2, num3));
			if (ScaleValueMultiplier.Value)
			{
				Set(e.ScrapValueMultiplier, (float)Math.Round(num5 / Mathf.Max(0.01f, countFactor), 2));
			}
		}

		private static void ScaleBetween(SelectableLevel level, MoonEntry e, Setup s)
		{
			bool num = s.Base.Tier.Value > s.Peak.Tier.Value;
			MoonEntry moonEntry = (num ? s.Peak : s.Base);
			MoonEntry moonEntry2 = (num ? s.Base : s.Peak);
			SelectableLevel level2 = (num ? s.PeakLevel : s.BaseLevel);
			SelectableLevel level3 = (num ? s.BaseLevel : s.PeakLevel);
			float p = TwoAnchorProgress(e.Tier.Value, moonEntry.Tier.Value, moonEntry2.Tier.Value);
			if (ScaleScrapCount.Value)
			{
				int num2 = LerpInt(moonEntry.MinScrapCount.Value, moonEntry2.MinScrapCount.Value);
				Set(e.MinScrapCount, num2);
				Set(e.MaxScrapCount, Math.Max(num2, LerpInt(moonEntry.MaxScrapCount.Value, moonEntry2.MaxScrapCount.Value)));
			}
			if (ScaleValueMultiplier.Value)
			{
				Set(e.ScrapValueMultiplier, (float)Math.Round(Math.Max(0f, Lerp(moonEntry.ScrapValueMultiplier.Value, moonEntry2.ScrapValueMultiplier.Value)), 2));
			}
			if (!ScaleTotalValue.Value)
			{
				Set(e.MinTotalScrapValue, -1);
				Set(e.MaxTotalScrapValue, -1);
			}
			else if (moonEntry.MinTotalScrapValue.Value >= 0 && moonEntry.MaxTotalScrapValue.Value >= 0 && moonEntry2.MinTotalScrapValue.Value >= 0 && moonEntry2.MaxTotalScrapValue.Value >= 0)
			{
				int num3 = LerpInt(moonEntry.MinTotalScrapValue.Value, moonEntry2.MinTotalScrapValue.Value);
				Set(e.MinTotalScrapValue, num3);
				Set(e.MaxTotalScrapValue, Math.Max(num3, LerpInt(moonEntry.MaxTotalScrapValue.Value, moonEntry2.MaxTotalScrapValue.Value)));
			}
			else
			{
				WarnOnce("Scale Min/Max Total Scrap Value is on, but the Base Moon and Peak Moon don't both have Min/Max Total Scrap Value set.");
			}
			if (ScalePower.Value)
			{
				Set(e.InsidePower, LerpInt(moonEntry.InsidePower.Value, moonEntry2.InsidePower.Value));
				Set(e.OutsidePower, LerpInt(moonEntry.OutsidePower.Value, moonEntry2.OutsidePower.Value));
				Set(e.DaytimePower, LerpInt(moonEntry.DaytimePower.Value, moonEntry2.DaytimePower.Value));
			}
			if (ScaleInteriorSize.Value)
			{
				Set(e.InteriorSize, (float)Math.Round(Math.Max(0.1f, Lerp(moonEntry.InteriorSize.Value, moonEntry2.InteriorSize.Value)), 2));
			}
			if (ScaleRoutePrice.Value)
			{
				Set(e.RoutePrice, LerpInt(TerminalControl.BasePrice(level2), TerminalControl.BasePrice(level3)));
			}
			float Lerp(float a, float b)
			{
				return a + (b - a) * p;
			}
			int LerpInt(int a, int b)
			{
				return Math.Max(0, Mathf.RoundToInt(Lerp(a, b)));
			}
		}

		internal static void ScaleAll()
		{
			foreach (KeyValuePair<SelectableLevel, MoonEntry> item in MoonManager.Entries.ToList())
			{
				Scale(item.Key, item.Value);
			}
			SaveIfChanged();
		}

		private static void Set<T>(ConfigEntry<T> entry, T value)
		{
			if (!object.Equals(entry.Value, value))
			{
				Busy = true;
				try
				{
					entry.Value = value;
				}
				finally
				{
					Busy = false;
				}
				dirty = true;
			}
		}

		internal static void SaveIfChanged()
		{
			if (dirty)
			{
				dirty = false;
				MoonManager.MoonConfig.Save();
				Plugin.Log.LogInfo((object)"Auto Scaling: updated moon values written to MoonTiers.Moons.cfg.");
			}
		}

		private static void WarnOnce(string msg)
		{
			if (!(msg == lastWarning))
			{
				lastWarning = msg;
				Plugin.Log.LogWarning((object)("Auto Scaling: " + msg));
			}
		}

		private static void Report(Setup s, string problem)
		{
			string text = ((problem != null) ? ("Auto Scaling " + problem + ".") : (s.TwoAnchors ? string.Format("Auto Scaling active: between {0} (tier {1:0.00}) and {2} (tier {3:0.00}), value multiplier {4}, total value {5}.", s.Base.Section, s.Base.Tier.Value, s.Peak.Section, s.Peak.Tier.Value, ScaleValueMultiplier.Value ? "on" : "off", ScaleTotalValue.Value ? "on" : "off") : string.Format("Auto Scaling active: from {0} (tier {1:0.00}) upward, value multiplier {2}, total value {3}.", s.Base.Section, s.Base.Tier.Value, ScaleValueMultiplier.Value ? "on" : "off", ScaleTotalValue.Value ? "on" : "off")));
			if (!(text == lastStatus))
			{
				lastStatus = text;
				if (problem == null || problem.StartsWith("off"))
				{
					Plugin.Log.LogInfo((object)text);
				}
				else
				{
					Plugin.Log.LogWarning((object)text);
				}
			}
		}

		internal static void LogCurve()
		{
			string problem;
			Setup setup = GetSetup(out problem);
			if (setup == null || setup.TwoAnchors)
			{
				return;
			}
			MoonEntry b = setup.Base;
			float top = TopTier();
			IEnumerable<string> values = (from t in Enumerable.Range(1, 8).Select((Func<int, float>)((int t) => t))
				where t < top
				select t).Concat(new float[1] { top }).Distinct().Select(delegate(float t)
			{
				float num = t - b.Tier.Value;
				float num2 = Mathf.Clamp(b.InteriorSize.Value + SizePerTier.Value * num, 0.1f, MaxInteriorSize.Value);
				string text;
				if (CountMode.Value == CountScaling.LowHigh)
				{
					float num3 = LowHighProgress(t, b.Tier.Value, top, CountCurve.Value);
					text = $"{Mathf.RoundToInt(Mathf.Lerp((float)b.MinScrapCount.Value, (float)HighMinCount.Value, num3))}-{Mathf.RoundToInt(Mathf.Lerp((float)b.MaxScrapCount.Value, (float)HighMaxCount.Value, num3))}";
				}
				else
				{
					float num4 = ((b.InteriorSize.Value > 0f) ? (num2 / b.InteriorSize.Value) : 1f);
					text = $"{Mathf.RoundToInt((float)b.MinScrapCount.Value * num4)}-{Mathf.RoundToInt((float)b.MaxScrapCount.Value * num4)}";
				}
				string text2 = "";
				if (ScaleTotalValue.Value && TotalMode.Value == TotalScaling.Curve && b.MinTotalScrapValue.Value >= 0)
				{
					float num5 = ValueCurve(t, b.Tier.Value);
					float num6 = ((b.InteriorSize.Value > 0f) ? (num2 / b.InteriorSize.Value) : 1f);
					text2 = $", total {Mathf.RoundToInt((float)b.MinTotalScrapValue.Value * num5)}-{Mathf.RoundToInt((float)b.MaxTotalScrapValue.Value * num5)} (x{num5 / Mathf.Max(0.01f, num6):0.##} per piece)";
				}
				else if (ScaleTotalValue.Value && TotalMode.Value == TotalScaling.LowHigh && HighMinTotal.Value >= 0 && b.MinTotalScrapValue.Value >= 0)
				{
					float num7 = LowHighProgress(t, b.Tier.Value, top, TotalCurve.Value);
					text2 = $", total {Mathf.RoundToInt(Mathf.Lerp((float)b.MinTotalScrapValue.Value, (float)HighMinTotal.Value, num7))}-{Mathf.RoundToInt(Mathf.Lerp((float)b.MaxTotalScrapValue.Value, (float)HighMaxTotal.Value, num7))}";
				}
				return $"T{t:0.00}: value x{ValueCurve(t, b.Tier.Value):0.##}, size {num2:0.##}, scrap {text}{text2}";
			});
			Plugin.Log.LogInfo((object)($"Auto Scaling preview (highest tier {top:0.00}):\n  " + string.Join("\n  ", values)));
		}
	}
	internal static class CompatPatches
	{
		private static bool warned;

		private static void DarmuhMoonsPlus_GetPrice(object __instance, ref int __result)
		{
			try
			{
				int num = TerminalControl.OverridePrice(Traverse.Create(__instance).Field("Level").GetValue<SelectableLevel>());
				if (num >= 0)
				{
					__result = num;
				}
			}
			catch (Exception ex)
			{
				if (!warned)
				{
					Plugin.Log.LogWarning((object)("MoonsPlus price compatibility failed: " + ex.Message));
				}
				warned = true;
			}
		}
	}
	internal static class Hooks
	{
		private static Harmony harmony;

		private static int ok;

		private static int failed;

		internal static readonly List<string> Failed = new List<string>();

		internal static void ApplyAll()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			harmony = new Harmony("staymotivatedjosh.MoonTiers");
			Patch(typeof(MenuManager), "Start", typeof(Patches), null, "MenuManager_Start");
			Patch(typeof(StartOfRound), "Start", typeof(Patches), null, "StartOfRound_Start");
			Patch(typeof(StartOfRound), "ChangeLevel", typeof(Patches), null, "StartOfRound_ChangeLevel");
			Patch(typeof(RoundManager), "LoadNewLevel", typeof(Patches), "RoundManager_LoadNewLevel");
			Patch(typeof(RoundManager), "GenerateNewFloor", typeof(Patches), "RoundManager_GenerateNewFloor");
			Patch(typeof(RoundManager), "SpawnScrapInLevel", typeof(Patches), "RoundManager_SpawnScrapInLevel", "RoundManager_SpawnScrapInLevel_Post");
			Patch(typeof(RoundManager), "SyncScrapValuesClientRpc", typeof(Patches), "RoundManager_SyncScrapValues");
			Patch(typeof(Terminal), "Start", typeof(TerminalPatches), null, "Terminal_Start");
			Patch(typeof(Terminal), "LoadNewNode", typeof(TerminalPatches), "Terminal_LoadNewNode", null, runLast: true);
			Patch(typeof(Terminal), "LoadNewNodeIfAffordable", typeof(TerminalPatches), "Terminal_LoadNewNodeIfAffordable", null, runLast: true);
			Patch(typeof(Terminal), "TextPostProcess", typeof(TerminalPatches), "Terminal_TextPostProcess_Pre", "Terminal_TextPostProcess");
			Patch(typeof(StartOfRound), "Start", typeof(PurchasePatches), null, "StartOfRound_Start");
			Patch(typeof(StartOfRound), "ChangeLevelClientRpc", typeof(PurchasePatches), null, "ChangeLevelClientRpc");
			Patch(typeof(StartOfRound), "ChangeLevelServerRpc", typeof(PurchasePatches), "ChangeLevelServerRpc");
			Patch(typeof(StartOfRound), "ResetShip", typeof(PurchasePatches), null, "ResetShip");
			Patch(typeof(GameNetworkManager), "ResetSavedGameValues", typeof(PurchasePatches), null, "ResetSavedGameValues");
			Patch(typeof(GameNetworkManager), "SaveGame", typeof(PurchasePatches), null, "SaveGame");
			PatchOptional("TerminalStuff.MoonsTweaks.MoonInfo", "GetPrice", typeof(CompatPatches), "DarmuhMoonsPlus_GetPrice", "darmuh's MoonsPlus (prices)");
			if (failed == 0)
			{
				Plugin.Log.LogInfo((object)$"All {ok} game hooks applied.");
			}
			else
			{
				Plugin.Log.LogError((object)string.Format("{0} game hooks applied, {1} FAILED: {2}. Paste this log to get it fixed.", ok, failed, string.Join(", ", Failed)));
			}
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private static void Patch(Type target, string method, Type patchClass, string prefix = null, string postfix = null, bool runLast = false)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			string text = target.Name + "." + method;
			try
			{
				MethodInfo methodInfo = AccessTools.Method(target, method, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					throw new MissingMethodException(target.Name, method);
				}
				HarmonyMethod val = ((prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(RequireMethod(patchClass, prefix)));
				if (val != null && runLast)
				{
					val.priority = 0;
				}
				HarmonyMethod val2 = ((postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(RequireMethod(patchClass, postfix)));
				harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ok++;
			}
			catch (Exception ex)
			{
				failed++;
				Failed.Add(text);
				Plugin.Log.LogError((object)("Couldn't hook " + text + ": " + ex.GetType().Name + ": " + ex.Message));
			}
		}

		private static void PatchOptional(string typeName, string method, Type patchClass, string postfix, string label)
		{
			Type type = AccessTools.TypeByName(typeName);
			if (!(type == null))
			{
				Patch(type, method, patchClass, null, postfix);
				if (!Failed.Contains(type.Name + "." + method))
				{
					Plugin.Log.LogInfo((object)("Compatibility enabled: " + label + "."));
				}
			}
		}

		private static MethodInfo RequireMethod(Type type, string name)
		{
			return AccessTools.Method(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.Name, name);
		}

		private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			try
			{
				MoonManager.RegisterLoadedLevels();
				if ((Object)(object)StartOfRound.Instance != (Object)null)
				{
					MoonManager.RegisterAll(StartOfRound.Instance.levels);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Moon scan after loading scene \"{((Scene)(ref scene)).name}\" failed: {arg}");
			}
		}
	}
	internal static class LLL
	{
		private static bool initDone;

		private static PropertyInfo extendedLevelsProp;

		private static MemberInfo selectableMember;

		private static PropertyInfo routePriceProp;

		private static readonly Dictionary<SelectableLevel, int> Original = new Dictionary<SelectableLevel, int>();

		private static bool warned;

		internal static bool Present
		{
			get
			{
				Init();
				if (extendedLevelsProp != null && routePriceProp != null)
				{
					return selectableMember != null;
				}
				return false;
			}
		}

		private static void Init()
		{
			if (initDone)
			{
				return;
			}
			initDone = true;
			try
			{
				Type type = AccessTools.TypeByName("LethalLevelLoader.PatchedContent");
				Type type2 = AccessTools.TypeByName("LethalLevelLoader.ExtendedLevel");
				if (!(type == null) && !(type2 == null))
				{
					extendedLevelsProp = AccessTools.Property(type, "ExtendedLevels");
					routePriceProp = AccessTools.Property(type2, "RoutePrice");
					selectableMember = (MemberInfo)(((object)AccessTools.Field(type2, "SelectableLevel")) ?? ((object)AccessTools.Property(type2, "SelectableLevel")));
					if (Present)
					{
						Plugin.Log.LogInfo((object)"LethalLevelLoader found: route prices will be set through it as well.");
					}
					else
					{
						Plugin.Log.LogWarning((object)"LethalLevelLoader found, but its price settings couldn't be located; prices are only set on the terminal pages.");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("LethalLevelLoader support disabled: " + ex.Message));
			}
		}

		private static IEnumerable<(object ext, SelectableLevel level)> All()
		{
			if (!Present)
			{
				yield break;
			}
			IEnumerable enumerable = null;
			try
			{
				enumerable = extendedLevelsProp.GetValue(null) as IEnumerable;
			}
			catch
			{
			}
			if (enumerable == null)
			{
				yield break;
			}
			foreach (object item in enumerable)
			{
				if (item != null)
				{
					SelectableLevel val = null;
					try
					{
						val = (SelectableLevel)((selectableMember is FieldInfo fieldInfo) ? /*isinst with value type is only supported in some contexts*/: /*isinst with value type is only supported in some contexts*/);
					}
					catch
					{
					}
					if ((Object)(object)val != (Object)null)
					{
						yield return (ext: item, level: val);
					}
				}
			}
		}

		private static object Find(SelectableLevel level)
		{
			foreach (var item in All())
			{
				var (result, _) = item;
				if ((Object)(object)item.level == (Object)(object)level)
				{
					return result;
				}
			}
			return null;
		}

		internal static bool TryOriginalPrice(SelectableLevel level, out int price)
		{
			price = 0;
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (Original.TryGetValue(level, out price))
			{
				return true;
			}
			object obj = Find(level);
			if (obj == null)
			{
				return false;
			}
			try
			{
				price = (int)routePriceProp.GetValue(obj);
			}
			catch
			{
				return false;
			}
			Original[level] = price;
			return true;
		}

		internal static void SetPrice(SelectableLevel level, int price)
		{
			object obj = Find(level);
			if (obj == null)
			{
				return;
			}
			try
			{
				if (!Original.ContainsKey(level))
				{
					Original[level] = (int)routePriceProp.GetValue(obj);
				}
				if ((int)routePriceProp.GetValue(obj) != price)
				{
					routePriceProp.SetValue(obj, price);
				}
			}
			catch (Exception ex)
			{
				if (!warned)
				{
					Plugin.Log.LogWarning((object)("Couldn't set a LethalLevelLoader route price: " + ex.Message));
				}
				warned = true;
			}
		}
	}
	internal class MoonEntry
	{
		public string Section;

		public ConfigEntry<bool> Enabled;

		public ConfigEntry<float> Tier;

		public ConfigEntry<int> MinScrapCount;

		public ConfigEntry<int> MaxScrapCount;

		public ConfigEntry<float> ScrapValueMultiplier;

		public ConfigEntry<int> MinTotalScrapValue;

		public ConfigEntry<int> MaxTotalScrapValue;

		public ConfigEntry<float> InteriorSize;

		public ConfigEntry<int> InsidePower;

		public ConfigEntry<int> OutsidePower;

		public ConfigEntry<int> DaytimePower;

		public ConfigEntry<string> Interiors;

		public ConfigEntry<string> InsideEnemies;

		public ConfigEntry<string> OutsideEnemies;

		public ConfigEntry<string> DaytimeEnemies;

		public ConfigEntry<string> ScrapItems;

		public ConfigEntry<bool> Hidden;

		public ConfigEntry<bool> Locked;

		public ConfigEntry<int> RoutePrice;

		public ConfigEntry<MoonPurchaseMode> PurchaseMode;

		public ConfigEntry<bool> AutoScale;
	}
	internal class VanillaSnapshot
	{
		public string RiskLevel;

		public int MinScrap;

		public int MaxScrap;

		public int MinTotal;

		public int MaxTotal;

		public float Size;

		public int InsidePower;

		public int OutsidePower;

		public int DaytimePower;

		public List<SpawnableEnemyWithRarity> Inside;

		public List<SpawnableEnemyWithRarity> Outside;

		public List<SpawnableEnemyWithRarity> Daytime;

		public List<SpawnableItemWithRarity> Scrap;

		public IntWithRarity[] Flows;
	}
	internal static class MoonManager
	{
		internal static ConfigFile MoonConfig;

		private static readonly Dictionary<SelectableLevel, VanillaSnapshot> Snapshots = new Dictionary<SelectableLevel, VanillaSnapshot>();

		internal static readonly Dictionary<SelectableLevel, MoonEntry> Entries = new Dictionary<SelectableLevel, MoonEntry>();

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

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

		private static readonly Dictionary<string, string> FriendlyInteriorNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			{ "Level1Flow", "Facility" },
			{ "Level2Flow", "Mansion" },
			{ "Level3Flow", "Mineshaft" }
		};

		private static bool reloading;

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

		internal static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			MoonConfig = new ConfigFile(Path.Combine(Paths.ConfigPath, "MoonTiers.Moons.cfg"), true);
			MoonConfig.SaveOnConfigSet = false;
			MoonConfig.SettingChanged += delegate
			{
				if (reloading || AutoScaling.Busy)
				{
					return;
				}
				try
				{
					MoonConfig.Save();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Couldn't save MoonTiers.Moons.cfg: " + ex.Message));
				}
			};
		}

		internal static void Reload()
		{
			try
			{
				reloading = true;
				MoonConfig.Reload();
				((BaseUnityPlugin)Plugin.Instance).Config.Reload();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Couldn't reload config (is there a typo in the file?): " + ex.Message));
			}
			finally
			{
				reloading = false;
			}
			ApplyAllTiers();
		}

		internal static void ApplyTier(SelectableLevel level)
		{
			if (!((Object)(object)level == (Object)null) && Entries.TryGetValue(level, out var value) && Snapshots.TryGetValue(level, out var value2))
			{
				string text = ((value.Enabled.Value && value.Tier.Value >= 0f) ? FormatTier(value.Tier.Value) : value2.RiskLevel);
				if (!(level.riskLevel == text))
				{
					level.riskLevel = text;
					RefreshShipScreen(level);
				}
			}
		}

		internal static void ApplyAllTiers()
		{
			foreach (SelectableLevel item in Entries.Keys.ToList())
			{
				ApplyTier(item);
			}
		}

		private static void RefreshShipScreen(SelectableLevel level)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.currentLevel != (Object)(object)level) && instance.inShipPhase)
				{
					AccessTools.Method(typeof(StartOfRound), "SetMapScreenInfoToCurrentLevel", (Type[])null, (Type[])null)?.Invoke(instance, null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("Couldn't refresh the ship screen: " + ex.Message));
			}
		}

		internal static void RegisterAll(IEnumerable<SelectableLevel> levels)
		{
			if (levels == null)
			{
				return;
			}
			List<SelectableLevel> list = levels.Where((SelectableLevel l) => (Object)(object)l != (Object)null).Distinct().ToList();
			List<string> fresh = (from l in list
				where !Entries.ContainsKey(l)
				select l.PlanetName).ToList();
			if (fresh.Count > 0)
			{
				Plugin.Log.LogInfo((object)string.Format("Moon scan found {0} moon(s); new: {1}", list.Count, string.Join(", ", fresh)));
			}
			bool flag = false;
			foreach (SelectableLevel item in list)
			{
				try
				{
					flag |= Register(item, save: false);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)string.Format("Couldn't create a config section for \"{0}\": {1}", ((Object)(object)item != (Object)null) ? item.PlanetName : "null", arg));
				}
			}
			if (!flag)
			{
				return;
			}
			MoonConfig.Save();
			WriteReferenceFile();
			Plugin.Log.LogInfo((object)$"MoonTiers.Moons.cfg now has {Entries.Values.Select((MoonEntry e) => e.Section).Distinct().Count()} moon section(s).");
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			if (StartOfRound.Instance.inShipPhase)
			{
				ApplyAll();
			}
			else
			{
				foreach (SelectableLevel item2 in list.Where((SelectableLevel l) => fresh.Contains(l.PlanetName)))
				{
					Apply(item2, saveScaling: false);
				}
				AutoScaling.SaveIfChanged();
			}
			TerminalControl.ApplyPrices();
		}

		internal static void RefreshAllInOrbit()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.inShipPhase)
			{
				if (Plugin.ReloadOnRoute.Value)
				{
					Reload();
				}
				RegisterAll(instance.levels);
				ApplyAll();
				TerminalControl.ApplyPrices();
			}
		}

		internal static void RegisterLoadedLevels()
		{
			try
			{
				List<SelectableLevel> levels = (from l in Resources.FindObjectsOfTypeAll<SelectableLevel>()
					where (Object)(object)l != (Object)null && !string.IsNullOrWhiteSpace(l.PlanetName)
					select l).ToList();
				int count = Entries.Count;
				RegisterAll(levels);
				if (Entries.Count > count)
				{
					Plugin.Log.LogInfo((object)$"Added {Entries.Count - count} new moon section(s) to MoonTiers.Moons.cfg.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Moon scan failed, will retry when the ship loads: " + ex.Message));
			}
		}

		internal static bool Register(SelectableLevel level, bool save = true)
		{
			if ((Object)(object)level == (Object)null || Entries.ContainsKey(level))
			{
				return false;
			}
			VanillaSnapshot vanillaSnapshot = TakeSnapshot(level);
			Snapshots[level] = vanillaSnapshot;
			IndexContent(vanillaSnapshot);
			string text = UniqueSection(level);
			MoonEntry moonEntry = new MoonEntry
			{
				Section = text
			};
			List<string> interiorNames = GetInteriorNames();
			moonEntry.Enabled = MoonConfig.Bind<bool>(text, "Enabled", true, "false = this moon uses its normal vanilla/modded values and none of the settings below.");
			moonEntry.Tier = MoonConfig.Bind<float>(text, "Tier", DefaultTier(vanillaSnapshot.RiskLevel), "YOUR rating of how worth it this moon is, shown in place of the Hazard Level letter (e.g. 6.28).\nIt is never calculated from the settings below; it only changes when you change it. The starting value is just the old letter converted (Safe=0, D=1 ... S+++=8).\n0 shows as 0.00. -1 (any negative number) = show the original text (\"" + vanillaSnapshot.RiskLevel + "\") instead.");
			moonEntry.MinScrapCount = MoonConfig.Bind<int>(text, "Min Scrap Count", vanillaSnapshot.MinScrap, "Fewest pieces of scrap that spawn inside.");
			moonEntry.MaxScrapCount = MoonConfig.Bind<int>(text, "Max Scrap Count", Math.Max(vanillaSnapshot.MinScrap, vanillaSnapshot.MaxScrap - 1), "Most pieces of scrap that spawn inside (inclusive).");
			moonEntry.ScrapValueMultiplier = MoonConfig.Bind<float>(text, "Scrap Value Multiplier", 1f, "Multiplies the value of every piece of scrap on this moon. 1 = normal, 1.5 = +50%, 0.75 = -25%.\nIf Min/Max Total Scrap Value are set (not -1), pieces are filled in to hit that total instead and this is just for reference.");
			moonEntry.MinTotalScrapValue = MoonConfig.Bind<int>(text, "Min Total Scrap Value", -1, "Lowest total value of all the scrap on the moon. Individual pieces are rescaled to hit a random total between Min and Max.\n-1 on either Min or Max = vanilla value rolls (no rescaling). Apparatus and hives are not counted.");
			moonEntry.MaxTotalScrapValue = MoonConfig.Bind<int>(text, "Max Total Scrap Value", -1, "Highest total value of all the scrap on the moon. -1 = vanilla.");
			moonEntry.InteriorSize = MoonConfig.Bind<float>(text, "Interior Size", vanillaSnapshot.Size, "Interior size multiplier. Vanilla moons range from about 1.0 to 2.35.");
			moonEntry.InsidePower = MoonConfig.Bind<int>(text, "Interior Power", vanillaSnapshot.InsidePower, "Max power level of enemies inside (each enemy costs power; higher = more/harder enemies).");
			moonEntry.OutsidePower = MoonConfig.Bind<int>(text, "Exterior Power", vanillaSnapshot.OutsidePower, "Max power level of nighttime outside enemies.");
			moonEntry.DaytimePower = MoonConfig.Bind<int>(text, "Daytime Power", vanillaSnapshot.DaytimePower, "Max power level of daytime enemies (bees, manticoils, locusts...).");
			moonEntry.Interiors = MoonConfig.Bind<string>(text, "Interiors", SerializeFlows(vanillaSnapshot.Flows, interiorNames), "Which interiors can spawn and how likely. Format  Name:Weight, Name:Weight\nWeights are relative (Facility:300, Mansion:100 = 75%/25%). 0 = never. See MoonTiers_Reference.txt for names.");
			moonEntry.InsideEnemies = MoonConfig.Bind<string>(text, "Inside Enemies", SerializeEnemies(vanillaSnapshot.Inside), "Enemies that spawn inside. Format  EnemyName:Rarity, EnemyName:Rarity  (higher rarity = more common, 0 = never).\nDelete an entry to remove that enemy; add any enemy from MoonTiers_Reference.txt, including modded ones.");
			moonEntry.OutsideEnemies = MoonConfig.Bind<string>(text, "Outside Enemies", SerializeEnemies(vanillaSnapshot.Outside), "Nighttime outside enemies. Same format as Inside Enemies.");
			moonEntry.DaytimeEnemies = MoonConfig.Bind<string>(text, "Daytime Enemies", SerializeEnemies(vanillaSnapshot.Daytime), "Daytime enemies. Same format as Inside Enemies.");
			moonEntry.ScrapItems = MoonConfig.Bind<string>(text, "Scrap Items", SerializeItems(vanillaSnapshot.Scrap), "Which scrap items can spawn and how common. Format  ItemName:Rarity. Leave as-is if you don't care.");
			moonEntry.Hidden = MoonConfig.Bind<bool>(text, "Hidden", false, "true = left out of the terminal's MOONS list. You can still route to it by typing its name (unless it's also Locked).");
			moonEntry.Locked = MoonConfig.Bind<bool>(text, "Locked", false, "true = the terminal refuses to route here. It still shows in the list, marked locked (unless it's also Hidden).");
			moonEntry.RoutePrice = MoonConfig.Bind<int>(text, "Route Price", -1, "Credits it costs to route here. -1 = the moon's normal price, 0 = free.");
			moonEntry.PurchaseMode = MoonConfig.Bind<MoonPurchaseMode>(text, "Purchase Mode", MoonPurchaseMode.Default, "Default = use the Purchase Mode in the general config. Vanilla = pay every trip. Permanent = pay once, free for the rest of the run.");
			moonEntry.AutoScale = MoonConfig.Bind<bool>(text, "Auto Scale", true, "Only matters when Auto Scaling is turned on in the general config.\ntrue = this moon's scrap, power, size (and optionally price) are worked out from its Tier (see [Auto Scaling] in the general config) and written into this section.\nfalse = keep the values you typed here by hand.");
			Entries[level] = moonEntry;
			Plugin.Log.LogInfo((object)("Registered moon \"" + level.PlanetName + "\" as [" + text + "]."));
			ApplyTier(level);
			moonEntry.Tier.SettingChanged += delegate
			{
				ApplyTier(level);
			};
			moonEntry.Enabled.SettingChanged += delegate
			{
				ApplyTier(level);
			};
			if (save)
			{
				MoonConfig.Save();
				WriteReferenceFile();
			}
			return true;
		}

		private static VanillaSnapshot TakeSnapshot(SelectableLevel l)
		{
			return new VanillaSnapshot
			{
				RiskLevel = l.riskLevel,
				MinScrap = l.minScrap,
				MaxScrap = l.maxScrap,
				MinTotal = l.minTotalScrapValue,
				MaxTotal = l.maxTotalScrapValue,
				Size = l.factorySizeMultiplier,
				InsidePower = l.maxEnemyPowerCount,
				OutsidePower = l.maxOutsideEnemyPowerCount,
				DaytimePower = l.maxDaytimeEnemyPowerCount,
				Inside = ((l.Enemies != null) ? new List<SpawnableEnemyWithRarity>(l.Enemies) : new List<SpawnableEnemyWithRarity>()),
				Outside = ((l.OutsideEnemies != null) ? new List<SpawnableEnemyWithRarity>(l.OutsideEnemies) : new List<SpawnableEnemyWithRarity>()),
				Daytime = ((l.DaytimeEnemies != null) ? new List<SpawnableEnemyWithRarity>(l.DaytimeEnemies) : new List<SpawnableEnemyWithRarity>()),
				Scrap = ((l.spawnableScrap != null) ? new List<SpawnableItemWithRarity>(l.spawnableScrap) : new List<SpawnableItemWithRarity>()),
				Flows = (IntWithRarity[])((l.dungeonFlowTypes != null) ? ((Array)(IntWithRarity[])l.dungeonFlowTypes.Clone()) : ((Array)new IntWithRarity[0]))
			};
		}

		private static void IndexContent(VanillaSnapshot s)
		{
			foreach (SpawnableEnemyWithRarity item in s.Inside.Concat(s.Outside).Concat(s.Daytime))
			{
				AddEnemy(item?.enemyType);
			}
			foreach (SpawnableItemWithRarity item2 in s.Scrap)
			{
				AddItem(item2?.spawnableItem);
			}
		}

		private static void IndexAllLoadedAssets()
		{
			EnemyType[] array = Resources.FindObjectsOfTypeAll<EnemyType>();
			for (int i = 0; i < array.Length; i++)
			{
				AddEnemy(array[i]);
			}
			Item[] array2 = Resources.FindObjectsOfTypeAll<Item>();
			foreach (Item val in array2)
			{
				if ((Object)(object)val != (Object)null && val.isScrap)
				{
					AddItem(val);
				}
			}
		}

		private static void AddEnemy(EnemyType t)
		{
			try
			{
				AddEnemyUnsafe(t);
			}
			catch
			{
			}
		}

		private static void AddItem(Item i)
		{
			try
			{
				AddItemUnsafe(i);
			}
			catch
			{
			}
		}

		private static void AddEnemyUnsafe(EnemyType t)
		{
			if (!((Object)(object)t == (Object)null))
			{
				if (!string.IsNullOrWhiteSpace(t.enemyName) && !EnemyLookup.ContainsKey(t.enemyName.Trim()))
				{
					EnemyLookup[t.enemyName.Trim()] = t;
				}
				if (!string.IsNullOrWhiteSpace(((Object)t).name) && !EnemyLookup.ContainsKey(((Object)t).name))
				{
					EnemyLookup[((Object)t).name] = t;
				}
			}
		}

		private static void AddItemUnsafe(Item i)
		{
			if (!((Object)(object)i == (Object)null))
			{
				if (!string.IsNullOrWhiteSpace(i.itemName) && !ItemLookup.ContainsKey(i.itemName.Trim()))
				{
					ItemLookup[i.itemName.Trim()] = i;
				}
				if (!string.IsNullOrWhiteSpace(((Object)i).name) && !ItemLookup.ContainsKey(((Object)i).name))
				{
					ItemLookup[((Object)i).name] = i;
				}
			}
		}

		internal static void ApplyAll()
		{
			foreach (SelectableLevel item in Entries.Keys.ToList())
			{
				Apply(item, saveScaling: false);
			}
			AutoScaling.SaveIfChanged();
		}

		internal static void Apply(SelectableLevel level)
		{
			Apply(level, saveScaling: true);
		}

		internal static void Apply(SelectableLevel level, bool saveScaling)
		{
			if ((Object)(object)level == (Object)null)
			{
				return;
			}
			Register(level);
			MoonEntry moonEntry = Entries[level];
			VanillaSnapshot vanillaSnapshot = Snapshots[level];
			AutoScaling.Scale(level, moonEntry);
			if (saveScaling)
			{
				AutoScaling.SaveIfChanged();
			}
			if (!moonEntry.Enabled.Value)
			{
				Restore(level, vanillaSnapshot);
				MoonTiersAPI.Raise(level);
				return;
			}
			try
			{
				ApplyTier(level);
				int num = Math.Max(0, moonEntry.MinScrapCount.Value);
				int num2 = Math.Max(num, moonEntry.MaxScrapCount.Value);
				level.minScrap = num;
				level.maxScrap = num2 + 1;
				level.factorySizeMultiplier = Mathf.Max(0.1f, moonEntry.InteriorSize.Value);
				level.maxEnemyPowerCount = Math.Max(0, moonEntry.InsidePower.Value);
				level.maxOutsideEnemyPowerCount = Math.Max(0, moonEntry.OutsidePower.Value);
				level.maxDaytimeEnemyPowerCount = Math.Max(0, moonEntry.DaytimePower.Value);
				level.Enemies = BuildEnemies(moonEntry.InsideEnemies.Value, level.PlanetName, "InsideEnemies");
				level.OutsideEnemies = BuildEnemies(moonEntry.OutsideEnemies.Value, level.PlanetName, "OutsideEnemies");
				level.DaytimeEnemies = BuildEnemies(moonEntry.DaytimeEnemies.Value, level.PlanetName, "DaytimeEnemies");
				IntWithRarity[] array = BuildFlows(moonEntry.Interiors.Value, level.PlanetName);
				level.dungeonFlowTypes = ((array.Length != 0 && array.Any((IntWithRarity f) => f.rarity > 0)) ? array : vanillaSnapshot.Flows);
				List<SpawnableItemWithRarity> list = BuildItems(moonEntry.ScrapItems.Value, level.PlanetName);
				level.spawnableScrap = ((list.Count > 0 && list.Any((SpawnableItemWithRarity s) => s.rarity > 0)) ? list : new List<SpawnableItemWithRarity>(vanillaSnapshot.Scrap));
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[{moonEntry.Section}] failed to apply, using original values: {arg}");
				Restore(level, vanillaSnapshot);
				ApplyTier(level);
			}
			MoonTiersAPI.Raise(level);
		}

		private static void Restore(SelectableLevel l, VanillaSnapshot s)
		{
			l.riskLevel = s.RiskLevel;
			l.minScrap = s.MinScrap;
			l.maxScrap = s.MaxScrap;
			l.minTotalScrapValue = s.MinTotal;
			l.maxTotalScrapValue = s.MaxTotal;
			l.factorySizeMultiplier = s.Size;
			l.maxEnemyPowerCount = s.InsidePower;
			l.maxOutsideEnemyPowerCount = s.OutsidePower;
			l.maxDaytimeEnemyPowerCount = s.DaytimePower;
			l.Enemies = new List<SpawnableEnemyWithRarity>(s.Inside);
			l.OutsideEnemies = new List<SpawnableEnemyWithRarity>(s.Outside);
			l.DaytimeEnemies = new List<SpawnableEnemyWithRarity>(s.Daytime);
			l.spawnableScrap = new List<SpawnableItemWithRarity>(s.Scrap);
			l.dungeonFlowTypes = s.Flows;
		}

		internal static string FormatTier(float tier)
		{
			try
			{
				return string.Format(CultureInfo.InvariantCulture, Plugin.TierFormat.Value, tier);
			}
			catch (FormatException)
			{
				return tier.ToString("0.00", CultureInfo.InvariantCulture);
			}
		}

		private static List<(string Name, int Weight)> ParseList(string text, string moon, string key)
		{
			List<(string, int)> list = new List<(string, int)>();
			if (string.IsNullOrWhiteSpace(text))
			{
				return list;
			}
			string[] array = text.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length != 0)
				{
					int num = text2.LastIndexOf(':');
					if (num <= 0 || !int.TryParse(text2.Substring(num + 1).Trim(), out var result))
					{
						Plugin.Log.LogWarning((object)("[" + moon + "] " + key + ": couldn't read \"" + text2 + "\" — expected Name:Number. Skipped."));
					}
					else
					{
						list.Add((text2.Substring(0, num).Trim(), Math.Max(0, result)));
					}
				}
			}
			return list;
		}

		private static List<SpawnableEnemyWithRarity> BuildEnemies(string text, string moon, string key)
		{
			List<SpawnableEnemyWithRarity> list = new List<SpawnableEnemyWithRarity>();
			foreach (var (text2, rarity) in ParseList(text, moon, key))
			{
				if (!EnemyLookup.TryGetValue(text2, out var value))
				{
					IndexAllLoadedAssets();
					if (!EnemyLookup.TryGetValue(text2, out value))
					{
						Plugin.Log.LogWarning((object)("[" + moon + "] " + key + ": no enemy called \"" + text2 + "\". Check MoonTiers_Reference.txt. Skipped."));
						continue;
					}
				}
				SpawnableEnemyWithRarity val = AccessTools.CreateInstance<SpawnableEnemyWithRarity>();
				val.enemyType = value;
				val.rarity = rarity;
				list.Add(val);
			}
			return list;
		}

		private static List<SpawnableItemWithRarity> BuildItems(string text, string moon)
		{
			List<SpawnableItemWithRarity> list = new List<SpawnableItemWithRarity>();
			foreach (var (text2, rarity) in ParseList(text, moon, "ScrapItems"))
			{
				if (!ItemLookup.TryGetValue(text2, out var value))
				{
					IndexAllLoadedAssets();
					if (!ItemLookup.TryGetValue(text2, out value))
					{
						Plugin.Log.LogWarning((object)("[" + moon + "] ScrapItems: no scrap item called \"" + text2 + "\". Skipped."));
						continue;
					}
				}
				SpawnableItemWithRarity val = AccessTools.CreateInstance<SpawnableItemWithRarity>();
				val.spawnableItem = value;
				val.rarity = rarity;
				list.Add(val);
			}
			return list;
		}

		private static IntWithRarity[] BuildFlows(string text, string moon)
		{
			List<string> interiorNames = GetInteriorNames();
			List<IntWithRarity> list = new List<IntWithRarity>();
			foreach (var item3 in ParseList(text, moon, "Interiors"))
			{
				string item = item3.Name;
				int item2 = item3.Weight;
				int num = ResolveInterior(item, interiorNames);
				if (num < 0)
				{
					Plugin.Log.LogWarning((object)("[" + moon + "] Interiors: no interior called \"" + item + "\". Check MoonTiers_Reference.txt. Skipped."));
				}
				else
				{
					IntWithRarity val = AccessTools.CreateInstance<IntWithRarity>();
					val.id = num;
					val.rarity = item2;
					list.Add(val);
				}
			}
			if (list.Count == 0 || list.All((IntWithRarity f) => f.rarity <= 0))
			{
				Plugin.Log.LogWarning((object)("[" + moon + "] Interiors: nothing usable listed, keeping the moon's original interiors."));
			}
			return list.ToArray();
		}

		private static int ResolveInterior(string name, List<string> names)
		{
			if (name.StartsWith("#") && int.TryParse(name.Substring(1), out var result))
			{
				return result;
			}
			if (int.TryParse(name, out result))
			{
				return result;
			}
			if (names == null)
			{
				return -1;
			}
			for (int i = 0; i < names.Count; i++)
			{
				if (string.Equals(names[i], name, StringComparison.OrdinalIgnoreCase))
				{
					return i;
				}
				if (FriendlyInteriorNames.TryGetValue(names[i], out var value) && string.Equals(value, name, StringComparison.OrdinalIgnoreCase))
				{
					return i;
				}
			}
			return -1;
		}

		internal static List<string> GetInteriorNames()
		{
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return new List<string> { "Level1Flow", "Level2Flow", "Level3Flow" };
			}
			if (!(AccessTools.Field(typeof(RoundManager), "dungeonFlowTypes")?.GetValue(instance) is Array array))
			{
				return null;
			}
			List<string> list = new List<string>();
			for (int i = 0; i < array.Length; i++)
			{
				object value = array.GetValue(i);
				Object val = (Object)((value is Object) ? value : null);
				if (val == (Object)null && value != null)
				{
					object? obj = AccessTools.Field(value.GetType(), "dungeonFlow")?.GetValue(value);
					val = (Object)((obj is Object) ? obj : null);
				}
				list.Add((val != (Object)null) ? val.name : ("#" + i));
			}
			return list;
		}

		private static string InteriorDisplayName(int id, List<string> names)
		{
			if (names == null || id < 0 || id >= names.Count)
			{
				return "#" + id;
			}
			if (!FriendlyInteriorNames.TryGetValue(names[id], out var value))
			{
				return names[id];
			}
			return value;
		}

		private static string SerializeEnemies(IEnumerable<SpawnableEnemyWithRarity> list)
		{
			return string.Join(", ", from e in list
				where (Object)(object)e?.enemyType != (Object)null
				select $"{Clean(e.enemyType.enemyName)}:{e.rarity}");
		}

		private static string SerializeItems(IEnumerable<SpawnableItemWithRarity> list)
		{
			List<string> list2 = new List<string>();
			foreach (SpawnableItemWithRarity item in list)
			{
				try
				{
					if ((Object)(object)item?.spawnableItem != (Object)null && !string.IsNullOrWhiteSpace(item.spawnableItem.itemName))
					{
						list2.Add($"{Clean(item.spawnableItem.itemName)}:{item.rarity}");
					}
				}
				catch
				{
				}
			}
			return string.Join(", ", list2);
		}

		private static string SerializeFlows(IEnumerable<IntWithRarity> flows, List<string> names)
		{
			return string.Join(", ", from f in flows
				where f != null
				select $"{InteriorDisplayName(f.id, names)}:{f.rarity}");
		}

		private static string Clean(string s)
		{
			return (s ?? "").Replace(",", "").Replace("\n", " ").Trim();
		}

		private static float DefaultTier(string risk)
		{
			return (risk ?? "").Trim().ToUpperInvariant() switch
			{
				"D" => 1f, 
				"C" => 2f, 
				"B" => 3f, 
				"A" => 4f, 
				"S" => 5f, 
				"S+" => 6f, 
				"S++" => 7f, 
				"S+++" => 8f, 
				"SAFE" => 0f, 
				_ => -1f, 
			};
		}

		private static string UniqueSection(SelectableLevel level)
		{
			string text = CleanSection(level.PlanetName);
			string text2 = CleanSection(TerminalControl.ShortName(level.PlanetName));
			string[] array = new string[3]
			{
				text2,
				text,
				text + " (" + ((Object)level).name + ")"
			};
			foreach (string text3 in array)
			{
				if (!string.IsNullOrWhiteSpace(text3) && (!SectionOwner.TryGetValue(text3, out var value) || (Object)(object)value == (Object)(object)level))
				{
					SectionOwner[text3] = level;
					return text3;
				}
			}
			return text + " " + ((Object)level).GetInstanceID();
		}

		private static string CleanSection(string planetName)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = planetName ?? "Unknown";
			foreach (char value in text)
			{
				if ("[]=\n\t\r\"'\\".IndexOf(value) < 0)
				{
					stringBuilder.Append(value);
				}
			}
			string text2 = stringBuilder.ToString().Trim();
			if (text2.Length != 0)
			{
				return text2;
			}
			return "Unknown";
		}

		internal static void WriteReferenceFile()
		{
			if (!Plugin.WriteReferenceFile.Value)
			{
				return;
			}
			try
			{
				IndexAllLoadedAssets();
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("MoonTiers reference — names you can use in MoonTiers.Moons.cfg (regenerated every launch).");
				stringBuilder.AppendLine();
				stringBuilder.AppendLine("=== INTERIORS (use the name, or #number) ===");
				List<string> interiorNames = GetInteriorNames();
				if (interiorNames != null)
				{
					for (int i = 0; i < interiorNames.Count; i++)
					{
						stringBuilder.AppendLine($"#{i}  {InteriorDisplayName(i, interiorNames)}" + ((InteriorDisplayName(i, interiorNames) != interiorNames[i]) ? ("  (also: " + interiorNames[i] + ")") : ""));
					}
				}
				stringBuilder.AppendLine();
				stringBuilder.AppendLine("=== ENEMIES (name used in config | in-game type) ===");
				foreach (EnemyType item in from t in EnemyLookup.Values.Distinct()
					orderby t.enemyName
					select t)
				{
					string text = (item.isDaytimeEnemy ? "daytime" : (item.isOutsideEnemy ? "outside" : "inside"));
					stringBuilder.AppendLine($"{Clean(item.enemyName),-28} | {text}, power {item.PowerLevel}, max {item.MaxCount}");
				}
				stringBuilder.AppendLine();
				stringBuilder.AppendLine("=== SCRAP ITEMS (name | raw value range before the game's x0.4) ===");
				foreach (Item item2 in from val in ItemLookup.Values.Distinct()
					orderby val.itemName
					select val)
				{
					stringBuilder.AppendLine($"{Clean(item2.itemName),-28} | {item2.minValue}-{item2.maxValue}");
				}
				File.WriteAllText(Path.Combine(Paths.ConfigPath, "MoonTiers_Reference.txt"), stringBuilder.ToString());
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't write reference file: " + ex.Message));
			}
		}
	}
	public static class MoonTiersAPI
	{
		public static event Action<SelectableLevel, float> OnMoonApplied;

		public static float GetTier(SelectableLevel level)
		{
			if ((Object)(object)level == (Object)null || !MoonManager.Entries.TryGetValue(level, out var value) || !value.Enabled.Value)
			{
				return -1f;
			}
			return value.Tier.Value;
		}

		public static float GetTier(string planetName)
		{
			return GetTier(((IEnumerable<SelectableLevel>)MoonManager.Entries.Keys).FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel l) => string.Equals(l.PlanetName, planetName, StringComparison.OrdinalIgnoreCase))));
		}

		public static IReadOnlyDictionary<SelectableLevel, float> GetAllTiers()
		{
			return MoonManager.Entries.Keys.ToDictionary((SelectableLevel l) => l, GetTier);
		}

		public static float GetCurrentTier()
		{
			return GetTier(((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.currentLevel : null);
		}

		public static bool IsLocked(SelectableLevel level)
		{
			return TerminalControl.IsLocked(level);
		}

		public static bool IsHidden(SelectableLevel level)
		{
			return TerminalControl.IsHidden(level);
		}

		public static void SetLocked(SelectableLevel level, bool? locked)
		{
			if (!((Object)(object)level == (Object)null))
			{
				if (locked.HasValue)
				{
					TerminalControl.LockOverride[level] = locked.Value;
				}
				else
				{
					TerminalControl.LockOverride.Remove(level);
				}
			}
		}

		public static void SetHidden(SelectableLevel level, bool? hidden)
		{
			if (!((Object)(object)level == (Object)null))
			{
				if (hidden.HasValue)
				{
					TerminalControl.HiddenOverride[level] = hidden.Value;
				}
				else
				{
					TerminalControl.HiddenOverride.Remove(level);
				}
			}
		}

		internal static void Raise(SelectableLevel level)
		{
			try
			{
				MoonTiersAPI.OnMoonApplied?.Invoke(level, GetTier(level));
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"An OnMoonApplied listener threw: {arg}");
			}
		}
	}
	internal static class Patches
	{
		private static void MenuManager_Start()
		{
			MoonManager.RegisterLoadedLevels();
		}

		private static void StartOfRound_Start(StartOfRound __instance)
		{
			MoonManager.RegisterAll(__instance.levels);
			MoonManager.RegisterLoadedLevels();
			MoonManager.WriteReferenceFile();
			MoonManager.ApplyAll();
			AutoScaling.LogCurve();
			TerminalControl.ApplyPrices();
		}

		private static void StartOfRound_ChangeLevel(StartOfRound __instance)
		{
			if (Plugin.ReloadOnRoute.Value)
			{
				MoonManager.Reload();
			}
			MoonManager.Apply(__instance.currentLevel);
		}

		private static void RoundManager_LoadNewLevel(object[] __args)
		{
			SelectableLevel? level = __args?.OfType<SelectableLevel>().FirstOrDefault();
			if (Plugin.ReloadOnRoute.Value)
			{
				MoonManager.Reload();
			}
			MoonManager.Apply(level);
		}

		private static void RoundManager_GenerateNewFloor(RoundManager __instance)
		{
			MoonManager.Apply(__instance.currentLevel);
		}

		private static void RoundManager_SpawnScrapInLevel(RoundManager __instance)
		{
			ScrapValueControl.Arm(__instance);
		}

		private static void RoundManager_SpawnScrapInLevel_Post(RoundManager __instance)
		{
			ScrapValueControl.Disarm(__instance);
		}

		private static void RoundManager_SyncScrapValues(object[] __args)
		{
			int[] array = __args?.OfType<int[]>().FirstOrDefault();
			NetworkObjectReference[] refs = __args?.OfType<NetworkObjectReference[]>().FirstOrDefault();
			if (array != null)
			{
				ScrapValueControl.OnValuesSent(array, refs);
			}
		}
	}
	internal static class ScrapValueControl
	{
		private static bool armed;

		private static bool totalArmed;

		private static int pendingTarget = -1;

		private static string pendingMoon;

		private static float pendingMult = 1f;

		private static bool resending;

		internal static void Arm(RoundManager rm)
		{
			armed = (totalArmed = false);
			pendingTarget = -1;
			pendingMult = 1f;
			SelectableLevel val = (((Object)(object)rm != (Object)null) ? rm.currentLevel : null);
			pendingMoon = (((Object)(object)val != (Object)null) ? val.PlanetName : "?");
			if ((Object)(object)val == (Object)null || !MoonManager.Entries.TryGetValue(val, out var value))
			{
				Plugin.Log.LogWarning((object)("[" + pendingMoon + "] Scrap is spawning but this moon has no MoonTiers section; scrap value left alone."));
			}
			else
			{
				if (!value.Enabled.Value)
				{
					return;
				}
				pendingMult = Math.Max(0f, value.ScrapValueMultiplier.Value);
				int value2 = value.MinTotalScrapValue.Value;
				int num = value.MaxTotalScrapValue.Value;
				if (value2 >= 0 && num >= 0)
				{
					if (num < value2)
					{
						num = value2;
					}
					pendingTarget = Random.Range(value2, num + 1);
					totalArmed = true;
				}
				armed = true;
				Plugin.Log.LogInfo((object)($"[{pendingMoon}] Spawning scrap: count {val.minScrap}-{val.maxScrap - 1}, value x{pendingMult:0.##}" + (totalArmed ? $", total target {pendingTarget} ({value2}-{num})." : ", no total range.")));
			}
		}

		internal static void Disarm(RoundManager rm)
		{
		}

		internal static void OnValuesSent(int[] values, NetworkObjectReference[] refs)
		{
			if (values == null || values.Length == 0)
			{
				return;
			}
			long num = ((IEnumerable<int>)values).Sum((Func<int, long>)((int v) => v));
			if (!armed)
			{
				if (!resending)
				{
					Plugin.Log.LogInfo((object)$"[{pendingMoon}] Scrap received: {values.Length} pieces worth {num} total.");
				}
				return;
			}
			armed = false;
			try
			{
				ApplyAndVerify(values, refs, num);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[{pendingMoon}] Scrap value step failed: {arg}");
			}
		}

		private static void ApplyAndVerify(int[] values, NetworkObjectReference[] refs, long rolled)
		{
			if (!totalArmed && Math.Abs(pendingMult - 1f) > 0.0001f)
			{
				for (int i = 0; i < values.Length; i++)
				{
					values[i] = Math.Max(1, (int)Math.Round((float)values[i] * pendingMult));
				}
				Plugin.Log.LogInfo((object)$"[{pendingMoon}] Scrap value x{pendingMult:0.##}: {values.Length} pieces, {rolled} -> {((IEnumerable<int>)values).Sum((Func<int, long>)((int v) => v))}.");
			}
			if (totalArmed)
			{
				Rescale(values);
			}
			if (refs != null && refs.Length == values.Length)
			{
				int[] array = (int[])values.Clone();
				SetOnObjects(refs, array);
				RoundManager instance = RoundManager.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					((MonoBehaviour)instance).StartCoroutine(VerifyLater(instance, refs, array, pendingMoon));
				}
			}
		}

		private static void SetOnObjects(NetworkObjectReference[] refs, int[] values)
		{
			NetworkObject val = default(NetworkObject);
			for (int i = 0; i < refs.Length; i++)
			{
				if (((NetworkObjectReference)(ref refs[i])).TryGet(ref val, (NetworkManager)null) && !((Object)(object)val == (Object)null))
				{
					GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
					if ((Object)(object)component != (Object)null && component.scrapValue != values[i])
					{
						component.SetScrapValue(values[i]);
					}
				}
			}
		}

		private static long ActualTotal(NetworkObjectReference[] refs, out int found, out int differ, int[] wanted)
		{
			long num = 0L;
			found = 0;
			differ = 0;
			NetworkObject val = default(NetworkObject);
			for (int i = 0; i < refs.Length; i++)
			{
				if (!((NetworkObjectReference)(ref refs[i])).TryGet(ref val, (NetworkManager)null) || (Object)(object)val == (Object)null)
				{
					continue;
				}
				GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
				if (!((Object)(object)component == (Object)null))
				{
					found++;
					num += component.scrapValue;
					if (component.scrapValue != wanted[i])
					{
						differ++;
					}
				}
			}
			return num;
		}

		private static IEnumerator VerifyLater(RoundManager rm, NetworkObjectReference[] refs, int[] wanted, string moon)
		{
			long expected = ((IEnumerable<int>)wanted).Sum((Func<int, long>)((int v) => v));
			for (int attempt = 1; attempt <= 2; attempt++)
			{
				yield return (object)new WaitForSeconds(4f);
				int found;
				int differ;
				long num = ActualTotal(refs, out found, out differ, wanted);
				if (differ == 0)
				{
					Plugin.Log.LogInfo((object)$"[{moon}] Scrap check: {found} pieces worth {num} total, as set.");
					break;
				}
				Plugin.Log.LogWarning((object)($"[{moon}] Scrap check {attempt}: {differ} of {found} pieces were changed after MoonTiers set them " + $"(now worth {num}, should be {expected}). Another mod is overwriting scrap values; setting them again."));
				SetOnObjects(refs, wanted);
				try
				{
					resending = true;
					rm.SyncScrapValuesClientRpc(refs, (int[])wanted.Clone());
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("[" + moon + "] Couldn't resend scrap values: " + ex.Message));
				}
				finally
				{
					resending = false;
				}
			}
		}

		internal static void Rescale(int[] values)
		{
			if (!totalArmed)
			{
				return;
			}
			totalArmed = false;
			if (values.Length == 0)
			{
				return;
			}
			int num = pendingTarget;
			long num2 = ((IEnumerable<int>)values).Sum((Func<int, long>)((int v) => v));
			if (num2 <= 0)
			{
				return;
			}
			double num3 = (double)num / (double)num2;
			int num4 = 0;
			long num5 = 0L;
			for (int num6 = 0; num6 < values.Length; num6++)
			{
				values[num6] = Math.Max(1, (int)Math.Round((double)values[num6] * num3));
				num5 += values[num6];
				if (values[num6] > values[num4])
				{
					num4 = num6;
				}
			}
			values[num4] = Math.Max(1, values[num4] + (int)(num - num5));
			Plugin.Log.LogInfo((object)$"[{pendingMoon}] Filled scrap total: {values.Length} pieces, rolled {num2} -> {values.Sum()} (target {num}), about {values.Sum() / values.Length} each.");
		}
	}
	public enum PurchaseMode
	{
		Vanilla,
		Permanent
	}
	public enum MoonPurchaseMode
	{
		Default,
		Vanilla,
		Permanent
	}
	[BepInPlugin("staymotivatedjosh.MoonTiers", "MoonTiers", "2.0.4")]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "staymotivatedjosh.MoonTiers";

		public const string NAME = "MoonTiers";

		public const string VERSION = "2.0.4";

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<string> TierFormat;

		internal static ConfigEntry<bool> ReloadOnRoute;

		internal static ConfigEntry<bool> WriteReferenceFile;

		internal static ConfigEntry<string> LockedMessage;

		internal static ConfigEntry<string> LockedTag;

		internal static ConfigEntry<PurchaseMode> DefaultPurchaseMode;

		internal static ConfigEntry<string> OwnedTag;

		private static void WarnAboutPriceMods()
		{
			try
			{
				string[] known = new string[5] { "LethalMoonUnlocks", "Lethal Moon Unlocks", "Custom Moon Prices", "MoonsPlus", "Moons Plus" };
				List<string> list = (from p in Chainloader.PluginInfos.Values
					select p.Metadata.Name into n
					where known.Any((string k) => string.Equals(n, k, StringComparison.OrdinalIgnoreCase))
					select n).Distinct().ToList();
				if (list.Count > 0)
				{
					Log.LogWarning((object)("These mods also control moon prices and override MoonTiers' Route Price (and Hidden/Locked/Purchase Mode): " + string.Join(", ", list) + ". Set prices in one place only."));
				}
			}
			catch
			{
			}
		}

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			TierFormat = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Tier Format", "{0:0.00}", "How the tier is shown where the Hazard Level letter used to be. {0} is the tier number.\nExamples: \"{0:0.00}\" -> 6.28 | \"Tier {0:0.00}\" -> Tier 6.28 | \"{0:0.0}\" -> 6.3");
			ReloadOnRoute = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Reload Config On Route", true, "Re-read this file every time you route to / land on a moon, so you can tweak values mid-session without restarting.");
			WriteReferenceFile = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Write Reference File", true, "Writes BepInEx/config/MoonTiers_Reference.txt listing every enemy name and interior name you can use below (includes modded ones).");
			LockedMessage = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Locked Message", "{0} is locked. Unlock a higher tier to travel here.", "Terminal message when someone tries to route to a locked moon. {0} is the moon's name.");
			LockedTag = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Locked Tag", "[LOCKED]", "Added after a locked moon's name in the MOONS list. Leave empty to show nothing.");
			DefaultPurchaseMode = ((BaseUnityPlugin)this).Config.Bind<PurchaseMode>("General", "Purchase Mode", PurchaseMode.Vanilla, "How paid moons work for every moon whose own Purchase Mode is Default.\nVanilla   = you pay every time you route there (the trip is only 'free' while you're already orbiting it).\nPermanent = pay once, then routing there is free for the rest of the run (until you get fired). Saved with your save file.");
			OwnedTag = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Owned Tag", "[OWNED]", "Added after a permanently purchased moon's name in the MOONS list. Leave empty to show nothing.");
			AutoScaling.Bind(((BaseUnityPlugin)this).Config);
			MoonManager.Init();
			Hooks.ApplyAll();
			Log.LogInfo((object)"MoonTiers 2.0.4 loaded.");
			WarnAboutPriceMods();
		}
	}
	internal static class PurchaseTracker
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnSyncReceived;
		}

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

			public static HandleNamedMessageDelegate <>9__6_0;

			internal void <OnShipLoaded>b__6_0(ulong sender, FastBufferReader reader)
			{
				SendTo(sender);
			}
		}

		private const string SaveKey = "MoonTiers_PurchasedMoons";

		private const string MsgSync = "MoonTiers_PurchasedSync";

		private const string MsgRequest = "MoonTiers_PurchasedRequest";

		internal static readonly HashSet<string> Purchased = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static string SaveFile
		{
			get
			{
				if (!((Object)(object)GameNetworkManager.Instance != (Object)null))
				{
					return null;
				}
				return GameNetworkManager.Instance.currentSaveFileName;
			}
		}

		internal static bool IsPermanent(SelectableLevel level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (MoonManager.Entries.TryGetValue(level, out var value) && value.Enabled.Value && value.PurchaseMode.Value != MoonPurchaseMode.Default)
			{
				return value.PurchaseMode.Value == MoonPurchaseMode.Permanent;
			}
			return Plugin.DefaultPurchaseMode.Value == PurchaseMode.Permanent;
		}

		internal static bool IsOwned(SelectableLevel level)
		{
			if ((Object)(object)level != (Object)null && IsPermanent(level))
			{
				return Purchased.Contains(level.PlanetName);
			}
			return false;
		}

		internal unsafe static void OnShipLoaded()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			Purchased.Clear();
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			if (singleton.IsServer)
			{
				Load();
				CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
				object obj = <>c.<>9__6_0;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = delegate(ulong sender, FastBufferReader reader)
					{
						SendTo(sender);
					};
					<>c.<>9__6_0 = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("MoonTiers_PurchasedRequest", (HandleNamedMessageDelegate)obj);
			}
			else
			{
				CustomMessagingManager customMessagingManager2 = singleton.CustomMessagingManager;
				object obj2 = <>O.<0>__OnSyncReceived;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnSyncReceived;
					<>O.<0>__OnSyncReceived = val2;
					obj2 = (object)val2;
				}
				customMessagingManager2.RegisterNamedMessageHandler("MoonTiers_PurchasedSync", (HandleNamedMessageDelegate)obj2);
				FastBufferWriter val3 = default(FastBufferWriter);
				((FastBufferWriter)(ref val3))..ctor(4, (Allocator)2, -1);
				try
				{
					byte b = 1;
					((FastBufferWriter)(ref val3)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					singleton.CustomMessagingManager.SendNamedMessage("MoonTiers_PurchasedRequest", 0uL, val3, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val3))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			TerminalControl.ApplyPrices();
		}

		internal static void OnRouted(int levelID)
		{
			SelectableLevel val = StartOfRound.Instance?.levels?.FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel l) => (Object)(object)l != (Object)null && l.levelID == levelID));
			if (!((Object)(object)val == (Object)null) && IsPermanent(val) && TerminalControl.BasePrice(val) > 0 && Purchased.Add(val.PlanetName))
			{
				Plugin.Log.LogInfo((object)(val.PlanetName + " purchased permanently for this run."));
				TerminalControl.ApplyPrices();
			}
		}

		internal static void RefundIfOwned(int levelID, ref int newGroupCredits)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			SelectableLevel val = StartOfRound.Instance?.levels?.FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel l) => (Object)(object)l != (Object)null && l.levelID == levelID));
			if (IsOwned(val))
			{
				Terminal val2 = Object.FindObjectOfType<Terminal>();
				if ((Object)(object)val2 != (Object)null && newGroupCredits < val2.groupCredits)
				{
					Plugin.Log.LogInfo((object)$"{val.PlanetName} is already owned; refunding {val2.groupCredits - newGroupCredits} credits.");
					newGroupCredits = val2.groupCredits;
				}
			}
		}

		internal static void ResetRun()
		{
			if (Purchased.Count > 0)
			{
				Plugin.Log.LogInfo((object)"Run over, permanent moon purchases cleared.");
			}
			Purchased.Clear();
			TerminalControl.ApplyPrices();
		}

		private static void Load()
		{
			try
			{
				if (string.IsNullOrEmpty(SaveFile) || !ES3.KeyExists("MoonTiers_PurchasedMoons", SaveFile))
				{
					return;
				}
				string[] array = ES3.Load<string>("MoonTiers_PurchasedMoons", SaveFile, "").Split('\n');
				foreach (string text in array)
				{
					if (!string.IsNullOrWhiteSpace(text))
					{
						Purchased.Add(text.Trim());
					}
				}
				Plugin.Log.LogInfo((object)$"Loaded {Purchased.Count} permanently purchased moon(s) from the save.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't load purchased moons: " + ex.Message));
			}
		}

		internal static void Save()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || string.IsNullOrEmpty(SaveFile))
			{
				return;
			}
			try
			{
				ES3.Save<string>("MoonTiers_PurchasedMoons", string.Join("\n", Purchased), SaveFile);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't save purchased moons: " + ex.Message));
			}
		}

		internal static void DeleteSave()
		{
			try
			{
				if (!string.IsNullOrEmpty(SaveFile))
				{
					ES3.DeleteKey("MoonTiers_PurchasedMoons", SaveFile);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't clear purchased moons: " + ex.Message));
			}
		}

		private unsafe static void SendTo(ulong clientId)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			string text = string.Join("\n", Purchased);
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(8 + text.Length * 2, (Allocator)2, 65536);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(text, false);
				singleton.CustomMessagingManager.SendNamedMessage("MoonTiers_PurchasedSync", clientId, val, (NetworkDelivery)4);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnSyncReceived(ulong sender, FastBufferReader reader)
		{
			string text = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
			Purchased.Clear();
			string[] array = (text ?? "").Split('\n');
			foreach (string text2 in array)
			{
				if (!string.IsNullOrWhiteSpace(text2))
				{
					Purchased.Add(text2.Trim());
				}
			}
			TerminalControl.ApplyPrices();
			Plugin.Log.LogInfo((object)$"Received {Purchased.Count} permanently purchased moon(s) from the host.");
		}
	}
	internal static class PurchasePatches
	{
		private static void StartOfRound_Start()
		{
			PurchaseTracker.OnShipLoaded();
		}

		private static void ChangeLevelClientRpc(object[] __args)
		{
			if (__args != null && __args.Length != 0 && __args[0] is int levelID)
			{
				PurchaseTracker.OnRouted(levelID);
			}
		}

		private static void ChangeLevelServerRpc(object[] __args)
		{
			if (__args != null && __args.Length >= 2 && __args[0] is int levelID && __args[1] is int newGroupCredits)
			{
				PurchaseTracker.RefundIfOwned(levelID, ref newGroupCredits);
				__args[1] = newGroupCredits;
			}
		}

		private static void ResetShip()
		{
			PurchaseTracker.ResetRun();
		}

		private static void ResetSavedGameValues()
		{
			PurchaseTracker.DeleteSave();
		}

		private static void SaveGame()
		{
			PurchaseTracker.Save();
		}
	}
	internal static class TerminalControl
	{
		private static TerminalNode moonsListNode;

		private static TerminalNode lockedNode;

		private static readonly Dictionary<TerminalNode, int> OriginalCost = new Dictionary<TerminalNode, int>();

		private static readonly Dictionary<TerminalNode, SelectableLevel> NodeLevel = new Dictionary<TerminalNode, SelectableLevel>();

		internal static readonly Dictionary<SelectableLevel, bool> LockOverride = new Dictionary<SelectableLevel, bool>();

		internal static readonly Dictionary<SelectableLevel, bool> HiddenOverride = new Dictionary<SelectableLevel, bool>();

		private static Terminal terminalRef;

		private static string lastPriceReport;

		internal static void Setup(Terminal terminal)
		{
			terminalRef = terminal;
			Discover();
			ApplyPrices();
			Plugin.Log.LogInfo((object)($"Terminal hooked: {NodeLevel.Count / 2} routable moons" + (LLL.Present ? " (LethalLevelLoader prices synced too)." : ".")));
		}

		internal static void Discover()
		{
			if ((Object)(object)terminalRef == (Object)null)
			{
				terminalRef = Object.FindObjectOfType<Terminal>();
			}
			SelectableLevel[] array = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.levels : null);
			TerminalKeyword[] array2 = (((Object)(object)terminalRef != (Object)null && (Object)(object)terminalRef.terminalNodes != (Object)null) ? terminalRef.terminalNodes.allKeywords : null);
			if (array == null || array2 == null)
			{
				return;
			}
			TerminalNode val = ((IEnumerable<TerminalKeyword>)array2).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword k) => (Object)(object)k != (Object)null && k.word == "moons"))?.specialKeywordResult;
			if ((Object)(object)val != (Object)null)
			{
				moonsListNode = val;
			}
			TerminalKeyword val2 = ((IEnumerable<TerminalKeyword>)array2).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword k) => (Object)(object)k != (Object)null && k.word == "route"));
			if (val2?.compatibleNouns == null)
			{
				return;
			}
			NodeLevel.Clear();
			CompatibleNoun[] compatibleNouns = val2.compatibleNouns;
			foreach (CompatibleNoun obj in compatibleNouns)
			{
				TerminalNode val3 = obj?.result;
				if ((Object)(object)val3 == (Object)null)
				{
					continue;
				}
				TerminalNode confirm = val3.terminalOptions?.Select((CompatibleNoun o) => o?.result).FirstOrDefault((Func<TerminalNode, bool>)((TerminalNode r) => (Object)(object)r != (Object)null && r.buyRerouteToMoon >= 0));
				if (!((Object)(object)confirm == (Object)null))
				{
					SelectableLevel val4 = ((IEnumerable<SelectableLevel>)array).FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel l) => (Object)(object)l != (Object)null && l.levelID == confirm.buyRerouteToMoon));
					if (!((Object)(object)val4 == (Object)null))
					{
						Track(val3, val4);
						Track(confirm, val4);
					}
				}
			}
		}

		private static void Track(TerminalNode node, SelectableLevel level)
		{
			NodeLevel[node] = level;
			if (!OriginalCost.ContainsKey(node))
			{
				OriginalCost[node] = node.itemCost;
			}
		}

		internal static void ApplyPrices()
		{
			Discover();
			foreach (SelectableLevel key in MoonManager.Entries.Keys)
			{
				OriginalPrice(key);
			}
			int num = 0;
			foreach (KeyValuePair<TerminalNode, SelectableLevel> item in NodeLevel.ToList())
			{
				if (!((Object)(object)item.Key == (Object)null))
				{
					int itemCost = DesiredPrice(item.Value);
					item.Key.itemCost = itemCost;
				}
			}
			foreach (SelectableLevel key2 in MoonManager.Entries.Keys)
			{
				if (MoonManager.Entries[key2].Enabled.Value && MoonManager.Entries[key2].RoutePrice.Value >= 0)
				{
					num++;
				}
				LLL.SetPrice(key2, DesiredPrice(key2));
			}
			string text = $"Route prices applied: {num} moon(s) with a custom Route Price, {NodeLevel.Count / 2} routable in the terminal.";
			if (text != lastPriceReport)
			{
				lastPriceReport = text;
				Plugin.Log.LogInfo((object)text);
			}
		}

		private static int DesiredPrice(SelectableLevel level)
		{
			if (PurchaseTracker.IsOwned(level))
			{
				return 0;
			}
			if (MoonManager.Entries.TryGetValue(level, out var value) && value.Enabled.Value && value.RoutePrice.Value >= 0)
			{
				return value.RoutePrice.Value;
			}
			return OriginalPrice(level);
		}

		private static int OriginalPrice(SelectableLevel level)
		{
			if (LLL.Present && LLL.TryOriginalPrice(level, out var price))
			{
				return price;
			}
			foreach (KeyValuePair<TerminalNode, SelectableLevel> item in NodeLevel)
			{
				if ((Object)(object)item.Key != (Object)null && (Object)(object)item.Value == (Object)(object)level && OriginalCost.TryGetValue(item.Key, out var value))
				{
					return value;
				}
			}
			return 0;
		}

		internal static int BasePrice(SelectableLevel level)
		{
			if (MoonManager.Entries.TryGetValue(level, out var value) && value.Enabled.Value && value.RoutePrice.Value >= 0)
			{
				return value.RoutePrice.Value;
			}
			return Math.Max(0, OriginalPrice(level));
		}

		internal static bool IsLocked(SelectableLevel level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (LockOverride.TryGetValue(level, out var value))
			{
				return value;
			}
			if (MoonManager.Entries.TryGetValue(level, out var value2) && value2.Enabled.Value)
			{
				return value2.Locked.Value;
			}
			return false;
		}

		internal static bool IsHidden(SelectableLevel level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (HiddenOverride.TryGetValue(level, out var value))
			{
				return value;
			}
			if (MoonManager.Entries.TryGetValue(level, out var value2) && value2.Enabled.Value)
			{
				return value2.Hidden.Value;
			}
			return false;
		}

		internal static TerminalNode Intercept(TerminalNode node)
		{
			if ((Object)(object)node == (Object)null)
			{
				return node;
			}
			Discover();
			bool flag = (Object)(object)node == (Object)(object)moonsListNode;
			if (!flag && !NodeLevel.ContainsKey(node))
			{
				return node;
			}
			MoonManager.RefreshAllInOrbit();
			if (flag || !NodeLevel.TryGetValue(node, out var value))
			{
				return node;
			}
			if (!IsLocked(value))
			{
				return node;
			}
			if ((Object)(object)lockedNode == (Object)null)
			{
				lockedNode = ScriptableObject.CreateInstance<TerminalNode>();
				((Object)lockedNode).name = "MoonTiersLocked";
				lockedNode.clearPreviousText = true;
				lockedNode.maxCharactersToType = 25;
				lockedNode.buyRerouteToMoon = -1;
				lockedNode.buyItemIndex = -1;
				lockedNode.itemCost = 0;
			}
			string text;
			try
			{
				text = string.Format(Plugin.LockedMessage.Value, ShortName(value.PlanetName));
			}
			catch (FormatException)
			{
				text = ShortName(value.PlanetName) + " is locked.";
			}
			lockedNode.displayText = "\n" + text + "\n\n";
			return lockedNode;
		}

		internal static int OverridePrice(SelectableLevel level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return -1;
			}
			if (PurchaseTracker.IsOwned(level))
			{
				return 0;
			}
			if (MoonManager.Entries.TryGetValue(level, out var value) && value.Enabled.Value && value.RoutePrice.Value >= 0)
			{
				return value.RoutePrice.Value;
			}
			return -1;
		}

		internal static int ShownPriceFor(TerminalNode node)
		{
			if ((Object)(object)node == (Object)null || !NodeLevel.TryGetValue(node, out var value))
			{
				return -1;
			}
			return DesiredPrice(value);
		}

		internal static TerminalNode BeforeCharge(Terminal terminal, TerminalNode node)
		{
			if ((Object)(object)terminalRef == (Object)null)
			{
				terminalRef = terminal;
			}
			Discover();
			if ((Object)(object)node == (Object)null || !NodeLevel.TryGetValue(node, out var value))
			{
				return node;
			}
			if (IsLocked(value))
			{
				return Intercept(node);
			}
			int num = DesiredPrice(value);
			int itemCost = node.itemCost;
			node.itemCost = num;
			LLL.SetPrice(value, num);
			Plugin.Log.LogInfo((object)($"Routing to {value.PlanetName}: charging {num} credits" + ((itemCost != num) ? $" (page had {itemCost})." : ".")));
			return node;
		}

		internal static string FilterMoonsList(string text, TerminalNode node)
		{
			if (string.IsNullOrEmpty(text) || (Object)(object)node == (Object)null || (Object)(object)node != (Object)(object)moonsListNode)
			{
				return text;
			}
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			List<string> list3 = new List<string>();
			foreach (SelectableLevel key in MoonManager.Entries.Keys)
			{
				if (IsHidden(key))
				{
					list.Add(ShortName(key.PlanetName));
				}
				else if (IsLocked(key))
				{
					list2.Add(ShortName(key.PlanetName));
				}
				else if (PurchaseTracker.IsOwned(key) && BasePrice(key) > 0)
				{
					list3.Add(ShortName(key.PlanetName));
				}
			}
			if (list.Count == 0 && list2.Count == 0 && list3.Count == 0)
			{
				return text;
			}
			string value = Plugin.LockedTag.Value;
			string value2 = Plugin.OwnedTag.Value;
			StringBuilder stringBuilder = new StringBuilder();
			string[] array = text.Split('\n');
			foreach (string text2 in array)
			{
				string name = ListedName(text2);
				if (name == null || !list.Any((string h) => Matches(name, h)))
				{
					string value3 = null;
					if (name != null && list2.Any((string l) => Matches(name, l)))
					{
						value3 = value;
					}
					else if (name != null && list3.Any((string o) => Matches(name, o)))
					{
						value3 = value2;
					}
					if (!string.IsNullOrEmpty(value3))
					{
						stringBuilder.Append(text2.TrimEnd('\r')).Append(' ').Append(value3)
							.Append('\n');
					}
					else
					{
						stringBuilder.Append(text2).Append('\n');
					}
				}
			}
			return stringBuilder.ToString().TrimEnd('\n') + (text.EndsWith("\n") ? "\n" : "");
		}

		internal static string FixShownPrices(string text, TerminalNode node)
		{
			if (string.IsNullOrEmpty(text) || text.IndexOf('$') < 0)
			{
				return text;
			}
			List<(string, string, string)> list = new List<(string, string, string)>();
			foreach (SelectableLevel key in MoonManager.Entries.Keys)
			{
				int num = OriginalPrice(key);
				int num2 = DesiredPrice(key);
				if (num != num2)
				{
					list.Add((ShortName(key.PlanetName), "$" + num, "$" + num2));
				}
			}
			if (list.Count == 0)
			{
				return text;
			}
			if ((Object)(object)node != (Object)null && NodeLevel.TryGetValue(node, out var value))
			{
				string text2 = ShortName(value.PlanetName);
				{
					foreach (var item in list)
					{
						if (item.Item1 == text2)
						{
							text = ReplacePrice(text, item.Item2, item.Item3);
						}
					}
					return text;
				}
			}
			string[] array = text.Split('\n');
			bool flag = false;
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].IndexOf('$') < 0)
				{
					continue;
				}
				foreach (var item2 in list)
				{
					if (ContainsWord(array[i], item2.Item1))
					{
						string text3 = ReplacePrice(array[i], item2.Item2, item2.Item3);
						if (text3 != array[i])
						{
							array[i] = text3;
							flag = true;
						}
						break;
					}
				}
			}
			if (!flag)
			{
				return text;
			}
			return string.Join("\n", array);
		}

		private static string ReplacePrice(string text, string from, string to)
		{
			return Regex.Replace(text, Regex.Escape(from) + "(?!\\d)", to.Replace("$", "$$"));
		}

		private static bool ContainsWord(string line, string word)
		{
			if (!string.IsNullOrEmpty(word))
			{
				return Regex.IsMatch(line, "(?<![\\w])" + Regex.Escape(word) + "(?![\\w])", RegexOptions.IgnoreCase);
			}
			return false;
		}

		private static string ListedName(string line)
		{
			string text = line.TrimStart();
			if (!text.StartsWith("*"))
			{
				return null;
			}
			return text.Substring(1).TrimStart();
		}

		private static bool Matches(string listed, string moon)
		{
			if (listed.StartsWith(moon, StringComparison.OrdinalIgnoreCase))
			{
				if (listed.Length != moon.Length)
				{
					return !char.IsLetterOrDigit(listed[moon.Length]);
				}
				return true;
			}
			return false;
		}

		internal static string ShortName(string planetName)
		{
			return Regex.Replace(planetName ?? "", "^\\d+\\s*", "").Trim();
		}
	}
	internal static class TerminalPatches
	{
		private static void Terminal_Start(Terminal __instance)
		{
			MoonManager.RegisterAll(((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.levels : null);
			if (AccessTools.Field(typeof(Terminal), "moonsCatalogueList")?.GetValue(__instance) is SelectableLevel[] levels)
			{
				MoonManager.RegisterAll(levels);
			}
			TerminalControl.Setup(__instance);
			MoonManager.RefreshAllInOrbit();
		}

		private static void Terminal_LoadNewNodeIfAffordable(Terminal __instance, object[] __args)
		{
			if (__args != null && __args.Length != 0)
			{
				object obj = __args[0];
				TerminalNode val = (TerminalNode)((obj is TerminalNode) ? obj : null);
				if (val != null)
				{
					__args[0] = TerminalControl.BeforeCharge(__instance, val);
				}
			}
		}

		private static void Terminal_LoadNewNode(object[] __args)
		{
			if (__args != null && __args.Length != 0)
			{
				object obj = __args[0];
				TerminalNode val = (TerminalNode)((obj is TerminalNode) ? obj : null);
				if (val != null)
				{
					__args[0] = TerminalControl.Intercept(val);
				}
			}
		}

		private static void Terminal_TextPostProcess_Pre(Terminal __instance, object[] __args)
		{
			int num = TerminalControl.ShownPriceFor(__args?.OfType<TerminalNode>().FirstOrDefault());
			if (num >= 0)
			{
				__instance.totalCostOfItems = num;
			}
		}

		private static void Terminal_TextPostProcess(ref string __result, object[] __args)
		{
			TerminalNode node = __args?.OfType<TerminalNode>().FirstOrDefault();
			__result = TerminalControl.FilterMoonsList(__result, node);
			__result = TerminalControl.FixShownPrices(__result, node);
		}
	}
}