Decompiled source of RandomMoons v0.1.0

neogalt-br.RandomMoons.dll

Decompiled 34 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dawn;
using Dawn.Internal;
using HarmonyLib;
using LethalNetworkAPI;
using LethalNetworkAPI.Utils;
using Microsoft.CodeAnalysis;
using RandomMoons.Draw;
using RandomMoons.Moons;
using Steamworks;
using Steamworks.Data;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("com.github.teamxiaolan.dawnlib")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("neogalt-br.RandomMoons")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+149d5d4552d1b07e5b057a40dbb72a1fe11de836")]
[assembly: AssemblyProduct("Random Moons")]
[assembly: AssemblyTitle("neogalt-br.RandomMoons")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RandomMoons
{
	internal static class DebugLog
	{
		[Conditional("DEBUG")]
		public static void Info(string message)
		{
			RandomMoons.Logger.LogInfo((object)("[debug] " + message));
		}
	}
	internal static class Draws
	{
		private static readonly DrawModel Model = new DrawModel(new Random().NextDouble);

		private static bool _loggedMoons;

		private static string? _warnedExclusions;

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

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

		private static bool _firedSinceTheLastDraw;

		public static void Load(StartOfRound startOfRound)
		{
			LastWarnings.Clear();
			Absences.Clear();
			_firedSinceTheLastDraw = false;
			SavedOffer savedOffer = SaveFile.Load();
			if (savedOffer == null)
			{
				Run(startOfRound, atLoad: true);
				return;
			}
			IReadOnlyList<OfferPredicate> moons = MoonHiding.Moons;
			List<string> list = new List<string>(moons.Count);
			List<string> list2 = new List<string>();
			for (int i = 0; i < moons.Count; i++)
			{
				list.Add(moons[i].Key);
				if (moons[i].IsLocked)
				{
					list2.Add(moons[i].Key);
				}
			}
			SavedOffer savedOffer2 = savedOffer.Restore(list);
			foreach (KeyValuePair<string, int> absence in savedOffer2.Absences)
			{
				Absences[absence.Key] = absence.Value;
			}
			PutInForce(savedOffer2.OfferedMoons);
			RandomMoons.Logger.LogInfo((object)("Loaded the saved offer: " + OfferTip.OfferedMoonNames() + "."));
			var (ship, offeredMoon) = savedOffer2.MoveShip(ShipMoon(startOfRound.currentLevel), list2);
			MoveShip(startOfRound, ship, offeredMoon, atLoad: true);
			OfferTip.ShowOnceSpawned();
		}

		public static void Save()
		{
			if (Offer.IsActive && !_firedSinceTheLastDraw)
			{
				SaveFile.Save(new SavedOffer(Offer.Moons, Absences));
			}
		}

		public static void ForgetAbsences()
		{
			Absences.Clear();
			_firedSinceTheLastDraw = true;
			SaveFile.Delete();
		}

		public static void Run(StartOfRound startOfRound, bool atLoad)
		{
			ExcludedMoons excluded = RandomMoons.Configuration.ExcludedMoons();
			WarnAboutUnmatchedExclusions(excluded);
			List<OfferPredicate> list = MoonPool(excluded);
			List<PoolMoon> list2 = new List<PoolMoon>(list.Count);
			for (int i = 0; i < list.Count; i++)
			{
				string key = list[i].Key;
				string riskLevel = list[i].Moon.Level.riskLevel ?? "";
				list2.Add(Absences.TryGetValue(key, out var value) ? new PoolMoon(key, riskLevel, value) : new PoolMoon(key, riskLevel));
			}
			int num = Quota();
			DrawResult drawResult = Model.Draw(new DrawInput
			{
				MoonPool = list2,
				Quota = num,
				OfferedMoons = RandomMoons.Configuration.OfferedMoons,
				RiskLevelWeights = RandomMoons.Configuration.RiskLevelWeights,
				OtherRiskLevelsWeight = RandomMoons.Configuration.OtherRiskLevelsWeight,
				QuotaSettings = RandomMoons.Configuration.Quotas(),
				DefaultQuotaMode = RandomMoons.Configuration.DefaultQuotaMode,
				GuaranteedAfter = RandomMoons.Configuration.GuaranteedAfter,
				ShipMoon = ShipMoon(startOfRound.currentLevel)
			});
			foreach (KeyValuePair<string, int> absence in drawResult.Absences)
			{
				Absences[absence.Key] = absence.Value;
			}
			LogNewWarnings(drawResult.Warnings);
			PutInForce(drawResult.OfferedMoons);
			RandomMoons.Logger.LogInfo((object)($"Draw for Quota {num}: offering {OfferTip.OfferedMoonNames()} out of {list2.Count} " + "moons in the Moon Pool."));
			MoveShip(startOfRound, drawResult.Ship, drawResult.ShipDestination, atLoad);
			_firedSinceTheLastDraw = false;
			Save();
			OfferTip.ShowOnceSpawned();
		}

		private static void PutInForce(IReadOnlyList<string> offeredMoons)
		{
			Offer.Set(offeredMoons);
			OfferSync.Publish();
		}

		private static List<OfferPredicate> MoonPool(ExcludedMoons excluded)
		{
			IReadOnlyList<OfferPredicate> moons = MoonHiding.Moons;
			List<OfferPredicate> list = new List<OfferPredicate>(moons.Count);
			for (int i = 0; i < moons.Count; i++)
			{
				OfferPredicate offerPredicate = moons[i];
				if (!offerPredicate.IsLocked && !excluded.Contains(offerPredicate.Moon))
				{
					list.Add(offerPredicate);
				}
			}
			return list;
		}

		private static int Quota()
		{
			return TimeOfDay.Instance.timesFulfilledQuota + 1;
		}

		[Conditional("DEBUG")]
		private static void LogAbsences(List<PoolMoon> pool, DrawResult result)
		{
			StringBuilder stringBuilder = new StringBuilder("Absence before -> after this Draw:");
			for (int i = 0; i < pool.Count; i++)
			{
				stringBuilder.Append($"\n  {pool[i].Key} ({pool[i].RiskLevel}): {pool[i].Absence} -> {result.Absences[pool[i].Key]}");
			}
		}

		private static void LogNewWarnings(IReadOnlyList<string> warnings)
		{
			HashSet<string> hashSet = new HashSet<string>(LastWarnings);
			LastWarnings.Clear();
			for (int i = 0; i < warnings.Count; i++)
			{
				LastWarnings.Add(warnings[i]);
				if (!hashSet.Contains(warnings[i]))
				{
					RandomMoons.Logger.LogWarning((object)warnings[i]);
				}
			}
		}

		private static void WarnAboutUnmatchedExclusions(ExcludedMoons excluded)
		{
			if (!(excluded.Setting == _warnedExclusions))
			{
				_warnedExclusions = excluded.Setting;
				List<string> list = excluded.Unmatched(((Registry<DawnMoonInfo>)(object)LethalContent.Moons).Values);
				if (list.Count > 0)
				{
					RandomMoons.Logger.LogWarning((object)("Excluded moons: no moon is called " + string.Join(", ", list) + "."));
				}
			}
		}

		[Conditional("DEBUG")]
		private static void LogMoonsOnce(ExcludedMoons excluded)
		{
			if (_loggedMoons)
			{
				return;
			}
			_loggedMoons = true;
			StringBuilder stringBuilder = new StringBuilder("Every moon DawnLib lists (key | Risk Level | original purchase state | Moon Pool):");
			foreach (DawnMoonInfo value in ((Registry<DawnMoonInfo>)(object)LethalContent.Moons).Values)
			{
				ITerminalPurchasePredicate purchasePredicate = value.DawnPurchaseInfo.PurchasePredicate;
				OfferPredicate offerPredicate = purchasePredicate as OfferPredicate;
				string text = PurchaseState((offerPredicate?.Original ?? purchasePredicate).CanPurchase());
				string text2 = ((offerPredicate != null) ? ((!offerPredicate.IsLocked) ? ((!excluded.Contains(value)) ? "yes" : "no, excluded") : "no, locked") : (((DawnBaseInfo<DawnMoonInfo>)(object)value).HasTag(Tags.Company) ? "no, the Company building" : "no, not in the catalogue or no route"));
				stringBuilder.Append($"\n  {((DawnBaseInfo<DawnMoonInfo>)(object)value).Key} | {value.Level.riskLevel} | {text} | {text2}");
			}
			RandomMoons.Logger.LogInfo((object)stringBuilder.ToString());
		}

		private static string PurchaseState(TerminalPurchaseResult result)
		{
			if (!(result is FailedPurchaseResult))
			{
				HiddenPurchaseResult val = (HiddenPurchaseResult)(object)((result is HiddenPurchaseResult) ? result : null);
				if (val != null)
				{
					if (val.IsFailure)
					{
						return "hidden and locked";
					}
					return "hidden";
				}
				return "routable";
			}
			return "locked";
		}

		private static string? ShipMoon(SelectableLevel level)
		{
			DawnMoonInfo dawnInfo = SelectableLevelExtensions.GetDawnInfo(level);
			if (dawnInfo == null)
			{
				return level.sceneName;
			}
			if (!((DawnBaseInfo<DawnMoonInfo>)(object)dawnInfo).HasTag(Tags.Company))
			{
				return ((object)((DawnBaseInfo<DawnMoonInfo>)(object)dawnInfo).Key).ToString();
			}
			return null;
		}

		private static void MoveShip(StartOfRound startOfRound, ShipMove ship, string? offeredMoon, bool atLoad)
		{
			SelectableLevel val = null;
			switch (ship)
			{
			case ShipMove.MoveToOfferedMoon:
			{
				OfferPredicate? offerPredicate = MoonHiding.Find(offeredMoon);
				val = ((offerPredicate != null) ? offerPredicate.Moon.Level : null);
				break;
			}
			case ShipMove.MoveToCompanyBuilding:
				val = CompanyBuilding();
				break;
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			int num = Array.IndexOf(startOfRound.levels, val);
			if (num < 0)
			{
				RandomMoons.Logger.LogError((object)("Can't move the ship to " + val.PlanetName + ": it isn't in the game's levels."));
				return;
			}
			RandomMoons.Logger.LogInfo((object)("Moving the ship from " + startOfRound.currentLevel.PlanetName + " to " + val.PlanetName + "."));
			if (atLoad)
			{
				startOfRound.ChangeLevel(num);
				startOfRound.ChangePlanet();
			}
			else
			{
				startOfRound.ChangeLevelServerRpc(num, Object.FindObjectOfType<Terminal>().groupCredits);
			}
		}

		private static SelectableLevel? CompanyBuilding()
		{
			foreach (DawnMoonInfo value in ((Registry<DawnMoonInfo>)(object)LethalContent.Moons).Values)
			{
				if (((DawnBaseInfo<DawnMoonInfo>)(object)value).HasTag(Tags.Company))
				{
					return value.Level;
				}
			}
			return null;
		}
	}
	[BepInPlugin("neogalt-br.RandomMoons", "Random Moons", "0.1.0")]
	[BepInDependency("com.github.teamxiaolan.dawnlib", "0.9.25")]
	[BepInDependency("LethalNetworkAPI", "3.4.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInIncompatibility("com.xmods.lethalmoonunlocks")]
	public class RandomMoons : BaseUnityPlugin
	{
		private const string DawnGuid = "com.github.teamxiaolan.dawnlib";

		private const string LethalNetworkApiGuid = "LethalNetworkAPI";

		private const string LethalMoonUnlocksGuid = "com.xmods.lethalmoonunlocks";

		internal const string LethalLevelLoaderGuid = "imabatby.lethallevelloader";

		public static RandomMoons Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		internal static RandomMoonsConfig Configuration { get; private set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Configuration = new RandomMoonsConfig(((BaseUnityPlugin)this).Config);
			MoonHiding.Init();
			OfferSync.Init();
			Patch();
			Logger.LogInfo((object)"neogalt-br.RandomMoons v0.1.0 has loaded!");
		}

		internal static void Patch()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("neogalt-br.RandomMoons");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
		}

		internal static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	internal sealed class RandomMoonsConfig
	{
		internal enum QuotaSectionMode
		{
			Default,
			Merge,
			Replace
		}

		private sealed class QuotaSection
		{
			private readonly ConfigEntry<string> _offeredMoons;

			private readonly ConfigEntry<string> _riskLevelWeights;

			private readonly ConfigEntry<string> _otherRiskLevelsWeight;

			private readonly ConfigEntry<QuotaSectionMode> _mode;

			public QuotaSection(ConfigFile file, int quota)
			{
				string text = $"Quota {quota}";
				string text2 = ((quota == 1) ? "the [Defaults]" : $"Quota {quota - 1}'s");
				_offeredMoons = file.Bind<string>(text, "Offered Moons", "", $"How many moons each Draw offers during Quota {quota}. Empty or -1 uses {text2}.");
				_riskLevelWeights = file.Bind<string>(text, "Risk Level weights", "", $"The Risk Level weights during Quota {quota}, written like the [Defaults] ones. Mode decides what the " + "Risk Levels not listed here get. Empty or -1 uses " + text2 + ".");
				_otherRiskLevelsWeight = file.Bind<string>(text, "Other Risk Levels weight", "", $"The weight of every Risk Level that no weight lists, during Quota {quota}. Empty or -1 uses " + text2 + ".");
				_mode = file.Bind<QuotaSectionMode>(text, "Mode", QuotaSectionMode.Default, "How this section's Risk Level weights combine with the earlier ones. Default: as Default quota mode says. Merge: Risk Levels not listed here keep their earlier weights. Replace: they get the Other Risk Levels weight.");
			}

			public QuotaSettings Settings()
			{
				QuotaSettings quotaSettings = new QuotaSettings();
				quotaSettings.OfferedMoons = _offeredMoons.Value;
				quotaSettings.RiskLevelWeights = _riskLevelWeights.Value;
				quotaSettings.OtherRiskLevelsWeight = _otherRiskLevelsWeight.Value;
				QuotaSettings quotaSettings2 = quotaSettings;
				quotaSettings2.Mode = _mode.Value switch
				{
					QuotaSectionMode.Merge => QuotaMode.Merge, 
					QuotaSectionMode.Replace => QuotaMode.Replace, 
					_ => null, 
				};
				return quotaSettings;
			}
		}

		private const string Draw = "Draw";

		private const string Defaults = "Defaults";

		private readonly ConfigEntry<int> _guaranteedAfter;

		private readonly ConfigEntry<string> _excludedMoons;

		private readonly ConfigEntry<QuotaMode> _defaultQuotaMode;

		private readonly ConfigEntry<int> _offeredMoons;

		private readonly ConfigEntry<string> _riskLevelWeights;

		private readonly ConfigEntry<int> _otherRiskLevelsWeight;

		private readonly List<QuotaSection> _quotas = new List<QuotaSection>();

		public int GuaranteedAfter => _guaranteedAfter.Value;

		public QuotaMode DefaultQuotaMode => _defaultQuotaMode.Value;

		public int OfferedMoons => _offeredMoons.Value;

		public string RiskLevelWeights => _riskLevelWeights.Value;

		public int OtherRiskLevelsWeight => _otherRiskLevelsWeight.Value;

		public RandomMoonsConfig(ConfigFile file)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			_guaranteedAfter = file.Bind<int>("Draw", "Guaranteed after", 6, new ConfigDescription("How many Draws in a row a moon can go without being offered before it is guaranteed: it is then offered whenever its Risk Level gets a pick, the moon that has waited longest first. Lower makes moons come back faster. Until then, a moon's chance grows with each Draw it isn't offered, and a moon just offered sits out the next Draw unless too few other moons of its Risk Level are left.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
			_excludedMoons = file.Bind<string>("Draw", "Excluded moons", "", "Moons that are never offered, separated by commas. Use a moon's name, with or without its number (Experimentation, 41 Experimentation), or its DawnLib key (lethal_company:experimentation). The log warns about names that match no moon.");
			_defaultQuotaMode = file.Bind<QuotaMode>("Draw", "Default quota mode", QuotaMode.Merge, "How a Quota section's Risk Level weights combine with the earlier Quotas', unless the section sets its own Mode. Merge: Risk Levels the section doesn't list keep their earlier weights. Replace: they get the Other Risk Levels weight.");
			ConfigEntry<int> val = file.Bind<int>("Draw", "Quota sections", 5, new ConfigDescription("How many Quota sections ([Quota 1], [Quota 2]...) Random Moons reads. Every Quota after the last section keeps that section's settings. Takes effect after a restart. Lowering it leaves the sections above it in this file, where they are ignored.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			_offeredMoons = file.Bind<int>("Defaults", "Offered Moons", 3, new ConfigDescription("How many moons each Draw offers. The Company building is always available on top.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			_riskLevelWeights = file.Bind<string>("Defaults", "Risk Level weights", "", "How large a share of the Offered Moons each Risk Level gets, relative to the others, as Risk Level=weight pairs separated by commas (D=1, C=1, B=2). Risk Levels are the letter grades the terminal shows, including LunarConfig's changes; case doesn't matter. A weight of 0 means that Risk Level is never offered. The log warns about malformed entries and names the Risk Levels not listed here.");
			_otherRiskLevelsWeight = file.Bind<int>("Defaults", "Other Risk Levels weight", 1, new ConfigDescription("The weight of every Risk Level that Risk Level weights doesn't list, such as a modded moon's.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			for (int i = 1; i <= val.Value; i++)
			{
				_quotas.Add(new QuotaSection(file, i));
			}
		}

		public ExcludedMoons ExcludedMoons()
		{
			return new ExcludedMoons(_excludedMoons.Value);
		}

		public IReadOnlyList<QuotaSettings> Quotas()
		{
			List<QuotaSettings> list = new List<QuotaSettings>(_quotas.Count);
			foreach (QuotaSection quota in _quotas)
			{
				list.Add(quota.Settings());
			}
			return list;
		}
	}
	internal static class SaveFile
	{
		private const string OfferedMoonsKey = "RandomMoons_OfferedMoons";

		private const string AbsencesKey = "RandomMoons_Absences";

		private const string GameVersionKey = "FileGameVers";

		private static string Name => GameNetworkManager.Instance.currentSaveFileName;

		public static SavedOffer? Load()
		{
			if (!ES3.KeyExists("RandomMoons_OfferedMoons", Name) || !ES3.KeyExists("RandomMoons_Absences", Name))
			{
				return null;
			}
			try
			{
				return new SavedOffer(ES3.Load<List<string>>("RandomMoons_OfferedMoons", Name), ES3.Load<Dictionary<string, int>>("RandomMoons_Absences", Name));
			}
			catch (Exception arg)
			{
				RandomMoons.Logger.LogError((object)$"Couldn't read the saved offer, so this save starts as a new one:\n{arg}");
				return null;
			}
		}

		public static void Save(SavedOffer offer)
		{
			if (!ES3.KeyExists("FileGameVers", Name))
			{
				return;
			}
			ES3.Save<List<string>>("RandomMoons_OfferedMoons", new List<string>(offer.OfferedMoons), Name);
			Dictionary<string, int> dictionary = new Dictionary<string, int>(offer.Absences.Count);
			foreach (KeyValuePair<string, int> absence in offer.Absences)
			{
				dictionary.Add(absence.Key, absence.Value);
			}
			ES3.Save<Dictionary<string, int>>("RandomMoons_Absences", dictionary, Name);
		}

		public static void Delete()
		{
			ES3.DeleteKey("RandomMoons_OfferedMoons", Name);
			ES3.DeleteKey("RandomMoons_Absences", Name);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "neogalt-br.RandomMoons";

		public const string PLUGIN_NAME = "Random Moons";

		public const string PLUGIN_VERSION = "0.1.0";
	}
}
namespace RandomMoons.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class GameNetworkManagerPatch
	{
		[HarmonyPatch("SaveGameValues")]
		[HarmonyPostfix]
		private static void SaveTheOffer(GameNetworkManager __instance)
		{
			if (__instance.isHostingGame)
			{
				Draws.Save();
			}
		}

		[HarmonyPatch("ResetSavedGameValues")]
		[HarmonyPostfix]
		private static void ForgetTheAbsences(GameNetworkManager __instance)
		{
			if (__instance.isHostingGame)
			{
				Draws.ForgetAbsences();
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class ModCheckPatch
	{
		private const char Separator = ',';

		[HarmonyPatch("SteamMatchmaking_OnLobbyCreated")]
		[HarmonyPostfix]
		private static void MarkTheLobbyAsRandomMoons(Result result, ref Lobby lobby)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)result == 1)
			{
				((Lobby)(ref lobby)).SetData("neogalt-br.RandomMoons", "0.1.0");
			}
		}

		[HarmonyPatch("LobbyDataIsJoinable")]
		[HarmonyPostfix]
		private static void RefuseLobbiesWithoutRandomMoons(ref Lobby lobby, ref bool __result)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (__result && string.IsNullOrEmpty(((Lobby)(ref lobby)).GetData("neogalt-br.RandomMoons")))
			{
				__result = false;
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)2, "The server host isn't running the Random Moons mod.");
				RandomMoons.Logger.LogInfo((object)string.Format("Refused lobby {0}: its host isn't running {1}.", ((Lobby)(ref lobby)).Id, "Random Moons"));
			}
		}

		[HarmonyPatch("SetConnectionDataBeforeConnecting")]
		[HarmonyPostfix]
		private static void AnnounceRandomMoons()
		{
			NetworkConfig networkConfig = NetworkManager.Singleton.NetworkConfig;
			string text = Encoding.ASCII.GetString(networkConfig.ConnectionData);
			networkConfig.ConnectionData = Encoding.ASCII.GetBytes(text + ",neogalt-br.RandomMoons");
		}

		[HarmonyPatch("ConnectionApproval")]
		[HarmonyPostfix]
		private static void TurnAwayClientsWithoutRandomMoons(ref ConnectionApprovalRequest request, ConnectionApprovalResponse response)
		{
			if (request.ClientNetworkId != NetworkManager.Singleton.LocalClientId && response.Approved)
			{
				string[] array = Encoding.ASCII.GetString(request.Payload).Split(',');
				if (Array.IndexOf(array, "neogalt-br.RandomMoons") < 0)
				{
					response.Approved = false;
					response.Reason = "This lobby requires the Random Moons mod.";
					RandomMoons.Logger.LogInfo((object)string.Format("Turned away client {0}: {1} isn't loaded.", request.ClientNetworkId, "Random Moons"));
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartWithThisLobbysOffer(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				Offer.Clear();
			}
			else
			{
				OfferSync.PutReceivedInForce();
			}
		}

		[HarmonyPatch("SetTimeAndPlanetToSavedSettings")]
		[HarmonyPostfix]
		private static void LoadTheOfferWhenTheSaveLoads(StartOfRound __instance)
		{
			if (!__instance.isChallengeFile)
			{
				Draws.Load(__instance);
			}
		}

		[HarmonyPatch("SetShipReadyToLand")]
		[HarmonyPostfix]
		private static void DrawBackInOrbit(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer && !__instance.isChallengeFile)
			{
				Draws.Run(__instance, atLoad: false);
			}
		}

		[HarmonyPatch("ChangeLevelServerRpc")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RefuseRoutesToMoonsNotOffered(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			Label? label2 = default(Label?);
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[3]
			{
				new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(StartOfRound), "isChallengeFile"), (string)null),
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction instruction) => CodeInstructionExtensions.Branches(instruction, ref label2)), (string)null)
			}).ThrowIfInvalid("Couldn't find the host's route check in StartOfRound.ChangeLevelServerRpc.");
			Label label = (Label)val.Operand;
			return val.Advance(1).Insert((CodeInstruction[])(object)new CodeInstruction[3]
			{
				new CodeInstruction(OpCodes.Ldarg_1, (object)null),
				CodeInstruction.Call(typeof(StartOfRoundPatch), "IsNotOffered", (Type[])null, (Type[])null),
				new CodeInstruction(OpCodes.Brtrue, (object)label)
			}).InstructionEnumeration();
		}

		private static bool IsNotOffered(int levelId)
		{
			OfferPredicate offerPredicate = MoonHiding.FindNotOffered(levelId);
			if (offerPredicate == null)
			{
				return false;
			}
			RandomMoons.Logger.LogInfo((object)("Refused a route to " + offerPredicate.Moon.GetNumberlessPlanetName() + ": it isn't offered. The credits go back to the crew."));
			return true;
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public class TerminalPatch
	{
		[HarmonyPatch("ParsePlayerSentence")]
		[HarmonyPostfix]
		private static void RefuseRoutesToMoonsNotOffered(ref TerminalNode __result)
		{
			if (!((Object)(object)__result == (Object)null) && __result.buyRerouteToMoon == -2)
			{
				OfferPredicate offerPredicate = MoonHiding.FindNotOffered(__result.displayPlanetInfo);
				if (offerPredicate != null)
				{
					__result = offerPredicate.Refusal;
				}
			}
		}
	}
}
namespace RandomMoons.Moons
{
	internal sealed class ExcludedMoons
	{
		private readonly List<string> _entries = new List<string>();

		public string Setting { get; }

		public ExcludedMoons(string setting)
		{
			Setting = setting;
			string[] array = setting.Split(',');
			foreach (string text in array)
			{
				string text2 = text.Trim();
				if (text2.Length > 0)
				{
					_entries.Add(text2);
				}
			}
		}

		public bool Contains(DawnMoonInfo moon)
		{
			for (int i = 0; i < _entries.Count; i++)
			{
				if (Names(_entries[i], moon))
				{
					return true;
				}
			}
			return false;
		}

		public List<string> Unmatched(IEnumerable<DawnMoonInfo> moons)
		{
			List<string> list = new List<string>(_entries);
			foreach (DawnMoonInfo moon in moons)
			{
				list.RemoveAll((string entry) => Names(entry, moon));
			}
			return list;
		}

		private static bool Names(string entry, DawnMoonInfo moon)
		{
			if (!string.Equals(entry, ((object)((DawnBaseInfo<DawnMoonInfo>)(object)moon).Key).ToString(), StringComparison.OrdinalIgnoreCase) && !string.Equals(entry, moon.Level.PlanetName, StringComparison.OrdinalIgnoreCase))
			{
				return string.Equals(LettersOnly(entry), moon.GetNumberlessPlanetName(), StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private static string LettersOnly(string text)
		{
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			foreach (char c in text)
			{
				if (char.IsLetter(c))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}
	}
	internal static class MoonHiding
	{
		private static readonly List<OfferPredicate> Predicates = new List<OfferPredicate>();

		public static IReadOnlyList<OfferPredicate> Moons => Predicates;

		public static void Init()
		{
			if (DawnConfig.VanillaCompatibility.Value)
			{
				string text = (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") ? "LethalLevelLoader's moons catalogue will list every moon" : "the game's moons catalogue will list every vanilla moon");
				RandomMoons.Logger.LogWarning((object)("DawnLib's \"Vanilla Compatibility\" is on, so " + text + ", offered or not. Routing to a moon that isn't offered is still refused."));
			}
			LethalContent.Moons.AfterTagging += WrapPredicates;
		}

		public static OfferPredicate? Find(string key)
		{
			for (int i = 0; i < Predicates.Count; i++)
			{
				if (Predicates[i].Key == key)
				{
					return Predicates[i];
				}
			}
			return null;
		}

		public static OfferPredicate? Find(SelectableLevel level)
		{
			DawnMoonInfo dawnInfo = SelectableLevelExtensions.GetDawnInfo(level);
			if (dawnInfo == null)
			{
				return null;
			}
			return dawnInfo.DawnPurchaseInfo.PurchasePredicate as OfferPredicate;
		}

		public static OfferPredicate? FindNotOffered(int levelId)
		{
			if (!Offer.IsActive)
			{
				return null;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			if (levelId < 0 || levelId >= levels.Length)
			{
				return null;
			}
			OfferPredicate offerPredicate = Find(levels[levelId]);
			if (offerPredicate == null || Offer.Contains(offerPredicate.Key))
			{
				return null;
			}
			return offerPredicate;
		}

		private static void WrapPredicates()
		{
			try
			{
				foreach (DawnMoonInfo value in ((Registry<DawnMoonInfo>)(object)LethalContent.Moons).Values)
				{
					if (!((DawnBaseInfo<DawnMoonInfo>)(object)value).HasTag(Tags.Company) && !((DawnBaseInfo<DawnMoonInfo>)(object)value).HasTag(Tags.Unimplemented) && !((Object)(object)value.RouteNode == (Object)null))
					{
						OfferPredicate offerPredicate = new OfferPredicate(value, value.DawnPurchaseInfo.PurchasePredicate);
						value.DawnPurchaseInfo.PurchasePredicate = (ITerminalPurchasePredicate)(object)offerPredicate;
						Predicates.Add(offerPredicate);
					}
				}
				RandomMoons.Logger.LogInfo((object)$"Took over the purchase predicates of {Predicates.Count} moons.");
			}
			catch (Exception arg)
			{
				RandomMoons.Logger.LogError((object)$"Couldn't take over the moons' purchase predicates:\n{arg}");
			}
		}
	}
	internal static class Offer
	{
		private static readonly HashSet<string> Keys = new HashSet<string>();

		private static readonly List<string> InOrder = new List<string>();

		public static bool IsActive { get; private set; }

		public static IReadOnlyList<string> Moons => InOrder;

		public static bool Contains(string key)
		{
			return Keys.Contains(key);
		}

		public static void Set(IReadOnlyList<string> keys)
		{
			Keys.Clear();
			InOrder.Clear();
			for (int i = 0; i < keys.Count; i++)
			{
				Keys.Add(keys[i]);
				InOrder.Add(keys[i]);
			}
			IsActive = true;
		}

		public static void Clear()
		{
			Keys.Clear();
			InOrder.Clear();
			IsActive = false;
		}
	}
	internal sealed class OfferPredicate : ITerminalPurchasePredicate
	{
		private readonly TerminalPurchaseResult _notOffered;

		public DawnMoonInfo Moon { get; }

		public string Key { get; }

		public ITerminalPurchasePredicate Original { get; }

		public TerminalNode Refusal { get; }

		public bool IsLocked
		{
			get
			{
				TerminalPurchaseResult val = Original.CanPurchase();
				if (!(val is FailedPurchaseResult))
				{
					HiddenPurchaseResult val2 = (HiddenPurchaseResult)(object)((val is HiddenPurchaseResult) ? val : null);
					if (val2 == null || !val2.IsFailure)
					{
						return false;
					}
				}
				return true;
			}
		}

		public OfferPredicate(DawnMoonInfo moon, ITerminalPurchasePredicate original)
		{
			Moon = moon;
			Key = ((object)((DawnBaseInfo<DawnMoonInfo>)(object)moon).Key).ToString();
			Original = original;
			Refusal = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)Refusal).name = "RandomMoons" + moon.GetNumberlessPlanetName() + "NotOffered";
			Refusal.displayText = moon.GetNumberlessPlanetName() + " isn't offered right now.\n\n";
			Refusal.clearPreviousText = true;
			_notOffered = (TerminalPurchaseResult)(object)TerminalPurchaseResult.Hidden().SetFailure(true).SetFailNode(Refusal);
		}

		public TerminalPurchaseResult CanPurchase()
		{
			if (!Offer.IsActive)
			{
				return Original.CanPurchase();
			}
			if (!Offer.Contains(Key))
			{
				return _notOffered;
			}
			TerminalPurchaseResult val = Original.CanPurchase();
			HiddenPurchaseResult val2 = (HiddenPurchaseResult)(object)((val is HiddenPurchaseResult) ? val : null);
			if (val2 == null || val2.IsFailure)
			{
				return val;
			}
			return (TerminalPurchaseResult)(object)TerminalPurchaseResult.Success();
		}
	}
	internal static class OfferSync
	{
		private static LNetworkVariable<string[]?> _offer;

		public static void Init()
		{
			_offer = LNetworkVariable<string[]>.Connect("OfferedMoons", (string[])null, (LNetworkVariableWritePerms)0, (Action<string[], string[]>)delegate(string[]? _, string[]? received)
			{
				Receive(received);
			});
			_offer.OnInitialized += delegate
			{
				Receive(_offer.Value);
			};
		}

		public static void Publish()
		{
			IReadOnlyList<string> moons = Offer.Moons;
			string[] array = new string[moons.Count];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = moons[i];
			}
			_offer.Value = array;
		}

		public static void PutReceivedInForce()
		{
			PutInForce(_offer.Value);
		}

		private static void PutInForce(string[]? keys)
		{
			if (keys == null)
			{
				Offer.Clear();
			}
			else
			{
				Offer.Set(keys);
			}
		}

		private static void Receive(string[]? keys)
		{
			if (!LNetworkUtils.IsHostOrServer)
			{
				PutInForce(keys);
				if (Offer.IsActive)
				{
					RandomMoons.Logger.LogInfo((object)("Received the host's offer: " + OfferTip.OfferedMoonNames() + "."));
					OfferTip.ShowOnceSpawned();
				}
			}
		}
	}
	internal static class OfferTip
	{
		public static void ShowOnceSpawned()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				((MonoBehaviour)instance).StartCoroutine(ShowOnceInControl());
			}
		}

		public static string OfferedMoonNames()
		{
			StringBuilder stringBuilder = new StringBuilder();
			IReadOnlyList<string> moons = Offer.Moons;
			for (int i = 0; i < moons.Count; i++)
			{
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(", ");
				}
				OfferPredicate? offerPredicate = MoonHiding.Find(moons[i]);
				stringBuilder.Append(((offerPredicate != null) ? offerPredicate.Moon.GetNumberlessPlanetName() : null) ?? moons[i]);
			}
			if (stringBuilder.Length <= 0)
			{
				return "no moon";
			}
			return stringBuilder.ToString();
		}

		private static IEnumerator ShowOnceInControl()
		{
			yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.localClientHasControl));
			HUDManager.Instance.DisplayTip("Offered Moons", Text(), false, false, "LC_Tip1");
		}

		private static string Text()
		{
			if (Offer.Moons.Count == 0)
			{
				return "Only the Company building is available.";
			}
			return OfferedMoonNames() + ", and the Company building.";
		}
	}
}
namespace RandomMoons.Draw
{
	public sealed class DrawInput
	{
		public IReadOnlyList<PoolMoon> MoonPool { get; set; } = Array.Empty<PoolMoon>();

		public int Quota { get; set; } = 1;

		public int OfferedMoons { get; set; }

		public string RiskLevelWeights { get; set; } = "";

		public int OtherRiskLevelsWeight { get; set; } = 1;

		public IReadOnlyList<QuotaSettings> QuotaSettings { get; set; } = Array.Empty<QuotaSettings>();

		public QuotaMode DefaultQuotaMode { get; set; }

		public int GuaranteedAfter { get; set; } = 6;

		public string? ShipMoon { get; set; }
	}
	public sealed class DrawModel
	{
		private sealed class QuotaValues
		{
			public int OfferedMoons { get; set; }

			public int OtherWeight { get; set; }

			public Dictionary<string, int> Weights { get; }

			public QuotaValues(int offeredMoons, int otherWeight, Dictionary<string, int> weights)
			{
				OfferedMoons = offeredMoons;
				OtherWeight = otherWeight;
				Weights = weights;
			}
		}

		private sealed class RiskLevel
		{
			public string Name { get; }

			public int Weight { get; }

			public bool IsListed { get; }

			public List<int> Moons { get; } = new List<int>();

			public int Picks { get; set; }

			public int Room => Moons.Count - Picks;

			public bool CanTakeMorePicks
			{
				get
				{
					if (Weight > 0)
					{
						return Room > 0;
					}
					return false;
				}
			}

			public RiskLevel(string name, int weight, bool isListed)
			{
				Name = name;
				Weight = weight;
				IsListed = isListed;
			}
		}

		private readonly Func<double> _random;

		public DrawModel(Func<double> random)
		{
			_random = random;
		}

		public DrawResult Draw(DrawInput input)
		{
			IReadOnlyList<PoolMoon> moonPool = input.MoonPool;
			List<string> list = new List<string>();
			QuotaValues quotaValues = CurrentSettings(input, list);
			List<RiskLevel> list2 = RiskLevels(moonPool, quotaValues.Weights, quotaValues.OtherWeight);
			SharePicks(list2, quotaValues.OfferedMoons);
			int guaranteedAfter = Math.Max(1, input.GuaranteedAfter);
			List<int> list3 = new List<int>();
			foreach (RiskLevel item in list2)
			{
				list3.AddRange(PickMoons(item, moonPool, guaranteedAfter));
			}
			list3.Sort();
			List<string> list4 = new List<string>(list3.Count);
			foreach (int item2 in list3)
			{
				list4.Add(moonPool[item2].Key);
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>(moonPool.Count);
			foreach (PoolMoon item3 in moonPool)
			{
				dictionary[item3.Key] = Absence(item3) + 1;
			}
			foreach (string item4 in list4)
			{
				dictionary[item4] = 0;
			}
			List<string> list5 = new List<string>();
			if (moonPool.Count == 0)
			{
				list5.Add("No moon can be offered: the Moon Pool is empty. Only the Company building is available.");
			}
			else if (quotaValues.OfferedMoons == 0)
			{
				list5.Add("No moon can be offered: Offered Moons is 0. Only the Company building is available.");
			}
			else if (list4.Count == 0)
			{
				list5.Add("No moon can be offered: every Risk Level in the Moon Pool has weight 0. Only the Company building is available.");
			}
			list5.AddRange(list);
			string text = DescribeUnlisted(list2, moonPool);
			if (text.Length > 0)
			{
				list5.Add("Risk Level weights: no weight listed for " + text + ", so they use the Other Risk Levels " + $"weight ({quotaValues.OtherWeight}).");
			}
			ShipMove ship = ShipMove.Stay;
			string shipDestination = null;
			if (input.ShipMoon != null && !list4.Contains(input.ShipMoon))
			{
				if (list4.Count == 0)
				{
					ship = ShipMove.MoveToCompanyBuilding;
				}
				else
				{
					ship = ShipMove.MoveToOfferedMoon;
					shipDestination = list4[RandomBelow(list4.Count)];
				}
			}
			return new DrawResult(list4, dictionary, ship, shipDestination, list5);
		}

		private static QuotaValues CurrentSettings(DrawInput input, List<string> malformed)
		{
			QuotaValues quotaValues = new QuotaValues(Math.Max(0, input.OfferedMoons), Math.Max(0, input.OtherRiskLevelsWeight), ParseWeights(input.RiskLevelWeights, "[Defaults]", malformed));
			int num = Math.Min(Math.Max(1, input.Quota), input.QuotaSettings.Count);
			for (int i = 0; i < num; i++)
			{
				QuotaSettings quotaSettings = input.QuotaSettings[i];
				string text = $"[Quota {i + 1}]";
				quotaValues.OfferedMoons = ParseQuotaNumber(quotaSettings.OfferedMoons, text + " Offered Moons", malformed) ?? quotaValues.OfferedMoons;
				quotaValues.OtherWeight = ParseQuotaNumber(quotaSettings.OtherRiskLevelsWeight, text + " Other Risk Levels weight", malformed) ?? quotaValues.OtherWeight;
				if (quotaSettings.RiskLevelWeights.Trim() == "-1")
				{
					continue;
				}
				Dictionary<string, int> dictionary = ParseWeights(quotaSettings.RiskLevelWeights, text, malformed);
				if (dictionary.Count == 0)
				{
					continue;
				}
				if ((quotaSettings.Mode ?? input.DefaultQuotaMode) == QuotaMode.Replace)
				{
					quotaValues.Weights.Clear();
				}
				foreach (KeyValuePair<string, int> item in dictionary)
				{
					quotaValues.Weights[item.Key] = item.Value;
				}
			}
			return quotaValues;
		}

		private static int? ParseQuotaNumber(string text, string setting, List<string> malformed)
		{
			string text2 = text.Trim();
			if (text2.Length == 0 || text2 == "-1")
			{
				return null;
			}
			if (int.TryParse(text2, NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			malformed.Add(setting + ": ignoring \"" + text2 + "\", which is neither a whole number of 0 or more nor -1 (or empty) to use the earlier Quota's.");
			return null;
		}

		private static Dictionary<string, int> ParseWeights(string text, string section, List<string> malformed)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
			List<string> list = new List<string>();
			string[] array = text.Split(',');
			foreach (string text2 in array)
			{
				string text3 = text2.Trim();
				if (text3.Length != 0)
				{
					string[] array2 = text3.Split('=');
					string text4 = array2[0].Trim();
					if (array2.Length == 2 && text4.Length > 0 && !dictionary.ContainsKey(text4) && int.TryParse(array2[1].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var result))
					{
						dictionary.Add(text4, result);
					}
					else
					{
						list.Add(text3);
					}
				}
			}
			if (list.Count > 0)
			{
				malformed.Add(section + " Risk Level weights: ignoring \"" + string.Join("\", \"", list) + "\". Each entry is a Risk Level listed once, \"=\" and a whole number of 0 or more, such as D=1.");
			}
			return dictionary;
		}

		private static List<RiskLevel> RiskLevels(IReadOnlyList<PoolMoon> pool, Dictionary<string, int> weights, int otherWeight)
		{
			List<RiskLevel> list = new List<RiskLevel>();
			Dictionary<string, RiskLevel> dictionary = new Dictionary<string, RiskLevel>(StringComparer.OrdinalIgnoreCase);
			for (int i = 0; i < pool.Count; i++)
			{
				string text = pool[i].RiskLevel.Trim();
				if (!dictionary.TryGetValue(text, out var value))
				{
					int value2;
					bool flag = weights.TryGetValue(text, out value2);
					value = new RiskLevel(text, flag ? value2 : otherWeight, flag);
					dictionary.Add(text, value);
					list.Add(value);
				}
				value.Moons.Add(i);
			}
			return list;
		}

		private static string DescribeUnlisted(List<RiskLevel> riskLevels, IReadOnlyList<PoolMoon> pool)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (RiskLevel riskLevel in riskLevels)
			{
				if (riskLevel.IsListed)
				{
					continue;
				}
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(", ");
				}
				stringBuilder.Append((riskLevel.Name.Length > 0) ? riskLevel.Name : "(blank)").Append(" (");
				for (int i = 0; i < riskLevel.Moons.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(", ");
					}
					stringBuilder.Append(pool[riskLevel.Moons[i]].Key);
				}
				stringBuilder.Append(')');
			}
			return stringBuilder.ToString();
		}

		private void SharePicks(List<RiskLevel> riskLevels, int picks)
		{
			List<long> list = new List<long>(riskLevels.Count);
			while (picks > 0)
			{
				long num = 0L;
				foreach (RiskLevel riskLevel in riskLevels)
				{
					if (riskLevel.CanTakeMorePicks)
					{
						num += riskLevel.Weight;
					}
				}
				if (num == 0L)
				{
					break;
				}
				int num2 = picks;
				int num3 = num2;
				list.Clear();
				foreach (RiskLevel riskLevel2 in riskLevels)
				{
					long item = 0L;
					if (riskLevel2.CanTakeMorePicks)
					{
						long num4 = (long)num2 * (long)riskLevel2.Weight;
						int num5 = (int)(num4 / num);
						num3 -= num5;
						int num6 = Math.Min(num5, riskLevel2.Room);
						riskLevel2.Picks += num6;
						picks -= num6;
						if (riskLevel2.CanTakeMorePicks)
						{
							item = num4 % num;
						}
					}
					list.Add(item);
				}
				while (num3 > 0)
				{
					int num7 = RandomWeighted(list);
					if (num7 < 0)
					{
						break;
					}
					riskLevels[num7].Picks++;
					picks--;
					list[num7] = 0L;
					num3--;
				}
			}
		}

		private List<int> PickMoons(RiskLevel riskLevel, IReadOnlyList<PoolMoon> pool, int guaranteedAfter)
		{
			List<int> list = new List<int>(riskLevel.Moons);
			List<long> list2 = new List<long>(list.Count);
			foreach (int item in list)
			{
				list2.Add(Absence(pool[item]));
			}
			List<int> list3 = new List<int>(riskLevel.Picks);
			for (int i = 0; i < riskLevel.Picks; i++)
			{
				int num = LongestGuaranteed(list2, guaranteedAfter);
				if (num < 0)
				{
					num = RandomWeighted(list2);
				}
				if (num < 0)
				{
					num = RandomBelow(list.Count);
				}
				list3.Add(list[num]);
				list.RemoveAt(num);
				list2.RemoveAt(num);
			}
			return list3;
		}

		private int LongestGuaranteed(List<long> absences, int guaranteedAfter)
		{
			long num = guaranteedAfter;
			int num2 = 0;
			foreach (long absence in absences)
			{
				if (absence > num)
				{
					num = absence;
					num2 = 1;
				}
				else if (absence == num)
				{
					num2++;
				}
			}
			if (num2 == 0)
			{
				return -1;
			}
			int num3 = RandomBelow(num2);
			for (int i = 0; i < absences.Count; i++)
			{
				if (absences[i] == num && num3-- == 0)
				{
					return i;
				}
			}
			return -1;
		}

		private static int Absence(PoolMoon moon)
		{
			return Math.Max(0, moon.Absence);
		}

		private int RandomWeighted(List<long> weights)
		{
			long num = 0L;
			foreach (long weight in weights)
			{
				num += weight;
			}
			if (num == 0L)
			{
				return -1;
			}
			long num2 = Math.Min(num - 1, (long)(_random() * (double)num));
			for (int i = 0; i < weights.Count; i++)
			{
				if (num2 < weights[i])
				{
					return i;
				}
				num2 -= weights[i];
			}
			return -1;
		}

		private int RandomBelow(int count)
		{
			return Math.Min(count - 1, (int)(_random() * (double)count));
		}
	}
	public sealed class DrawResult
	{
		public IReadOnlyList<string> OfferedMoons { get; }

		public IReadOnlyDictionary<string, int> Absences { get; }

		public ShipMove Ship { get; }

		public string? ShipDestination { get; }

		public IReadOnlyList<string> Warnings { get; }

		internal DrawResult(IReadOnlyList<string> offeredMoons, IReadOnlyDictionary<string, int> absences, ShipMove ship, string? shipDestination, IReadOnlyList<string> warnings)
		{
			OfferedMoons = offeredMoons;
			Absences = absences;
			Ship = ship;
			ShipDestination = shipDestination;
			Warnings = warnings;
		}
	}
	public sealed class PoolMoon
	{
		public string Key { get; }

		public string RiskLevel { get; }

		public int Absence { get; }

		public PoolMoon(string key, string riskLevel, int absence = 1)
		{
			Key = key;
			RiskLevel = riskLevel;
			Absence = absence;
		}
	}
	public enum QuotaMode
	{
		Merge,
		Replace
	}
	public sealed class QuotaSettings
	{
		public string OfferedMoons { get; set; } = "";

		public string RiskLevelWeights { get; set; } = "";

		public string OtherRiskLevelsWeight { get; set; } = "";

		public QuotaMode? Mode { get; set; }
	}
	public sealed class SavedOffer
	{
		public IReadOnlyList<string> OfferedMoons { get; }

		public IReadOnlyDictionary<string, int> Absences { get; }

		public SavedOffer(IReadOnlyList<string> offeredMoons, IReadOnlyDictionary<string, int> absences)
		{
			OfferedMoons = offeredMoons;
			Absences = absences;
		}

		public SavedOffer Restore(IEnumerable<string> moons)
		{
			HashSet<string> hashSet = new HashSet<string>(moons);
			List<string> list = new List<string>(OfferedMoons.Count);
			foreach (string offeredMoon in OfferedMoons)
			{
				if (hashSet.Contains(offeredMoon))
				{
					list.Add(offeredMoon);
				}
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>(Absences.Count);
			foreach (KeyValuePair<string, int> absence in Absences)
			{
				if (hashSet.Contains(absence.Key))
				{
					dictionary.Add(absence.Key, absence.Value);
				}
			}
			return new SavedOffer(list, dictionary);
		}

		public (ShipMove Ship, string? Destination) MoveShip(string? shipMoon, IEnumerable<string> lockedMoons)
		{
			if (shipMoon == null)
			{
				return (Ship: ShipMove.Stay, Destination: null);
			}
			foreach (string offeredMoon in OfferedMoons)
			{
				if (offeredMoon == shipMoon)
				{
					return (Ship: ShipMove.Stay, Destination: null);
				}
			}
			HashSet<string> hashSet = new HashSet<string>(lockedMoons);
			foreach (string offeredMoon2 in OfferedMoons)
			{
				if (!hashSet.Contains(offeredMoon2))
				{
					return (Ship: ShipMove.MoveToOfferedMoon, Destination: offeredMoon2);
				}
			}
			return (Ship: ShipMove.MoveToCompanyBuilding, Destination: null);
		}
	}
	public enum ShipMove
	{
		Stay,
		MoveToOfferedMoon,
		MoveToCompanyBuilding
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}