Decompiled source of MonitorTakeover v1.1.1

Y4NGZMonitorTakeover.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;
using Y4NGZCompany.Bootstrap;
using Y4NGZCompany.Core;
using Y4NGZCompany.Core.Compat;
using Y4NGZCompany.Experience.UITheme;
using Y4NGZCompany.ShipSystems.MonitorRow;
using Y4NGZCompany.ShipSystems.Rendering;
using Y4NGZCompany.ShipSystems.Takeover;
using Y4NGZCore.Assets;
using Y4NGZCore.Configuration;
using Y4NGZCore.Diagnostics;
using Y4NGZCore.Lifecycle;
using Y4NGZCore.Modules;
using Y4NGZCore.Modules.Layout;
using Y4NGZCore.Modules.Monitor;
using Y4NGZCore.Modules.Net;
using Y4NGZCore.Modules.Quota;
using Y4NGZCore.Modules.Routes;
using Y4NGZCore.Modules.ShipSystems;
using Y4NGZCore.Saves;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("DunGen")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.ASPP")]
[assembly: IgnoresAccessChecksTo("DunGen.Integration.UnityNav")]
[assembly: IgnoresAccessChecksTo("EasyTextEffects")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.CoreUtils")]
[assembly: IgnoresAccessChecksTo("Unity.XR.Management")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.ConformanceAutomation")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MetaQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MockRuntime")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.OculusQuestSupport")]
[assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.RuntimeDebugger")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpatialTracking")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XR.LegacyInputHelpers")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Y4NGZMonitorTakeover")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Y4NGZ monitor takeover: the quota milestone registry and its rewards, milestone unlock gating, the quota announcement, and the monitor takeover presentation")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+38739fda0b7b0ab0694c3812be04d03f93bb96ff")]
[assembly: AssemblyProduct("Y4NGZMonitorTakeover")]
[assembly: AssemblyTitle("Y4NGZMonitorTakeover")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Y4NGZCore.Modules.Quota
{
	public readonly struct QuotaRolloverFinalized
	{
		public readonly int CompletedQuotaCount;

		public readonly int ProfitQuotaBefore;

		public readonly int QuotaFulfilledBefore;

		public readonly int ProfitQuotaAfter;

		public readonly int DaysUntilDeadlineAfter;

		public readonly int ObjectiveOutcomeDelta;

		public readonly bool OutcomeCountedTowardQuota;

		public QuotaRolloverFinalized(int completedQuotaCount, int profitQuotaBefore, int quotaFulfilledBefore, int profitQuotaAfter, int daysUntilDeadlineAfter, int objectiveOutcomeDelta, bool outcomeCountedTowardQuota)
		{
			CompletedQuotaCount = completedQuotaCount;
			ProfitQuotaBefore = profitQuotaBefore;
			QuotaFulfilledBefore = quotaFulfilledBefore;
			ProfitQuotaAfter = profitQuotaAfter;
			DaysUntilDeadlineAfter = daysUntilDeadlineAfter;
			ObjectiveOutcomeDelta = objectiveOutcomeDelta;
			OutcomeCountedTowardQuota = outcomeCountedTowardQuota;
		}
	}
	public static class QuotaRolloverNotifications
	{
		private static readonly object Gate = new object();

		private static int _lastPublishedQuotaCount = int.MinValue;

		private static bool _hasPublished;

		private static QuotaRolloverFinalized _lastPublished;

		public static bool HasPublished
		{
			get
			{
				lock (Gate)
				{
					return _hasPublished;
				}
			}
		}

		public static QuotaRolloverFinalized LastPublished
		{
			get
			{
				lock (Gate)
				{
					return _lastPublished;
				}
			}
		}

		public static event Action<QuotaRolloverFinalized> QuotaRolloverFinalized;

		public static bool PublishQuotaRolloverFinalized(QuotaRolloverFinalized payload)
		{
			lock (Gate)
			{
				if (_hasPublished && payload.CompletedQuotaCount <= _lastPublishedQuotaCount)
				{
					return false;
				}
				_hasPublished = true;
				_lastPublishedQuotaCount = payload.CompletedQuotaCount;
				_lastPublished = payload;
			}
			Action<QuotaRolloverFinalized> quotaRolloverFinalized = QuotaRolloverNotifications.QuotaRolloverFinalized;
			if (quotaRolloverFinalized == null)
			{
				return true;
			}
			Delegate[] invocationList = quotaRolloverFinalized.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					((Action<QuotaRolloverFinalized>)obj)(payload);
				}
				catch (Exception ex)
				{
					ModuleDiagnostics.Warn("[QuotaRollover] Subscriber failed for completed quota " + $"{payload.CompletedQuotaCount}: {ex.GetType().Name}: {ex.Message}");
				}
			}
			return true;
		}

		public static void ResetRunState()
		{
			lock (Gate)
			{
				_hasPublished = false;
				_lastPublishedQuotaCount = int.MinValue;
				_lastPublished = default(QuotaRolloverFinalized);
			}
			QuotaRolloverOutcomeStaging.ResetRunState();
		}

		public static void ResetForTests()
		{
			QuotaRolloverNotifications.QuotaRolloverFinalized = null;
			ResetRunState();
		}
	}
	public static class QuotaTakeoverHandoff
	{
		private static bool _quotaJustCompleted;

		public static bool QuotaJustCompleted
		{
			get
			{
				return _quotaJustCompleted;
			}
			set
			{
				Assign(ref _quotaJustCompleted, value);
			}
		}

		public static bool AnyPending => _quotaJustCompleted;

		public static event Action Changed;

		public static void ClearAll()
		{
			QuotaJustCompleted = false;
		}

		private static void Assign(ref bool field, bool value)
		{
			if (field != value)
			{
				field = value;
				Raise();
			}
		}

		private static void Raise()
		{
			Action changed = QuotaTakeoverHandoff.Changed;
			if (changed == null)
			{
				return;
			}
			try
			{
				changed();
			}
			catch (Exception ex)
			{
				ModuleDiagnostics.WarnOnce("quota.handoff.changed", "[QuotaRollover] Takeover handoff subscriber failed: " + ex.GetType().Name + ": " + ex.Message);
			}
		}

		public static void ResetForTests()
		{
			_quotaJustCompleted = false;
			QuotaTakeoverHandoff.Changed = null;
		}
	}
}
namespace Y4NGZCompany.Core
{
	internal enum TakeoverSoundtrackMode
	{
		Off,
		Replace,
		Mix
	}
	internal readonly struct QuotaAudioChoice<T>
	{
		internal readonly T Check;

		internal readonly string Setting;

		internal readonly bool OwnRejected;

		internal readonly T OwnCheck;

		internal QuotaAudioChoice(T check, string setting, bool ownRejected, T ownCheck)
		{
			Check = check;
			Setting = setting ?? string.Empty;
			OwnRejected = ownRejected;
			OwnCheck = ownCheck;
		}
	}
	internal static class QuotaAudioKeys
	{
		internal const string AlarmKey = "AlarmFile";

		internal const string VoicesKey = "VoiceFiles";

		internal const string SoundtrackKey = "Soundtrack";

		internal static string OwnValue(bool hasSection, QuotaMode mode, string value)
		{
			if (!hasSection || !mode.UsesQuotaDialogueAndMedia())
			{
				return null;
			}
			return value;
		}

		internal static string QuotaSetting(string key, int quota)
		{
			return "[Quota " + quota.ToString(CultureInfo.InvariantCulture) + "] " + key;
		}

		internal static string PublishedSetting(string key, int quota)
		{
			if (quota <= 0)
			{
				return key;
			}
			return key + " for quota " + quota.ToString(CultureInfo.InvariantCulture);
		}

		internal static QuotaAudioChoice<T> Pick<T>(string key, int quota, string ownValue, string globalValue, Func<string, string, T> check, Func<T, bool> usable)
		{
			if (string.IsNullOrWhiteSpace(ownValue))
			{
				return new QuotaAudioChoice<T>(check(key, globalValue ?? string.Empty), key, ownRejected: false, default(T));
			}
			string text = QuotaSetting(key, quota);
			T val = check(text, ownValue);
			if (usable(val))
			{
				return new QuotaAudioChoice<T>(val, text, ownRejected: false, default(T));
			}
			return new QuotaAudioChoice<T>(check(key, globalValue ?? string.Empty), key, ownRejected: true, val);
		}

		internal static bool PickSoundtrack<T>(TakeoverSoundtrackMode mode, int quota, string ownValue, string globalValue, Func<string, string, T> check, Func<T, bool> usable, out QuotaAudioChoice<T> choice)
		{
			if (mode == TakeoverSoundtrackMode.Off)
			{
				choice = default(QuotaAudioChoice<T>);
				return false;
			}
			choice = Pick("Soundtrack", quota, ownValue, globalValue, check, usable);
			return true;
		}
	}
	internal static class QuotaDeadlineMath
	{
		internal const float OtherModRateTolerance = 0.0001f;

		internal static int PeriodQuotaAfterRollover(int timesFulfilledQuota)
		{
			return timesFulfilledQuota + 1;
		}

		internal static int? PeriodStartedByRollover(int timesFulfilledBefore, int timesFulfilledAfter)
		{
			if (!QuotaRolloverCheck.QuotaAdvanced(timesFulfilledBefore, timesFulfilledAfter))
			{
				return null;
			}
			return PeriodQuotaAfterRollover(timesFulfilledAfter);
		}

		internal static float? DeadlineSeconds(float totalTime, int days)
		{
			days = QuotaMilestoneGrantParser.ClampDeadlineDays(days);
			if (days <= 0)
			{
				return null;
			}
			return totalTime * (float)days;
		}

		internal static float? BuyingRate(int days, int daysUntilDeadline)
		{
			if (days <= 0)
			{
				return null;
			}
			if (daysUntilDeadline <= 0)
			{
				return 1f;
			}
			float num = 0.7f / (float)days * (float)(days - daysUntilDeadline) + 0.3f;
			return (num < 0.3f) ? 0.3f : ((num > 1f) ? 1f : num);
		}

		internal static float VanillaBuyingRate(int deadlineDaysAmount, int daysUntilDeadline)
		{
			if (daysUntilDeadline == 0)
			{
				return 1f;
			}
			float num = 0.3f;
			return (1f - num) / (float)deadlineDaysAmount * (float)(deadlineDaysAmount - daysUntilDeadline) + num;
		}

		internal static bool TryPriceDay(bool vanillaPriced, int windowDays, int deadlineDaysAmount, int daysUntilDeadline, ref float rate, ref int pricedWindow)
		{
			if (!vanillaPriced)
			{
				return false;
			}
			float? num = BuyingRate(windowDays, daysUntilDeadline);
			pricedWindow = (num.HasValue ? windowDays : 0);
			if (!num.HasValue)
			{
				return false;
			}
			float num2 = rate - VanillaBuyingRate(deadlineDaysAmount, daysUntilDeadline);
			rate = ((float.IsNaN(num2) || float.IsInfinity(num2) || Math.Abs(num2) < 0.0001f) ? num.Value : (num.Value + num2));
			return true;
		}
	}
	[HarmonyPatch]
	internal static class QuotaDeadlinePatch
	{
		private const int FirstQuotaPeriod = 1;

		private const int PricingPriority = -10;

		private static bool _resyncAfterFiredSequence;

		private static QuotaDeadlineWindowRecord _appliedWindow;

		private static int _lastPricedWindow;

		[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static void BeforeSetNewProfitQuota(TimeOfDay __instance, out int __state)
		{
			__state = (((Object)(object)__instance != (Object)null) ? __instance.timesFulfilledQuota : 0);
		}

		[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
		[HarmonyPostfix]
		[HarmonyPriority(500)]
		private static void AfterSetNewProfitQuota(TimeOfDay __instance, int __state)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer)
				{
					return;
				}
				int? num = QuotaDeadlineMath.PeriodStartedByRollover(__state, __instance.timesFulfilledQuota);
				if (num.HasValue)
				{
					int value = num.Value;
					int num2 = QuotaProgressionRegistry.HostDeadlineDaysForPeriod(value);
					bool flag = TryApplyDeadline(__instance, num2);
					_appliedWindow = new QuotaDeadlineWindowRecord(value, flag ? num2 : 0);
					if (flag)
					{
						__instance.SyncTimeClientRpc(__instance.globalTime, (int)__instance.timeUntilDeadline);
						ModuleLog.Takeover.LogInfo((object)$"[QuotaDeadline] Quota {value} deadline set to {num2} days.");
					}
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSetNewProfitQuota: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SetTimeAndPlanetToSavedSettings")]
		[HarmonyPrefix]
		private static void BeforeSetTimeAndPlanetToSavedSettings(StartOfRound __instance, out bool __state)
		{
			__state = false;
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				if (!((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsServer && !((Object)(object)instance == (Object)null))
				{
					__state = !ES3.KeyExists("DeadlineTime", instance.currentSaveFileName);
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.BeforeSetTimeAndPlanetToSavedSettings: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SetTimeAndPlanetToSavedSettings")]
		[HarmonyPostfix]
		private static void AfterSetTimeAndPlanetToSavedSettings(StartOfRound __instance, bool __state)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer)
				{
					return;
				}
				TakeoverRoutePolicy.OnHostSaveLoaded();
				TimeOfDay instance = TimeOfDay.Instance;
				if (__instance.isChallengeFile || (Object)(object)instance == (Object)null)
				{
					return;
				}
				if (__state)
				{
					int num = QuotaProgressionRegistry.HostDeadlineDaysForPeriod(1);
					bool flag = TryApplyDeadline(instance, num);
					_appliedWindow = new QuotaDeadlineWindowRecord(1, flag ? num : 0);
					if (flag)
					{
						ModuleLog.Takeover.LogInfo((object)$"[QuotaDeadline] New save: quota 1 deadline set to {num} days.");
					}
				}
				instance.SetBuyingRateForDay();
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSetTimeAndPlanetToSavedSettings: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		[HarmonyPostfix]
		private static void AfterResetShip(StartOfRound __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer)
				{
					return;
				}
				TakeoverRoutePolicy.ClearForcedRoute("the crew was fired");
				TimeOfDay instance = TimeOfDay.Instance;
				if (!__instance.isChallengeFile && !((Object)(object)instance == (Object)null))
				{
					int num = QuotaProgressionRegistry.HostDeadlineDaysForPeriod(1);
					bool flag = TryApplyDeadline(instance, num);
					_appliedWindow = new QuotaDeadlineWindowRecord(1, flag ? num : 0);
					instance.SetBuyingRateForDay();
					if (flag)
					{
						instance.SyncTimeClientRpc(instance.globalTime, (int)instance.timeUntilDeadline);
						_resyncAfterFiredSequence = true;
						ModuleLog.Takeover.LogInfo((object)$"[QuotaDeadline] Fired: quota 1 deadline set to {num} days.");
					}
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterResetShip: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "EndPlayersFiredSequenceClientRpc")]
		[HarmonyPostfix]
		private static void AfterEndPlayersFiredSequence(StartOfRound __instance)
		{
			try
			{
				if (_resyncAfterFiredSequence && !((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsServer)
				{
					_resyncAfterFiredSequence = false;
					TimeOfDay instance = TimeOfDay.Instance;
					if ((Object)(object)instance != (Object)null)
					{
						instance.SyncTimeClientRpc(instance.globalTime, (int)instance.timeUntilDeadline);
					}
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterEndPlayersFiredSequence: {arg}");
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
		[HarmonyPostfix]
		private static void AfterSaveGameValues(GameNetworkManager __instance)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				TimeOfDay instance2 = TimeOfDay.Instance;
				if (!((Object)(object)__instance == (Object)null) && __instance.isHostingGame && !((Object)(object)instance == (Object)null) && !((Object)(object)instance2 == (Object)null) && !instance.isChallengeFile && instance.inShipPhase && !instance.beganLoadingNewLevel && (!((Object)(object)RoundManager.Instance != (Object)null) || !RoundManager.Instance.dungeonIsGenerating))
				{
					int period = QuotaDeadlineMath.PeriodQuotaAfterRollover(instance2.timesFulfilledQuota);
					TakeoverRoutePolicy.PersistDeadlineWindow(_appliedWindow.For(period));
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSaveGameValues: {arg}");
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")]
		[HarmonyPostfix]
		private static void AfterResetSavedGameValues(GameNetworkManager __instance)
		{
			try
			{
				if ((Object)(object)__instance != (Object)null && __instance.isHostingGame)
				{
					TakeoverRoutePolicy.PersistDeadlineWindow(default(QuotaDeadlineWindowRecord));
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterResetSavedGameValues: {arg}");
			}
		}

		[HarmonyPatch(typeof(TimeOfDay), "SyncTimeClientRpc")]
		[HarmonyPostfix]
		private static void AfterSyncTime(TimeOfDay __instance)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)StartOfRound.Instance == (Object)null))
				{
					if (!((NetworkBehaviour)__instance).IsServer)
					{
						__instance.UpdateProfitQuotaCurrentTime();
					}
					RepriceInOrbit(__instance);
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSyncTime: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
		[HarmonyPostfix]
		private static void AfterSetShipReadyToLand()
		{
			try
			{
				RepriceInOrbit(TimeOfDay.Instance);
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSetShipReadyToLand: {arg}");
			}
		}

		[HarmonyPatch(typeof(TimeOfDay), "SetBuyingRateForDay")]
		[HarmonyPostfix]
		[HarmonyPriority(-10)]
		private static void AfterSetBuyingRateForDay(TimeOfDay __instance, bool __runOriginal)
		{
			try
			{
				StartOfRound instance = StartOfRound.Instance;
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)instance == (Object)null) && !instance.isChallengeFile)
				{
					int days;
					int windowDays = (TryGetActiveWindowDays(__instance, out days) ? days : 0);
					int deadlineDaysAmount = ((__instance.quotaVariables != null) ? __instance.quotaVariables.deadlineDaysAmount : 0);
					float rate = instance.companyBuyingRate;
					if (QuotaDeadlineMath.TryPriceDay(__runOriginal, windowDays, deadlineDaysAmount, __instance.daysUntilDeadline, ref rate, ref _lastPricedWindow))
					{
						instance.companyBuyingRate = rate;
					}
				}
			}
			catch (Exception arg)
			{
				ModuleLog.Takeover.LogError((object)$"QuotaDeadlinePatch.AfterSetBuyingRateForDay: {arg}");
			}
		}

		internal static void RepriceInOrbit(TimeOfDay timeOfDay)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)timeOfDay == (Object)null) && !((Object)(object)instance == (Object)null) && instance.inShipPhase && !instance.isChallengeFile && !(timeOfDay.totalTime <= 0f) && TryGetActiveWindowDays(timeOfDay, out var days) && (days > 0 || _lastPricedWindow > 0))
			{
				timeOfDay.SetBuyingRateForDay();
			}
		}

		private static bool TryGetActiveWindowDays(TimeOfDay timeOfDay, out int days)
		{
			if (((NetworkBehaviour)timeOfDay).IsServer)
			{
				days = HostPricingWindowDays(QuotaDeadlineMath.PeriodQuotaAfterRollover(timeOfDay.timesFulfilledQuota));
				return true;
			}
			days = (QuotaPeriodState.HasHostDeadlineDays ? QuotaPeriodState.HostDeadlineDays : 0);
			return QuotaPeriodState.HasHostDeadlineDays;
		}

		internal static int HostActivePricingWindowDays()
		{
			TimeOfDay instance = TimeOfDay.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return 0;
			}
			return HostPricingWindowDays(QuotaDeadlineMath.PeriodQuotaAfterRollover(instance.timesFulfilledQuota));
		}

		internal static int HostPricingWindowDays(int periodQuota)
		{
			TimeOfDay instance = TimeOfDay.Instance;
			int vanillaDeadlineDays = (((Object)(object)instance != (Object)null && instance.quotaVariables != null) ? instance.quotaVariables.deadlineDaysAmount : 0);
			return QuotaPeriodState.PricingWindowDays(_appliedWindow.DaysFor(periodQuota), HostHasAnyDeadlineWindow(), vanillaDeadlineDays);
		}

		internal static void RestoreAppliedWindow(QuotaDeadlineWindowRecord record)
		{
			_appliedWindow = record;
		}

		private static bool HostHasAnyDeadlineWindow()
		{
			for (int i = 1; i < 10; i++)
			{
				if (QuotaProgressionRegistry.HostDeadlineDaysForPeriod(i) > 0)
				{
					return true;
				}
			}
			return false;
		}

		private static bool TryApplyDeadline(TimeOfDay timeOfDay, int days)
		{
			if (timeOfDay.totalTime <= 0f)
			{
				return false;
			}
			float? num = QuotaDeadlineMath.DeadlineSeconds(timeOfDay.totalTime, days);
			if (!num.HasValue)
			{
				return false;
			}
			timeOfDay.timeUntilDeadline = num.Value;
			timeOfDay.UpdateProfitQuotaCurrentTime();
			return true;
		}
	}
	internal readonly struct QuotaItemGrant
	{
		public readonly string Name;

		public readonly int Count;

		public QuotaItemGrant(string name, int count)
		{
			Name = name;
			Count = count;
		}
	}
	internal static class QuotaMilestoneGrantParser
	{
		internal const int MaxDeadlineDays = 14;

		internal const int MaxItemCount = 20;

		internal static int ClampDeadlineDays(int days)
		{
			if (days >= 0)
			{
				if (days <= 14)
				{
					return days;
				}
				return 14;
			}
			return 0;
		}

		internal static IReadOnlyList<QuotaItemGrant> ParseItems(string raw, Action<string> warn)
		{
			List<QuotaItemGrant> list = new List<QuotaItemGrant>();
			if (string.IsNullOrWhiteSpace(raw))
			{
				return list;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = raw.Split(';');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				string text2 = text;
				int result = 1;
				int num = text.IndexOf('|');
				if (num >= 0)
				{
					text2 = text.Substring(0, num).Trim();
					string text3 = text.Substring(num + 1).Trim();
					if (!int.TryParse(text3, NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
					{
						Warn(warn, "GrantItems", text, "count '" + text3 + "' is not a whole number");
						continue;
					}
					if (result < 1 || result > 20)
					{
						Warn(warn, "GrantItems", text, "count must be 1-" + 20.ToString(CultureInfo.InvariantCulture));
						continue;
					}
				}
				if (text2.Length == 0)
				{
					Warn(warn, "GrantItems", text, "item name is blank");
				}
				else if (text2.IndexOf(':') >= 0)
				{
					Warn(warn, "GrantItems", text, "item name must not contain ':'");
				}
				else if (!hashSet.Add(text2))
				{
					Warn(warn, "GrantItems", text, "duplicate item name (first entry wins)");
				}
				else
				{
					list.Add(new QuotaItemGrant(text2, result));
				}
			}
			return list;
		}

		internal static IReadOnlyList<string> ParseUpgrades(string raw, Action<string> warn)
		{
			List<string> list = new List<string>();
			if (string.IsNullOrWhiteSpace(raw))
			{
				return list;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = raw.Split(';');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					if (text.IndexOf(':') >= 0)
					{
						Warn(warn, "GrantShipUpgrade", text, "upgrade name must not contain ':'");
					}
					else if (!hashSet.Add(text))
					{
						Warn(warn, "GrantShipUpgrade", text, "duplicate upgrade name");
					}
					else
					{
						list.Add(text);
					}
				}
			}
			return list;
		}

		internal static string NormalizeRouteName(string raw)
		{
			if (raw != null)
			{
				return raw.Trim();
			}
			return string.Empty;
		}

		private static void Warn(Action<string> warn, string key, string entry, string reason)
		{
			warn?.Invoke(key + " entry '" + entry + "' skipped: " + reason);
		}
	}
	internal sealed class QuotaMilestoneOptions
	{
		private string _routeName = string.Empty;

		internal ConfigEntry<int> DeadlineDays { get; private set; }

		internal ConfigEntry<string> ForceRoute { get; private set; }

		internal QuotaGrantLists Grants { get; private set; }

		internal ConfigEntry<string> AlarmFile { get; private set; }

		internal ConfigEntry<string> VoiceFiles { get; private set; }

		internal ConfigEntry<string> Soundtrack { get; private set; }

		internal int EffectiveDeadlineDays => QuotaMilestoneGrantParser.ClampDeadlineDays(DeadlineDays.Value);

		internal string ForcedRouteName => _routeName;

		private QuotaMilestoneOptions()
		{
		}

		internal static ConfigEntry<QuotaMode> BindMode(ConfigFile config, string section, ManualLogSource log)
		{
			ConfigEntry<QuotaMode> val = config.Bind<QuotaMode>(section, "Mode", QuotaMode.TakeoverAndRewards, "What completing this quota does.\nTakeoverAndRewards: the monitor takeover plays, then the reward screen shows this quota's rewards and unlocks.\nRewardsOnly: no takeover; the rewards and unlocks still apply, and the reward screen shows when the ship reaches orbit.\nTakeoverOnly: the takeover plays with this quota's own dialogue and media; this quota grants and unlocks nothing and adds nothing to the reward screen.\nNothing: no takeover, rewards, unlocks or reward screen.\nWhile EnableQuotaProgression is off, every quota plays the takeover, whatever its Mode, but pays no rewards, and its reward screen shows only another mod's constellation unlocks, if any.");
			if (!Enum.IsDefined(typeof(QuotaMode), val.Value))
			{
				if (log != null)
				{
					log.LogWarning((object)$"[{section}] Mode value {(int)val.Value} is not TakeoverAndRewards, RewardsOnly, TakeoverOnly or Nothing; using TakeoverAndRewards.");
				}
				val.Value = (QuotaMode)((ConfigEntryBase)val).DefaultValue;
			}
			return val;
		}

		internal static ConfigEntry<string> BindName(ConfigFile config, string section)
		{
			return config.Bind<string>(section, "Name", string.Empty, "Shown in capitals as the reward screen's title, with QUOTA N under it. Blank shows QUOTA N. A long name is shrunk to fit, then ends in an ellipsis.");
		}

		internal static ConfigEntry<int> BindGrantTokensPerPlayer(ConfigFile config, string section, string description = "Tokens granted once per eligible player through Y4NGZUpgrades.")
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return config.Bind<int>(section, "GrantTokensPerPlayer", 0, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>()));
		}

		internal static ConfigEntry<int> BindGrantGroupCredits(ConfigFile config, string section, string description = "Group credits granted once when this quota completes.")
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			return config.Bind<int>(section, "GrantGroupCredits", 100, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100000), Array.Empty<object>()));
		}

		internal static ConfigEntry<float> BindGrantShipFuel(ConfigFile config, string section, string description = "Ship fuel granted once when this quota completes.")
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			return config.Bind<float>(section, "GrantShipFuel", 0f, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f), Array.Empty<object>()));
		}

		internal static QuotaMilestoneOptions Bind(ConfigFile config, string section, Action<string> warn)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			QuotaMilestoneOptions options = new QuotaMilestoneOptions();
			options.DeadlineDays = config.Bind<int>(section, "DeadlineDays", 0, new ConfigDescription("Days the crew gets to meet this quota. 0 uses the game's own deadline. Quota 1 applies on a new save and after being fired; later quotas apply when the previous quota is completed. Used only when Mode is TakeoverAndRewards or RewardsOnly.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 14), Array.Empty<object>()));
			options.ForceRoute = config.Bind<string>(section, "ForceRoute", string.Empty, "Moon name as the terminal shows it (for example Titan). After this quota's ceremony the only allowed route is that moon until the crew lands there once. Empty means no forced route; an unknown name is logged and ignored. Used only when Mode is TakeoverAndRewards or RewardsOnly.");
			options.Grants = QuotaGrantLists.Bind(config, section, "Items placed in the ship on the next landing after this quota is completed, as Name|count;Name|count (a bare Name means 1, count 1-20). Empty grants nothing; bad or duplicate entries are logged and skipped. Used only when Mode is TakeoverAndRewards or RewardsOnly.", "Ship upgrades granted for free (one level each) when this quota is completed, as Name;Name. Empty grants nothing; bad or duplicate entries are logged and skipped. Used only when Mode is TakeoverAndRewards or RewardsOnly.", warn);
			options.AlarmFile = config.Bind<string>(section, "AlarmFile", string.Empty, "This quota's own alarm: one MP3, WAV or OGG file (at most 32 MiB) in BepInEx/config/Y4NGZCompany/MonitorTakeovers, as AlarmFile in [Audio]. Blank, or a file the host cannot use, uses AlarmFile from [Audio].");
			options.VoiceFiles = config.Bind<string>(section, "VoiceFiles", string.Empty, "This quota's own voice clips, as VoiceFiles in [Audio]. Blank, or a list with no file the host can use, uses VoiceFiles from [Audio].");
			options.Soundtrack = config.Bind<string>(section, "Soundtrack", string.Empty, "This quota's own soundtrack: a file or a full YouTube link, as Soundtrack in [Audio]. Plays only while SoundtrackMode in [Audio] is Mix or Replace, at SoundtrackVolume. Blank, or a file the host cannot use, uses Soundtrack from [Audio].");
			options.RefreshRoute();
			options.ForceRoute.SettingChanged += delegate
			{
				options.RefreshRoute();
			};
			return options;
		}

		private void RefreshRoute()
		{
			_routeName = QuotaMilestoneGrantParser.NormalizeRouteName(ForceRoute.Value);
		}
	}
	internal sealed class QuotaGrantLists
	{
		private Action<string> _warn;

		private IReadOnlyList<QuotaItemGrant> _items = Array.Empty<QuotaItemGrant>();

		private IReadOnlyList<string> _upgrades = Array.Empty<string>();

		internal ConfigEntry<string> GrantItems { get; private set; }

		internal ConfigEntry<string> GrantShipUpgrade { get; private set; }

		internal IReadOnlyList<QuotaItemGrant> Items => _items;

		internal IReadOnlyList<string> ShipUpgrades => _upgrades;

		private QuotaGrantLists()
		{
		}

		internal static QuotaGrantLists Bind(ConfigFile config, string section, string itemsDescription, string upgradesDescription, Action<string> warn)
		{
			QuotaGrantLists grants = new QuotaGrantLists
			{
				_warn = warn
			};
			grants.GrantItems = config.Bind<string>(section, "GrantItems", string.Empty, itemsDescription);
			grants.GrantShipUpgrade = config.Bind<string>(section, "GrantShipUpgrade", string.Empty, upgradesDescription);
			grants.RefreshItems();
			grants.RefreshUpgrades();
			grants.GrantItems.SettingChanged += delegate
			{
				grants.RefreshItems();
			};
			grants.GrantShipUpgrade.SettingChanged += delegate
			{
				grants.RefreshUpgrades();
			};
			return grants;
		}

		private void RefreshItems()
		{
			_items = QuotaMilestoneGrantParser.ParseItems(GrantItems.Value, _warn);
		}

		private void RefreshUpgrades()
		{
			_upgrades = QuotaMilestoneGrantParser.ParseUpgrades(GrantShipUpgrade.Value, _warn);
		}
	}
	internal sealed class QuotaRewardOptions
	{
		internal readonly ConfigEntry<int> GrantTokensPerPlayer;

		internal readonly ConfigEntry<int> GrantGroupCredits;

		internal readonly ConfigEntry<float> GrantShipFuel;

		internal readonly QuotaGrantLists Grants;

		internal QuotaRewardOptions(ConfigEntry<int> tokens, ConfigEntry<int> credits, ConfigEntry<float> fuel, QuotaGrantLists grants)
		{
			GrantTokensPerPlayer = tokens;
			GrantGroupCredits = credits;
			GrantShipFuel = fuel;
			Grants = grants;
		}

		internal QuotaRewardSpec Spec(int quota)
		{
			return new QuotaRewardSpec(quota, GrantGroupCredits.Value, GrantShipFuel.Value, GrantTokensPerPlayer.Value, Grants.Items, Grants.ShipUpgrades);
		}

		internal static QuotaRewardOptions BindRepeating(ConfigFile config, Action<string> warn)
		{
			return new QuotaRewardOptions(QuotaMilestoneOptions.BindGrantTokensPerPlayer(config, "Quotas 10 And Later", "Tokens granted once per eligible player through Y4NGZUpgrades for each completed quota from 10 on. Read live: a change applies to every quota not yet paid."), QuotaMilestoneOptions.BindGrantGroupCredits(config, "Quotas 10 And Later", "Group credits granted once for each completed quota from 10 on. Read live: a change applies to every quota not yet paid."), QuotaMilestoneOptions.BindGrantShipFuel(config, "Quotas 10 And Later", "Ship fuel granted once for each completed quota from 10 on. Read live: a change applies to every quota not yet paid."), QuotaGrantLists.Bind(config, "Quotas 10 And Later", "Items placed in the ship on the next landing after each completed quota from 10 on, as Name|count;Name|count (a bare Name means 1, count 1-20). Empty grants nothing; bad or duplicate entries are logged and skipped. Read live: a change applies to every quota not yet paid.", "Ship upgrades granted for free (one level each) for each completed quota from 10 on, as Name;Name. Empty grants nothing; bad or duplicate entries are logged and skipped. Read live: a change applies to every quota not yet paid.", warn));
		}
	}
	internal sealed class QuotaMilestoneSummary
	{
		internal int Quota;

		internal QuotaMode Mode;

		internal IReadOnlyList<string> Contracts;

		internal IReadOnlyList<string> ShipUpgrades;

		internal IReadOnlyList<string> Constellations;

		internal IReadOnlyList<string> Moons;

		internal IReadOnlyList<string> Suits;

		internal IReadOnlyList<string> StoreItems;

		internal string ForcedRouteName;

		internal QuotaRewardSpec Rewards;
	}
	internal enum QuotaMode
	{
		TakeoverAndRewards,
		RewardsOnly,
		TakeoverOnly,
		Nothing
	}
	internal static class QuotaModeEffects
	{
		internal static bool PlaysTakeover(this QuotaMode mode)
		{
			if (mode != QuotaMode.TakeoverAndRewards)
			{
				return mode == QuotaMode.TakeoverOnly;
			}
			return true;
		}

		internal static bool GrantsRewards(this QuotaMode mode)
		{
			if (mode != QuotaMode.TakeoverAndRewards)
			{
				return mode == QuotaMode.RewardsOnly;
			}
			return true;
		}

		internal static bool UsesQuotaDialogueAndMedia(this QuotaMode mode)
		{
			return mode != QuotaMode.Nothing;
		}

		internal static bool HostPlaysTakeover(bool progressionEnabled, bool hasSection, QuotaMode mode)
		{
			if (progressionEnabled && hasSection)
			{
				return mode.PlaysTakeover();
			}
			return true;
		}
	}
	internal static class QuotaPeriodState
	{
		internal static bool HasHostDeadlineDays { get; private set; }

		internal static int HostDeadlineDays { get; private set; }

		internal static bool ApplyHostDeadlineDays(int days)
		{
			days = QuotaMilestoneGrantParser.ClampDeadlineDays(days);
			bool result = !HasHostDeadlineDays || HostDeadlineDays != days;
			HostDeadlineDays = days;
			HasHostDeadlineDays = true;
			return result;
		}

		internal static void Reset()
		{
			HasHostDeadlineDays = false;
			HostDeadlineDays = 0;
		}

		internal static int PricingWindowDays(int appliedDeadlineDays, bool anyWindowConfigured, int vanillaDeadlineDays)
		{
			appliedDeadlineDays = QuotaMilestoneGrantParser.ClampDeadlineDays(appliedDeadlineDays);
			if (appliedDeadlineDays > 0)
			{
				return appliedDeadlineDays;
			}
			if (!anyWindowConfigured)
			{
				return 0;
			}
			return QuotaMilestoneGrantParser.ClampDeadlineDays(vanillaDeadlineDays);
		}
	}
	internal readonly struct QuotaDeadlineWindowRecord
	{
		internal readonly int Period;

		internal readonly int Days;

		internal QuotaDeadlineWindowRecord(int period, int days)
		{
			Period = ((period > 0) ? period : 0);
			Days = ((Period > 0) ? QuotaMilestoneGrantParser.ClampDeadlineDays(days) : 0);
		}

		internal int DaysFor(int period)
		{
			if (period <= 0 || period != Period)
			{
				return 0;
			}
			return Days;
		}

		internal QuotaDeadlineWindowRecord For(int period)
		{
			if (period <= 0 || period != Period)
			{
				return default(QuotaDeadlineWindowRecord);
			}
			return this;
		}

		internal string Encode()
		{
			return Period.ToString(CultureInfo.InvariantCulture) + ":" + Days.ToString(CultureInfo.InvariantCulture);
		}

		internal static bool TryDecode(string stored, out QuotaDeadlineWindowRecord record)
		{
			record = default(QuotaDeadlineWindowRecord);
			if (string.IsNullOrEmpty(stored))
			{
				return false;
			}
			int num = stored.IndexOf(':');
			if (num <= 0 || num != stored.LastIndexOf(':'))
			{
				return false;
			}
			if (!int.TryParse(stored.Substring(0, num), NumberStyles.None, CultureInfo.InvariantCulture, out var result) || !int.TryParse(stored.Substring(num + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var result2) || result < 1 || result2 > 14)
			{
				return false;
			}
			record = new QuotaDeadlineWindowRecord(result, result2);
			return true;
		}
	}
	public readonly struct QuotaTokenGrantRequest
	{
		public readonly int CompletedQuota;

		public readonly int TokensPerPlayer;

		public readonly string ActionId;

		public readonly bool IsReplay;

		public QuotaTokenGrantRequest(int completedQuota, int tokensPerPlayer, string actionId)
			: this(completedQuota, tokensPerPlayer, actionId, isReplay: false)
		{
		}

		public QuotaTokenGrantRequest(int completedQuota, int tokensPerPlayer, string actionId, bool isReplay)
		{
			CompletedQuota = completedQuota;
			TokensPerPlayer = tokensPerPlayer;
			ActionId = actionId ?? string.Empty;
			IsReplay = isReplay;
		}
	}
	public static class QuotaProgressionApi
	{
		public const int TokenGrantProtocolVersion = 1;

		private static Func<QuotaTokenGrantRequest, bool> _tokenGrantHandler;

		public static bool IsTokenGrantCapabilityAvailable => _tokenGrantHandler != null;

		public static void RegisterTokenGrantHandler(Func<QuotaTokenGrantRequest, bool> handler)
		{
			_tokenGrantHandler = handler;
		}

		public static void UnregisterTokenGrantHandler(Func<QuotaTokenGrantRequest, bool> handler)
		{
			if (_tokenGrantHandler == handler)
			{
				_tokenGrantHandler = null;
			}
		}

		internal static bool TryGrantTokens(QuotaTokenGrantRequest request)
		{
			if (_tokenGrantHandler != null)
			{
				return _tokenGrantHandler(request);
			}
			return false;
		}
	}
	public enum ForcedQuotaCompletionResult
	{
		StartedImmediately,
		QueuedUntilOrbit,
		HostOnly,
		InvalidQuota,
		NotInRound,
		Busy,
		Unavailable
	}
	public static class QuotaProgressionDebugApi
	{
		public static string LastResultReason { get; private set; } = string.Empty;

		public static ForcedQuotaCompletionResult ForceCompletedQuota(int completedQuota)
		{
			string reason;
			return ForceCompletedQuota(completedQuota, out reason);
		}

		public static ForcedQuotaCompletionResult ForceCompletedQuota(int completedQuota, out string reason)
		{
			ForcedQuotaCompletionResult result;
			try
			{
				result = QuotaTakeoverDebugController.ForceCompletedQuota(completedQuota, out reason);
			}
			catch (Exception ex)
			{
				ModuleLog.Takeover.LogWarning((object)$"QuotaProgressionDebugApi.ForceCompletedQuota failed: {ex}");
				result = ForcedQuotaCompletionResult.Unavailable;
				reason = "Forcing the quota failed: " + ex.Message;
			}
			reason = reason ?? string.Empty;
			LastResultReason = reason;
			return result;
		}
	}
	internal sealed class QuotaMilestoneConfig
	{
		internal readonly int Quota;

		internal readonly ConfigEntry<QuotaMode> Mode;

		internal readonly ConfigEntry<string> Name;

		internal readonly ConfigEntry<string> Dialogue;

		internal readonly ConfigEntry<string> DialogueFile;

		internal readonly ConfigEntry<string> MediaFile;

		internal readonly ConfigEntry<string> UnlockContracts;

		internal readonly ConfigEntry<string> UnlockShipUpgradePurchases;

		internal readonly ConfigEntry<string> UnlockConstellations;

		internal readonly ConfigEntry<string> UnlockMoons;

		internal readonly ConfigEntry<string> UnlockSuits;

		internal readonly ConfigEntry<string> UnlockStoreItems;

		internal readonly QuotaRewardOptions Rewards;

		internal readonly QuotaMilestoneOptions Options;

		internal IEnumerable<string> Contracts => Split(UnlockContracts.Value);

		internal IEnumerable<string> Upgrades => Split(UnlockShipUpgradePurchases.Value);

		internal IEnumerable<string> Constellations => Split(UnlockConstellations.Value);

		internal IEnumerable<string> Moons => Split(UnlockMoons.Value);

		internal IEnumerable<string> Suits => Split(UnlockSuits.Value);

		internal IEnumerable<string> StoreItems => Split(UnlockStoreItems.Value);

		internal QuotaMilestoneConfig(ConfigFile config, int quota, ManualLogSource log)
		{
			Quota = quota;
			string section = MonitorTakeoverConfigSchemaMigration.QuotaSection(quota);
			Mode = QuotaMilestoneOptions.BindMode(config, section, log);
			Name = QuotaMilestoneOptions.BindName(config, section);
			Dialogue = config.Bind<string>(section, "Dialogue", string.Empty, "Inline takeover dialogue. Use \\n for line breaks; blank uses built-in dialogue.");
			DialogueFile = config.Bind<string>(section, "DialogueFile", string.Empty, "Optional UTF-8 .txt file under BepInEx/config/Y4NGZCompany/MonitorTakeovers.");
			MediaFile = config.Bind<string>(section, "Media", string.Empty, "Video (MP4), image (PNG or JPG), or full YouTube link shown on the ship monitors when this quota is completed. A blank value first plays " + TakeoverMediaPicker.QuotaDropInName(quota) + " from BepInEx/config/Y4NGZCompany/MonitorTakeovers when that file is there, with no config edit. Blank then uses MediaForAllQuotas from the Media section, then takeover.mp4 from the same folder when that file is there, and if there is none, the built-in Y4NGZ video. Files go in BepInEx/config/Y4NGZCompany/MonitorTakeovers and every player needs an identical copy or they see the built-in video; a YouTube link is downloaded and cached by each player in the background.");
			UnlockContracts = config.Bind<string>(section, "UnlockContracts", string.Empty, "Comma-separated stable contract IDs that begin rolling at this quota.");
			UnlockShipUpgradePurchases = config.Bind<string>(section, "UnlockShipUpgradePurchases", string.Empty, "Comma-separated stable ship-upgrade IDs unlocked for purchase at this quota.");
			UnlockConstellations = config.Bind<string>(section, "UnlockConstellations", string.Empty, "Comma-separated constellation names unlocked at this quota.");
			UnlockMoons = config.Bind<string>(section, "UnlockMoons", string.Empty, "Comma-separated moon names as the terminal shows them (e.g. Titan, Artifice) that cannot be routed to until this quota. Moons not named in any quota stay available.");
			UnlockSuits = config.Bind<string>(section, "UnlockSuits", string.Empty, "Comma-separated suit unlockable names (as in StartOfRound.unlockablesList, e.g. Green suit) hidden from the suit rack until this quota.");
			UnlockStoreItems = config.Bind<string>(section, "UnlockStoreItems", string.Empty, "Comma-separated store item names (as in Terminal.buyableItemsList, e.g. Pro-flashlight) unavailable for purchase until this quota.");
			ConfigEntry<int> tokens = QuotaMilestoneOptions.BindGrantTokensPerPlayer(config, section);
			ConfigEntry<int> credits = QuotaMilestoneOptions.BindGrantGroupCredits(config, section);
			ConfigEntry<float> fuel = QuotaMilestoneOptions.BindGrantShipFuel(config, section);
			Options = QuotaMilestoneOptions.Bind(config, section, delegate(string message)
			{
				QuotaProgressionRegistry.LogMilestoneWarning("[" + section + "] " + message);
			});
			Rewards = new QuotaRewardOptions(tokens, credits, fuel, Options.Grants);
		}

		private static IEnumerable<string> Split(string value)
		{
			return from item in (value ?? string.Empty).Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
				select item.Trim() into item
				where item.Length > 0
				select item;
		}
	}
	internal static class QuotaProgressionRegistry
	{
		private sealed class ModuleGate : IQuotaUnlockGate
		{
			public bool IsFeatureUnlocked(string category, string stableId, int completedQuotas)
			{
				return category switch
				{
					"assignment" => IsContractUnlocked(stableId, completedQuotas), 
					"ship_upgrade" => IsShipUpgradePurchaseUnlocked(stableId, completedQuotas), 
					"constellation" => IsConstellationUnlocked(stableId, completedQuotas), 
					"suit" => IsSuitUnlocked(stableId), 
					"store_item" => IsStoreItemUnlocked(stableId), 
					"moon" => IsMoonUnlocked(stableId), 
					_ => true, 
				};
			}

			public bool TryGetUnlockQuota(string category, string stableId, out int quota)
			{
				if (category == "constellation")
				{
					return TryGetConstellationUnlockQuota(stableId, out quota);
				}
				if (category == "moon")
				{
					return TryGetMoonUnlockQuota(stableId, out quota);
				}
				quota = 0;
				return false;
			}
		}

		private sealed class ModulePresentationPolicy : IQuotaPresentationPolicy
		{
			public bool RewardsCeremonyEnabled => QuotaProgressionRegistry.RewardsCeremonyEnabled;
		}

		private sealed class SpecQuotaComparer : IComparer<QuotaRewardSpec>
		{
			public int Compare(QuotaRewardSpec a, QuotaRewardSpec b)
			{
				return a.Quota.CompareTo(b.Quota);
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Action<QuotaRolloverFinalized> <0>__OnQuotaRolloverFinalized;

			public static Action<string> <1>__OnRewardProviderAvailable;

			public static Func<string, string> <2>__MoonKey;

			public static Func<string, string> <3>__Normalize;

			public static Func<char, bool> <4>__IsLetterOrDigit;

			public static Action <5>__ClearQuotaStatus;

			public static HandleNamedMessageDelegate <6>__OnPayloadMessage;

			public static HandleNamedMessageDelegate <7>__OnGateSnapshotMessage;

			public static HandleNamedMessageDelegate <8>__OnSoundtrackMessage;

			public static HandleNamedMessageDelegate <9>__OnMediaPlanMessage;

			public static HandleNamedMessageDelegate <10>__OnQuotaStatusMessage;

			public static HandleNamedMessageDelegate <11>__OnMoonRulesMessage;

			public static Action<NetworkManager> <12>__OnRegistered;

			public static Action<NetworkManager> <13>__OnUnregistering;

			public static Action<ulong> <14>__OnClientConnected;

			public static Func<string, string, TakeoverAudioFileCheck> <15>__CheckHostSoundtrack;
		}

		private static ConfigEntry<bool> _retryPending;

		private static ConfigEntry<bool> _randomizeDialogue;

		private static ConfigEntry<bool> _randomizeWithoutReplacement;

		private static ConfigEntry<string> _defaultMediaFile;

		private static ConfigEntry<bool> _allowYoutube;

		private static ConfigEntry<string> _mumbleAudioFiles;

		private static ConfigEntry<string> _alarmAudioFile;

		private static ConfigEntry<string> _soundtrackSource;

		private static ConfigEntry<TakeoverSoundtrackMode> _soundtrackMode;

		private static ConfigEntry<float> _soundtrackVolume;

		private static ConfigEntry<bool> _loopMedia;

		private static ConfigEntry<bool> _enableMediaAudio;

		private static ConfigEntry<bool> _useMediaLengthAsDuration;

		private static ConfigEntry<string> _perMonitorMediaPool;

		private static ConfigEntry<int> _maxConcurrentMediaPlayers;

		private static ConfigEntry<bool> _enableUnlockAnnouncement;

		private static ConfigEntry<float> _unlockAnnouncementSeconds;

		private static ConfigEntry<bool> _announceOnBothMonitors;

		private static ConfigEntry<bool> _rewardsCeremonyEnabled;

		private static ConfigEntry<bool> _ceremonyMirrorBothMonitors;

		private static ConfigEntry<float> _ceremonyTypewriterSecondsPerChar;

		private static ConfigEntry<bool> _ceremonyLineConfirmSting;

		private static ConfigEntry<bool> _ceremonyRestoreStatic;

		private static QuotaRewardOptions _repeatingReward;

		private static ModuleGate _moduleGate;

		private static ModulePresentationPolicy _modulePresentationPolicy;

		private static bool _rolloverSubscribed;

		private const string LedgerSaveKey = "Y4NGZCompany.QuotaProgressionLedger.v1";

		private static readonly Dictionary<int, QuotaMilestoneConfig> Milestones = new Dictionary<int, QuotaMilestoneConfig>();

		private static ConfigEntry<bool> _enabled;

		private static ManualLogSource _log;

		private static QuotaTakeoverPayload _currentPayload;

		private static bool _hasCurrentPayload;

		private static bool _hasAuthoritativeUpgradeSnapshot;

		private static readonly HashSet<string> AuthoritativeUnlockedUpgrades = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

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

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

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

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

		private static int _authoritativeQuota;

		private static float _nextSnapshotAt;

		private static string _activeSaveName = string.Empty;

		private static string _cachedLedgerSave = string.Empty;

		private static HashSet<string> _cachedLedger;

		private static float _nextTokenReplayAt;

		private static int _tokenReplayAttemptsRemaining;

		private const float TokenReplayFirstDelaySeconds = 6f;

		private const float TokenReplayIntervalSeconds = 6f;

		private const int TokenReplayAttempts = 3;

		private static readonly List<QuotaRewardSpec> RewardSpecs = new List<QuotaRewardSpec>();

		private static readonly SpecQuotaComparer ByQuota = new SpecQuotaComparer();

		private static readonly HashSet<int> _ceremonyPointsRaised = new HashSet<int>();

		private static bool _retrying;

		private static readonly HashSet<string> RepeatingCapWarnedSaves = new HashSet<string>(StringComparer.Ordinal);

		private static readonly Action<string> Info = delegate(string message)
		{
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogInfo((object)message);
			}
		};

		private const QuotaMode NoSectionMode = QuotaMode.TakeoverAndRewards;

		private const string PayloadMessage = "Y4NGZCompany.QuotaTakeoverPayload.v3";

		private const string GateSnapshotMessage = "Y4NGZCompany.QuotaProgressionSnapshot.v2";

		private const string SoundtrackMessage = "Y4NGZCompany.QuotaTakeoverSoundtrack.v1";

		private const string MediaPlanMessage = "Y4NGZCompany.QuotaTakeoverMediaPlan.v1";

		private const string MoonRulesMessage = "Y4NGZCompany.QuotaMoonUnlockRules.v1";

		private const int MaxPerMonitorPoolEntries = 6;

		private const int MaxPerMonitorPoolChars = 3000;

		private const int MaxOverrideFileNameChars = 120;

		private const int MaxYoutubeUrlChars = 500;

		private const int MaxMumbleOverrideNameChars = 1000;

		private const int MaxMumbleOverrideHashChars = 1000;

		private static readonly NamedMessageRegistration Registration = CreateRegistration();

		private static TakeoverSoundtrackPlanWire _soundtrackPlan = TakeoverSoundtrackPlanWire.Off;

		private static TakeoverMediaPlanWire _mediaPlan;

		private const int PayloadNonFragmentedLimitBytes = 1024;

		private const int MaxPayloadBlobBytes = 32768;

		internal static string MediaDirectory => Path.Combine(Y4NGZCompanyPaths.LocalDataDir, "MonitorTakeovers");

		internal static bool ProgressionEnabled => _enabled?.Value ?? false;

		internal static bool RandomizeDialogue => _randomizeDialogue?.Value ?? false;

		internal static bool LoopVideo => _loopMedia?.Value ?? true;

		internal static bool PlayVideoSound => _enableMediaAudio?.Value ?? false;

		internal static bool HoldForWholeVideo => _useMediaLengthAsDuration?.Value ?? false;

		internal static bool EnableUnlockAnnouncement => _enableUnlockAnnouncement?.Value ?? true;

		internal static float UnlockAnnouncementSeconds => _unlockAnnouncementSeconds?.Value ?? 4.5f;

		internal static bool AnnounceOnBothMonitors => _announceOnBothMonitors?.Value ?? false;

		internal static bool RewardsCeremonyEnabled => _rewardsCeremonyEnabled?.Value ?? true;

		internal static bool CeremonyMirrorBothMonitors => _ceremonyMirrorBothMonitors?.Value ?? true;

		internal static float CeremonyTypewriterSecondsPerChar => Mathf.Clamp(_ceremonyTypewriterSecondsPerChar?.Value ?? 0.03f, 0.005f, 0.2f);

		internal static bool CeremonyLineConfirmSting => _ceremonyLineConfirmSting?.Value ?? true;

		internal static bool CeremonyRestoreStatic => _ceremonyRestoreStatic?.Value ?? true;

		internal static TakeoverSoundtrackMode SoundtrackMode => _soundtrackMode?.Value ?? TakeoverSoundtrackMode.Off;

		internal static float SoundtrackVolume => Mathf.Clamp01(_soundtrackVolume?.Value ?? 0.8f);

		internal static bool PerMonitorMediaConfigured => PerMonitorMediaPool().Length != 0;

		internal static int MaxVideosAtOnce => Mathf.Clamp(_maxConcurrentMediaPlayers?.Value ?? 3, 1, 6);

		internal static int CurrentPayloadQuota
		{
			get
			{
				if (!_hasCurrentPayload)
				{
					return 0;
				}
				return _currentPayload.Quota;
			}
		}

		internal static event Action<int> HostCeremonyPoint;

		internal static void LogMilestoneWarning(string message)
		{
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogWarning((object)message);
			}
		}

		internal static bool TryGetMilestoneOptions(int quota, out QuotaMilestoneOptions options)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled != null && enabled.Value && Milestones.TryGetValue(quota, out var value) && value != null && value.Mode.Value.GrantsRewards())
			{
				options = value.Options;
				return true;
			}
			options = null;
			return false;
		}

		internal static int HostDeadlineDaysForPeriod(int periodQuota)
		{
			if (!TryGetMilestoneOptions(periodQuota, out var options))
			{
				return 0;
			}
			return options.EffectiveDeadlineDays;
		}

		internal static string[] PerMonitorMediaPool()
		{
			return SplitSemicolonList(_perMonitorMediaPool?.Value);
		}

		internal static void Initialize(ConfigFile config, ManualLogSource log)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Expected O, but got Unknown
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Expected O, but got Unknown
			_log = log;
			_enabled = config.Bind<bool>("General", "EnableQuotaProgression", true, "Enable quota-based unlock gates, rewards, and takeover presentation.");
			_retryPending = config.Bind<bool>("General", "RetryPendingOptionalRewards", true, "Retry optional rewards such as tokens when their provider becomes available later.");
			_randomizeDialogue = config.Bind<bool>("Presentation", "RandomizeDialogue", false, "Choose configured dialogue from any quota whose Mode is not Nothing instead of attaching dialogue to its quota.");
			_randomizeWithoutReplacement = config.Bind<bool>("Presentation", "RandomizeWithoutReplacement", true, "When randomizing, use every available passage once before the deterministic pool repeats.");
			_defaultMediaFile = config.Bind<string>("Media", "MediaForAllQuotas", string.Empty, "Video (MP4), image (PNG or JPG), or full YouTube link shown on the ship monitors by every quota that leaves its own Media setting blank. A quota's own quotaN.mp4 in BepInEx/config/Y4NGZCompany/MonitorTakeovers wins over this. A blank value first plays takeover.mp4 from the same folder when that file is there, with no config edit. Blank shows the built-in Y4NGZ video. Files go in BepInEx/config/Y4NGZCompany/MonitorTakeovers and every player needs an identical copy or they see the built-in video; a YouTube link is downloaded and cached by each player in the background.");
			_loopMedia = config.Bind<bool>("Media", "LoopVideo", true, "Restart your video from the beginning if it ends before the takeover does.");
			_enableMediaAudio = config.Bind<bool>("Media", "PlayVideoSound", false, "Play the sound from your own video on top of the takeover's built-in audio (the alarm, the drone, and the voice lines). Off by default so it does not talk over the dialogue. The built-in video never plays its own sound, and a playing Soundtrack mutes this.");
			_useMediaLengthAsDuration = config.Bind<bool>("Media", "HoldForWholeVideo", false, "Keep the monitors taken over until your video finishes instead of for Takeover Duration seconds. Only applies to a video you supply (local MP4 or YouTube link); capped at 30 minutes.");
			_perMonitorMediaPool = config.Bind<string>("Media", "MediaPerMonitor", string.Empty, "Show a different video or image on each ship monitor. Semicolon-separated list of files from BepInEx/config/Y4NGZCompany/MonitorTakeovers and/or full YouTube links (semicolons, because a link can contain a comma). Leave blank for one shared video on every monitor, chosen by the quota's Media setting and MediaForAllQuotas. Files need an identical copy on every player; links are cached by each player. Example: clip1.mp4;https://youtu.be/abc;poster.png");
			_maxConcurrentMediaPlayers = config.Bind<int>("Media", "MaxVideosAtOnce", 3, new ConfigDescription("How many videos may play at the same time when MediaPerMonitor lists several. Extra monitors repeat the videos already playing. Lower this if per-monitor takeovers stutter.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6), Array.Empty<object>()));
			_allowYoutube = config.Bind<bool>("Media", "Allow YouTube takeover videos", true, "On: this PC downloads yt-dlp from github.com/yt-dlp/yt-dlp and, when FFmpeg is not on PATH, FFmpeg (the ffbinaries build on github.com) into BepInEx/cache/Y4NGZMonitorTakeover, and runs them to fetch the YouTube links used as takeover media, soundtracks or MediaPerMonitor entries. Off: neither is downloaded or run on this PC, a YouTube link shows the built-in video (a soundtrack link plays nothing) and a tip says so once. Each player sets this for their own PC.");
			YoutubeVideoResolver.SetAllowed(_allowYoutube.Value);
			_allowYoutube.SettingChanged += delegate
			{
				YoutubeVideoResolver.SetAllowed(_allowYoutube.Value);
			};
			_mumbleAudioFiles = config.Bind<string>("Audio", "VoiceFiles", string.Empty, "Your own voice clips, replacing the built-in mumbled voice lines that repeat in random order, through the ship-speaker filter, under the typed dialogue. Not synchronized narration: for one whole recording use Soundtrack instead. Full file names with extensions, MP3, WAV or OGG only (no links), separated by commas, so a file name cannot contain a comma. Up to 12 files of at most 32 MiB each, in BepInEx/config/Y4NGZCompany/MonitorTakeovers of the active profile. Used for every quota whose own VoiceFiles is blank or unusable. Every player needs an identical copy; a file that is missing, different or unreadable for a player is skipped for them while their other files still play, and they hear the built-in voices only when none of the files is usable.");
			_alarmAudioFile = config.Bind<string>("Audio", "AlarmFile", string.Empty, "One file that replaces the game's alarm looping from the start of the takeover. Full file name with extension, MP3, WAV or OGG only, at most 32 MiB, in the same folder as VoiceFiles. Used for every quota whose own AlarmFile is blank or unusable. A player without a usable identical copy hears the game's alarm.");
			_soundtrackSource = config.Bind<string>("Audio", "Soundtrack", string.Empty, "Music for the whole takeover: a full file name with extension (MP3, WAV or OGG, at most 32 MiB) from BepInEx/config/Y4NGZCompany/MonitorTakeovers of the active profile, or a full YouTube link. It loops for as long as the takeover lasts and never makes the takeover longer. Does nothing while SoundtrackMode is Off. Used for every quota whose own Soundtrack is blank or unusable. A file needs an identical copy on every player; a link is downloaded and cached by each player.");
			_soundtrackMode = config.Bind<TakeoverSoundtrackMode>("Audio", "SoundtrackMode", TakeoverSoundtrackMode.Off, "Off: no soundtrack; the takeover audio plays as usual, including your AlarmFile and VoiceFiles. Mix: the Soundtrack plays on top of that audio. Replace: only the Soundtrack plays, and the power-down whine, alarm, drone and voice lines are silenced, built-in or your own AlarmFile and VoiceFiles alike. If a Replace soundtrack cannot start or fails while playing, the drone and voice lines return for the rest of that takeover.");
			_soundtrackVolume = config.Bind<float>("Audio", "SoundtrackVolume", 0.8f, new ConfigDescription("Volume of the Soundtrack only (0 = silent, 1 = full). 0 is deliberate silence, so Replace at 0 still silences the takeover audio. Does not affect VoiceVolume or the alarm.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			_enableUnlockAnnouncement = config.Bind<bool>("Rewards Ceremony", "EnableUnlockAnnouncement", true, "After the takeover ends, show the quota's new unlocks and grants on the left large ship monitor.");
			_unlockAnnouncementSeconds = config.Bind<float>("Rewards Ceremony", "UnlockAnnouncementSeconds", 4.5f, new ConfigDescription("Seconds the unlock announcement stays on the monitor.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 15f), Array.Empty<object>()));
			_announceOnBothMonitors = config.Bind<bool>("Rewards Ceremony", "AnnounceOnBothMonitors", false, "Also show the unlock announcement on the right large ship monitor.");
			_rewardsCeremonyEnabled = config.Bind<bool>("Rewards Ceremony", "RewardsCeremonyEnabled", true, "Present the unlock announcement as a ceremony: each reward line types out with a tick per step and a confirm when it lands, and the display hold starts after typing finishes.");
			_ceremonyMirrorBothMonitors = config.Bind<bool>("Rewards Ceremony", "CeremonyMirrorBothMonitors", true, "During the rewards ceremony, mirror the announcement onto the right large ship monitor as well.");
			_ceremonyTypewriterSecondsPerChar = config.Bind<float>("Rewards Ceremony", "CeremonyTypewriterSecondsPerChar", 0.03f, new ConfigDescription("Seconds each typed character takes during the rewards ceremony.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.005f, 0.2f), Array.Empty<object>()));
			_ceremonyLineConfirmSting = config.Bind<bool>("Rewards Ceremony", "CeremonyLineConfirmSting", true, "Play a confirm sting as each reward line finishes typing.");
			_ceremonyRestoreStatic = config.Bind<bool>("Rewards Ceremony", "CeremonyRestoreStatic", true, "End the rewards ceremony with a brief CRT static burst before the monitors return to their normal views instead of a hard cut.");
			Directory.CreateDirectory(MediaDirectory);
			Milestones.Clear();
			for (int num = 1; num < 10; num++)
			{
				Milestones[num] = new QuotaMilestoneConfig(config, num, _log);
			}
			_repeatingReward = QuotaRewardOptions.BindRepeating(config, delegate(string message)
			{
				LogMilestoneWarning("[Quotas 10 And Later] " + message);
			});
			if (_enabled.Value)
			{
				YoutubeVideoResolver.Prefetch(_defaultMediaFile?.Value);
				YoutubeVideoResolver.Prefetch(_soundtrackSource?.Value);
				foreach (QuotaMilestoneConfig value in Milestones.Values)
				{
					if (value.Mode.Value.UsesQuotaDialogueAndMedia())
					{
						YoutubeVideoResolver.Prefetch(value.MediaFile.Value);
						YoutubeVideoResolver.Prefetch(value.Options.Soundtrack.Value);
					}
				}
				string[] array = PerMonitorMediaPool();
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					YoutubeVideoResolver.Prefetch(array[num2]);
				}
				WarnOnCommaSeparatedMediaPool();
			}
			WriteEffectiveAudit();
			EnsureModuleWiring();
			TakeoverMediaNoticeHub.Initialize();
		}

		internal static void EnsureModuleWiring()
		{
			if (_moduleGate == null)
			{
				_moduleGate = new ModuleGate();
				_modulePresentationPolicy = new ModulePresentationPolicy();
				ModuleCapabilityRegistry.Register("y4ngz.quota.unlocks", (object)_moduleGate);
				ModuleCapabilityRegistry.Register("y4ngz.quota.presentation_policy", (object)_modulePresentationPolicy);
			}
			if (!_rolloverSubscribed)
			{
				_rolloverSubscribed = true;
				QuotaRolloverNotifications.QuotaRolloverFinalized += OnQuotaRolloverFinalized;
				QuotaRewardBroker.RewardProviderAvailable += OnRewardProviderAvailable;
			}
		}

		private static string ReadDialogue(QuotaMilestoneConfig milestone)
		{
			if (milestone == null)
			{
				return string.Empty;
			}
			if (!string.IsNullOrWhiteSpace(milestone.DialogueFile.Value) && TryResolveFile(milestone.DialogueFile.Value, ".txt", out var path))
			{
				try
				{
					if (new FileInfo(path).Length <= 65536)
					{
						return File.ReadAllText(path).Trim();
					}
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)$"Quota {milestone.Quota} dialogue file exceeds 64 KB; using inline/built-in dialogue.");
					}
				}
				catch (Exception ex)
				{
					ManualLogSource log2 = _log;
					if (log2 != null)
					{
						log2.LogWarning((object)$"Quota {milestone.Quota} dialogue file failed: {ex.Message}");
					}
				}
			}
			return (milestone.Dialogue.Value ?? string.Empty).Replace("\\n", "\n").Trim();
		}

		internal static bool TryResolveTakeoverMedia(string configured, string expectedHash, TakeoverMediaSource source, out string path, out TakeoverMediaProblem problem, out string reason)
		{
			path = null;
			bool flag = YoutubeVideoResolver.IsYoutubeUrl(configured);
			string located = null;
			string detail = null;
			TakeoverAudioFileStatus localStatus = ((!flag) ? TakeoverMediaFiles.Locate(MediaDirectory, configured, TakeoverMediaFiles.Extensions, out located, out detail) : TakeoverAudioFileStatus.Accepted);
			if (!TakeoverMediaFiles.Accept(flag, source, NetworkRole.IsServerFlagSet(), expectedHash, localStatus, detail, () => ComputeSha256(located), out problem, out reason))
			{
				return false;
			}
			if (!flag)
			{
				path = located;
				return true;
			}
			if (!YoutubeVideoResolver.IsAllowed)
			{
				problem = TakeoverMediaProblem.YoutubeOff;
			}
			else
			{
				if (YoutubeVideoResolver.TryGetCachedVideo(configured, out path))
				{
					return true;
				}
				problem = TakeoverMediaProblem.YoutubeNotReady;
			}
			return false;
		}

		private static TakeoverMediaPick PickTakeoverMedia(int quota)
		{
			QuotaMilestoneConfig value;
			bool flag = Milestones.TryGetValue(quota, out value) && value != null && value.Mode.Value.UsesQuotaDialogueAndMedia();
			string folder = MediaDirectory;
			return TakeoverMediaPicker.Pick(quota, flag, flag ? value.MediaFile.Value : null, _defaultMediaFile?.Value, (string name) => File.Exists(Path.Combine(folder, name)));
		}

		private static bool TryResolveFile(string configured, string extension, out string path)
		{
			TakeoverAudioFileStatus status;
			string detail;
			return TryResolveFile(configured, new string[1] { extension }, out path, out status, out detail);
		}

		private static bool TryResolveFile(string configured, string[] extensions, out string path, out TakeoverAudioFileStatus status, out string detail)
		{
			status = TakeoverMediaFiles.Locate(MediaDirectory, configured, extensions, out path, out detail);
			if (status == TakeoverAudioFileStatus.TooLarge)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Configured takeover media '" + Path.GetFileName(configured.Trim()) + "' exceeds the size limit."));
				}
			}
			return status == TakeoverAudioFileStatus.Accepted;
		}

		private static string[] SplitList(string value)
		{
			return TakeoverAudioPolicy.SplitList(value);
		}

		internal static string[] SplitSemicolonList(string value)
		{
			return (from item in (value ?? string.Empty).Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries)
				select item.Trim() into item
				where item.Length > 0
				select item).ToArray();
		}

		internal static string[] SplitSemicolonListPreservingEmpty(string value)
		{
			string text = value ?? string.Empty;
			if (text.Length == 0)
			{
				return Array.Empty<string>();
			}
			return (from item in text.Split(';')
				select item.Trim()).ToArray();
		}

		private static void WarnOnCommaSeparatedMediaPool()
		{
			string text = _perMonitorMediaPool?.Value ?? string.Empty;
			if (text.IndexOf(';') < 0 && text.IndexOf(',') >= 0 && SplitList(text).Length >= 2)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)"[QuotaProgression] MediaPerMonitor looks comma-separated; this key uses ';' so that a YouTube link containing a comma stays intact. The whole value is being read as one entry.");
				}
			}
		}

		private static void WriteEffectiveAudit()
		{
			try
			{
				string text = Y4NGZCompanyPaths.LocalDataFile("quota-progression-effective.tsv");
				List<string> list = new List<string> { "quota\tmode\tname\tdialogue\tmedia\tcontracts\tupgrades\tconstellations\tmoons\tsuits\tstore_items\ttokens_per_player\tgroup_credits\tship_fuel\tdeadline_days\tforce_route\tgrant_items\tgrant_ship_upgrade\talarm_file\tvoice_files\tsoundtrack\tmedia_pick" };
				foreach (QuotaMilestoneConfig item in Milestones.Values.OrderBy((QuotaMilestoneConfig m) => m.Quota))
				{
					string value = ((!string.IsNullOrWhiteSpace(item.DialogueFile.Value)) ? ("file:" + item.DialogueFile.Value) : ((!string.IsNullOrWhiteSpace(item.Dialogue.Value)) ? "inline" : "built-in"));
					list.Add(string.Join("\t", item.Quota.ToString(), item.Mode.Value.ToString(), EscapeAudit(item.Name.Value), EscapeAudit(value), EscapeAudit(item.MediaFile.Value), EscapeAudit(string.Join(",", item.Contracts)), EscapeAudit(string.Join(",", item.Upgrades)), EscapeAudit(string.Join(",", item.Constellations)), EscapeAudit(string.Join(",", item.Moons)), EscapeAudit(string.Join(",", item.Suits)), EscapeAudit(string.Join(",", item.StoreItems)), item.Rewards.GrantTokensPerPlayer.Value.ToString(), item.Rewards.GrantGroupCredits.Value.ToString(), item.Rewards.GrantShipFuel.Value.ToString(CultureInfo.InvariantCulture), item.Options.EffectiveDeadlineDays.ToString(CultureInfo.InvariantCulture), EscapeAudit(item.Options.ForceRoute.Value), EscapeAudit(item.Rewards.Grants.GrantItems.Value), EscapeAudit(item.Rewards.Grants.GrantShipUpgrade.Value), EscapeAudit(item.Options.AlarmFile.Value), EscapeAudit(item.Options.VoiceFiles.Value), EscapeAudit(item.Options.Soundtrack.Value), EscapeAudit(TakeoverMediaPicker.DescribeForAudit(PickTakeoverMedia(item.Quota)))));
				}
				list.Add(string.Empty);
				list.Add("shared_key\tvalue");
				list.Add("MediaForAllQuotas\t" + EscapeAudit(_defaultMediaFile?.Value));
				list.Add("VoiceFiles\t" + EscapeAudit(_mumbleAudioFiles?.Value));
				list.Add("AlarmFile\t" + EscapeAudit(_alarmAudioFile?.Value));
				list.Add("Soundtrack\t" + EscapeAudit(_soundtrackSource?.Value));
				list.Add("SoundtrackMode\t" + SoundtrackMode);
				list.Add("SoundtrackVolume\t" + SoundtrackVolume.ToString(CultureInfo.InvariantCulture));
				list.Add("MediaPerMonitor\t" + EscapeAudit(_perMonitorMediaPool?.Value));
				list.Add("MaxVideosAtOnce\t" + MaxVideosAtOnce);
				list.Add(string.Empty);
				list.Add("repeating_reward_key\tvalue");
				list.Add("GrantTokensPerPlayer\t" + _repeatingReward.GrantTokensPerPlayer.Value);
				list.Add("GrantGroupCredits\t" + _repeatingReward.GrantGroupCredits.Value);
				list.Add("GrantShipFuel\t" + _repeatingReward.GrantShipFuel.Value.ToString(CultureInfo.InvariantCulture));
				list.Add("GrantItems\t" + EscapeAudit(_repeatingReward.Grants.GrantItems.Value));
				list.Add("GrantShipUpgrade\t" + EscapeAudit(_repeatingReward.Grants.GrantShipUpgrade.Value));
				File.WriteAllLines(text, list);
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)$"Quota progression effective audit written to '{text}' ({Milestones.Count} milestones).");
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Quota progression effective audit failed: " + ex.Message));
				}
			}
		}

		private static string EscapeAudit(string value)
		{
			return (value ?? string.Empty).Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n");
		}

		private static string ComputeSha256(string path)
		{
			string error;
			return TakeoverAudioPolicy.ComputeSha256(path, out error);
		}

		internal static bool IsContractUnlocked(string contractId, int completedQuotas)
		{
			return IsNamedUnlockSatisfied(contractId, completedQuotas, (QuotaMilestoneConfig milestone) => milestone.Contracts);
		}

		internal static bool IsShipUpgradePurchaseUnlocked(string upgradeId, int completedQuotas)
		{
			if ((Object)(object)NetworkManager.Singleton != (Object)null && !NetworkManager.Singleton.IsServer && _hasAuthoritativeUpgradeSnapshot)
			{
				return AuthoritativeUnlockedUpgrades.Contains(Normalize(upgradeId));
			}
			return IsNamedUnlockSatisfied(upgradeId, completedQuotas, (QuotaMilestoneConfig milestone) => milestone.Upgrades);
		}

		internal static bool IsConstellationUnlocked(string name, int completedQuotas)
		{
			return IsNamedUnlockSatisfied(name, completedQuotas, (QuotaMilestoneConfig milestone) => milestone.Constellations);
		}

		internal static bool TryGetConstellationUnlockQuota(string name, out int quota)
		{
			quota = 0;
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || string.IsNullOrWhiteSpace(name))
			{
				return false;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && !NetworkManager.Singleton.IsServer && _hasAuthoritativeUpgradeSnapshot)
			{
				return AuthoritativeConstellationUnlockQuotas.TryGetValue(Normalize(name), out quota);
			}
			foreach (QuotaMilestoneConfig item in from m in Milestones.Values
				where m.Mode.Value.GrantsRewards()
				orderby m.Quota
				select m)
			{
				if (item.Constellations.Any((string item) => Normalize(item) == Normalize(name)))
				{
					quota = item.Quota;
					return true;
				}
			}
			return false;
		}

		internal static bool IsSuitUnlocked(string name)
		{
			return IsRuleUnlocked(name, AuthoritativeSuitUnlockQuotas, (QuotaMilestoneConfig milestone) => milestone.Suits);
		}

		internal static bool IsStoreItemUnlocked(string name)
		{
			return IsRuleUnlocked(name, AuthoritativeStoreItemUnlockQuotas, (QuotaMilestoneConfig milestone) => milestone.StoreItems);
		}

		internal static bool IsMoonUnlocked(string planetName)
		{
			return IsRuleUnlocked(MoonKey(planetName), AuthoritativeMoonUnlockQuotas, (QuotaMilestoneConfig milestone) => milestone.Moons.Select(MoonKey));
		}

		internal static bool TryGetMoonUnlockQuota(string planetName, out int quota)
		{
			quota = 0;
			string key = MoonKey(planetName);
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || string.IsNullOrWhiteSpace(key))
			{
				return false;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && !NetworkManager.Singleton.IsServer && _hasAuthoritativeUpgradeSnapshot)
			{
				return AuthoritativeMoonUnlockQuotas.TryGetValue(Normalize(key), out quota);
			}
			foreach (QuotaMilestoneConfig item in from m in Milestones.Values
				where m.Mode.Value.GrantsRewards()
				orderby m.Quota
				select m)
			{
				if (item.Moons.Any((string item) => Normalize(MoonKey(item)) == Normalize(key)))
				{
					quota = item.Quota;
					return true;
				}
			}
			return false;
		}

		internal static string MoonKey(string planetName)
		{
			string text = (planetName ?? string.Empty).Trim();
			int i;
			for (i = 0; i < text.Length && char.IsDigit(text[i]); i++)
			{
			}
			if (i > 0 && i < text.Length && (text[i] == '-' || text[i] == ' ' || text[i] == '_'))
			{
				text = text.Substring(i + 1);
			}
			return text.Trim();
		}

		private static bool IsRuleUnlocked(string name, Dictionary<string, int> authoritative, Func<QuotaMilestoneConfig, IEnumerable<string>> selector)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || string.IsNullOrWhiteSpace(name))
			{
				return true;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && !NetworkManager.Singleton.IsServer && _hasAuthoritativeUpgradeSnapshot)
			{
				if (authoritative.TryGetValue(Normalize(name), out var value))
				{
					return _authoritativeQuota >= value;
				}
				return true;
			}
			int completedQuotas = (((Object)(object)TimeOfDay.Instance != (Object)null) ? Math.Max(0, TimeOfDay.Instance.timesFulfilledQuota) : 0);
			return IsNamedUnlockSatisfied(name, completedQuotas, selector);
		}

		internal static QuotaMilestoneSummary GetMilestoneSummary(int quota)
		{
			if (!Milestones.TryGetValue(quota, out var value) || value == null)
			{
				return RepeatingSummary(quota);
			}
			return new QuotaMilestoneSummary
			{
				Quota = value.Quota,
				Mode = value.Mode.Value,
				Contracts = value.Contracts.ToArray(),
				ShipUpgrades = value.Upgrades.ToArray(),
				Constellations = value.Constellations.ToArray(),
				Moons = value.Moons.ToArray(),
				Suits = value.Suits.ToArray(),
				StoreItems = value.StoreItems.ToArray(),
				ForcedRouteName = (value.Options?.ForcedRouteName ?? string.Empty),
				Rewards = value.Rewards.Spec(value.Quota)
			};
		}

		private static QuotaMilestoneSummary RepeatingSummary(int quota)
		{
			if (_repeatingReward == null || quota < 10 || quota > 1000)
			{
				return null;
			}
			QuotaRewardSpec rewards = _repeatingReward.Spec(quota);
			if (rewards.PaysNothing)
			{
				return null;
			}
			return new QuotaMilestoneSummary
			{
				Quota = quota,
				Mode = QuotaMode.TakeoverAndRewards,
				Contracts = Array.Empty<string>(),
				ShipUpgrades = Array.Empty<string>(),
				Constellations = Array.Empty<string>(),
				Moons = Array.Empty<string>(),
				Suits = Array.Empty<string>(),
				StoreItems = Array.Empty<string>(),
				ForcedRouteName = string.Empty,
				Rewards = rewards
			};
		}

		private static bool IsNamedUnlockSatisfied(string name, int completedQuotas, Func<QuotaMilestoneConfig, IEnumerable<string>> selector)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || string.IsNullOrWhiteSpace(name))
			{
				return true;
			}
			int? num = null;
			foreach (QuotaMilestoneConfig item in from m in Milestones.Values
				where m.Mode.Value.GrantsRewards()
				orderby m.Quota
				select m)
			{
				if (selector(item).Any((string item) => Normalize(item) == Normalize(name)))
				{
					num = item.Quota;
					break;
				}
			}
			if (num.HasValue)
			{
				return completedQuotas >= num.Value;
			}
			return true;
		}

		private unsafe static void SendGateSnapshot()
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			CustomMessagingManager val = ((singleton != null) ? singleton.CustomMessagingManager : null);
			if (val == null)
			{
				return;
			}
			NetworkManager singleton2 = NetworkManager.Singleton;
			if (singleton2 == null || !singleton2.IsServer)
			{
				return;
			}
			int quota = (((Object)(object)TimeOfDay.Instance != (Object)null) ? Math.Max(0, TimeOfDay.Instance.timesFulfilledQuota) : 0);
			string value = string.Join(",", (from id in QuotaUnlockCatalogs.GetStableIds("ship_upgrade")
				where IsNamedUnlockSatisfied(id, quota, (QuotaMilestoneConfig milestone) => milestone.Upgrades)
				select id).Select(Normalize));
			string value2 = BuildRuleString((QuotaMilestoneConfig milestone) => milestone.Constellations);
			string value3 = BuildRuleString((QuotaMilestoneConfig milestone) => milestone.Suits);
			string value4 = BuildRuleString((QuotaMilestoneConfig milestone) => milestone.StoreItems);
			FastBufferWriter val2 = default(FastBufferWriter);
			((FastBufferWriter)(ref val2))..ctor(17408, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val2)).WriteValueSafe<int>(ref quota, default(ForPrimitives));
				FixedString4096Bytes val3 = FixedString4096Bytes.op_Implicit(TruncateFixed(value, 1000, quota, "UnlockShipUpgradePurchases rules"));
				FixedString4096Bytes val4 = FixedString4096Bytes.op_Implicit(TruncateFixed(value2, 1000, quota, "UnlockConstellations rules"));
				FixedString4096Bytes val5 = FixedString4096Bytes.op_Implicit(TruncateFixed(value3, 1000, quota, "UnlockSuits rules"));
				FixedString4096Bytes val6 = FixedString4096Bytes.op_Implicit(TruncateFixed(value4, 1000, quota, "UnlockStoreItems rules"));
				((FastBufferWriter)(ref val2)).WriteValueSafe<FixedString4096Bytes>(ref val3, default(ForFixedStrings));
				((FastBufferWriter)(ref val2)).WriteValueSafe<FixedString4096Bytes>(ref val4, default(ForFixedStrings));
				((FastBufferWriter)(ref val2)).WriteValueSafe<FixedString4096Bytes>(ref val5, default(ForFixedStrings));
				((FastBufferWriter)(ref val2)).WriteValueSafe<FixedString4096Bytes>(ref val6, default(ForFixedStrings));
				val.SendNamedMessageToAll("Y4NGZCompany.QuotaProgressionSnapshot.v2", val2, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val2))/*cast due to .constrained prefix*/).Dispose();
			}
			SendMoonRules(val, quota);
			QuotaProgressionSuitGate.OnUnlockStateMaybeChanged(quota);
			SendQuotaStatus(val);
		}

		private unsafe static void SendMoonRules(CustomMessagingManager manager, int quota)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (manager == null)
			{
				return;
			}
			string value = BuildRuleString((QuotaMilestoneConfig milestone) => milestone.Moons.Select(MoonKey));
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(4608, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref quota, default(ForPrimitives));
				FixedString4096Bytes val2 = FixedString4096Bytes.op_Implicit(TruncateFixed(value, 1000, quota, "UnlockMoons rules"));
				((FastBufferWriter)(ref val)).WriteValueSafe<FixedString4096Bytes>(ref val2, default(ForFixedStrings));
				manager.SendNamedMessageToAll("Y4NGZCompany.QuotaMoonUnlockRules.v1", val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private unsafe static void OnMoonRulesMessage(ulong sender, FastBufferReader reader)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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: Unknown result type (might be due to invalid IL or missing references)
			if (sender == 0L)
			{
				int val = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref val, default(ForPrimitives));
				FixedString4096Bytes val2 = default(FixedString4096Bytes);
				((FastBufferReader)(ref reader)).ReadValueSafe<FixedString4096Bytes>(ref val2, default(ForFixedStrings));
				ParseRuleString(((object)(*(FixedString4096Bytes*)(&val2))/*cast due to .constrained prefix*/).ToString(), AuthoritativeMoonUnlockQuotas);
				_authoritativeQuota = Math.Max(_authoritativeQuota, Math.Max(0, val));
			}
		}

		private static string BuildRuleString(Func<QuotaMilestoneConfig, IEnumerable<string>> selector)
		{
			return string.Join(";", from @group in (from m in Milestones.Values
					where m.Mode.Value.GrantsRewards()
					orderby m.Quota
					select m).SelectMany((QuotaMilestoneConfig m) => from name in selector(m)
					select Normalize(name) + "=" + m.Quota).GroupBy<string, string>((string entry) => entry.Substring(0, entry.IndexOf('=')), StringComparer.OrdinalIgnoreCase)
				select @group.First());
		}

		private static void ParseRuleString(string rules, Dictionary<string, int> target)
		{
			target.Clear();
			string[] array = (rules ?? string.Empty).Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				int num = text.IndexOf('=');
				if (num > 0 && int.TryParse(text.Substring(num + 1), out var result))
				{
					target[Normalize(text.Substring(0, num))] = result;
				}
			}
		}

		private unsafe static void OnGateSnapshotMessage(ulong sender, FastBufferReader reader)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			if (sender == 0L)
			{
				int val = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref val, default(ForPrimitives));
				FixedString4096Bytes val2 = default(FixedString4096Bytes);
				((FastBufferReader)(ref reader)).ReadValueSafe<FixedString4096Bytes>(ref val2, default(ForFixedStrings));
				FixedString4096Bytes val3 = default(FixedString4096Bytes);
				((FastBufferReader)(ref reader)).ReadValueSafe<FixedString4096Bytes>(ref val3, default(ForFixedStrings));
				FixedString4096Bytes val4 = default(FixedString4096Bytes);
				((FastBufferReader)(ref reader)).ReadValueSafe<FixedString4096Bytes>(ref val4, default(ForFixedStrings));
				FixedString4096Bytes val5 = default(FixedString4096Bytes);
				((FastBufferReader)(ref reader)).ReadValueSafe<FixedString4096Bytes>(ref val5, default(ForFixedStrings));
				AuthoritativeUnlockedUpgrades.Clear();
				string[] array = ((object)(*(FixedString4096Bytes*)(&val2))/*cast due to .constrained prefix*/).ToString().Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string value in array)
				{
					AuthoritativeUnlockedUpgrades.Add(Normalize(value));
				}
				ParseRuleString(((object)(*(FixedString4096Bytes*)(&val3))/*cast due to .constrained prefix*/).ToString(), AuthoritativeConstellationUnlockQuotas);
				ParseRuleString(((object)(*(FixedString4096Bytes*)(&val4))/*cast due to .constrained prefix*/).ToString(), AuthoritativeSuitUnlockQuotas);
				ParseRuleString(((object)(*(FixedString4096Bytes*)(&val5))/*cast due to .constrained prefix*/).ToString(), AuthoritativeStoreItemUnlockQuotas);
				_authoritativeQuota = Math.Max(0, val);
				_hasAuthoritativeUpgradeSnapshot = true;
				QuotaProgressionSuitGate.OnUnlockStateMaybeChanged(_authoritativeQuota);
			}
		}

		private static string Normalize(string value)
		{
			return new string((value ?? string.Empty).ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray());
		}

		private static void ReplayLedgeredTokenGrants()
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value)
			{
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if (singleton == null || !singleton.IsServer || !QuotaProgressionApi.IsTokenGrantCapabilityAvailable)
			{
				return;
			}
			int num = (((Object)(object)TimeOfDay.Instance != (Object)null) ? Math.Max(0, TimeOfDay.Instance.timesFulfilledQuota) : 0);
			if (num < 1)
			{
				return;
			}
			int num2 = QuotaRewardPass.ReplayPaidTokens(LoadLedger(), CurrentRewardSpecs(), num);
			if (num2 > 0)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)$"Replayed {num2} ledgered quota token grant(s) for connected players.");
				}
			}
		}

		private static IReadOnlyList<QuotaRewardSpec> CurrentRewardSpecs()
		{
			RewardSpecs.Clear();
			foreach (QuotaMilestoneConfig value in Milestones.Values)
			{
				if (value != null && value.Mode.Value.GrantsRewards())
				{
					RewardSpecs.Add(value.Rewards.Spec(value.Quota));
				}
			}
			if (_repeatingReward != null)
			{
				RewardSpecs.Add(_repeatingReward.Spec(10));
			}
			RewardSpecs.Sort(ByQuota);
			return RewardSpecs;
		}

		private static HashSet<string> LoadLedger()
		{
			string text = CurrentSaveName();
			if (_cachedLedger != null && string.Equals(_cachedLedgerSave, text, StringComparison.Ordinal))
			{
				return _cachedLedger;
			}
			bool flag = false;
			try
			{
				_cachedLedger = QuotaRewardLedger.Parse(ES3.Load<string>("Y4NGZCompany.QuotaProgressionLedger.v1", text, string.Empty));
			}
			catch (Exception ex)
			{
				flag = true;
				_cachedLedger = new HashSet<string>(StringComparer.Ordinal);
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Quota progression ledger load failed: " + ex.Message));
				}
			}
			_cachedLedgerSave = text;
			if (!flag && QuotaRewardLedger.HealFalsePaidFuelRewards(_cachedLedger))
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogInfo((object)"Quota progression ledger healed: fuel milestones recorded as paid before the grant predicate was fixed are owed again.");
				}
				SaveLedger(_cachedLedger);
			}
			return _cachedLedger;
		}

		private static void SaveLedger(HashSet<string> ledger, string failureEffect = null)
		{
			_cachedLedger = ledger;
			_cachedLedgerSave = CurrentSaveName();
			try
			{
				ES3.Save<string>("Y4NGZCompany.QuotaProgressionLedger.v1", QuotaRewardLedger.Serialize(ledger), _cachedLedgerSave);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Quota progression ledger save failed: " + ex.Message + (string.IsNullOrEmpty(failureEffect) ? string.Empty : ("; " + failureEffect))));
				}
			}
		}

		private static string CurrentSaveName()
		{
			return GameNetworkManager.Instance?.currentSaveFileName ?? "unsaved";
		}

		private static int StableHash(string value)
		{
			int num = 17;
			string text = value ?? string.Empty;
			foreach (char c in text)
			{
				num = num * 31 + c;
			}
			if (num != int.MinValue)
			{
				return num;
			}
			return 0;
		}

		internal static void ResetForNewRun()
		{
			_hasCurrentPayload = false;
			_ceremonyPointsRaised.Clear();
			_tokenReplayAttemptsRemaining = 0;
			_retrying = false;
			SaveLedger(QuotaRewardLedger.NewRunLedger(), "the save still holds the fired run's reward ledger, so after a reload the new run's quotas read as already paid.");
		}

		private static void LogRetryTransition(string owedRewardId)
		{
			bool flag = owedRewardId != null;
			if (flag != _retrying)
			{
				_retrying = flag;
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)(flag ? ("[QuotaProgression] Quota reward " + owedRewardId + " is owed and can be paid; retrying every 5 s until it lands.") : "[QuotaProgression] No owed quota reward can be paid now; the reward retry stops."));
				}
			}
		}

		internal static void RaiseHostCeremonyPoint(int completedQuota)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)singleton == (Object)null || !singleton.IsServer || !_ceremonyPointsRaised.Add(completedQuota))
			{
				return;
			}
			Action<int> hostCeremonyPoint = QuotaProgressionRegistry.HostCeremonyPoint;
			if (hostCeremonyPoint == null)
			{
				return;
			}
			Delegate[] invocationList = hostCeremonyPoint.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					((Action<int>)obj)(completedQuota);
				}
				catch (Exception arg)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)$"Quota ceremony point handler failed for quota {completedQuota}: {arg}");
					}
				}
			}
		}

		internal static bool ShouldPlayTakeover(int completedQuota)
		{
			if (_hasCurrentPayload && _currentPayload.Quota == completedQuota)
			{
				return _currentPayload.TakeoverEnabled;
			}
			return true;
		}

		internal static bool IsRewardUpgradeOwned(int quota, string upgrade)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (singleton != null && singleton.IsServer)
			{
				return QuotaRewardLedger.WasOwned(LoadLedger(), quota, upgrade);
			}
			return false;
		}

		private static bool DecideHostTakeover(int quota)
		{
			QuotaMilestoneConfig value;
			bool flag = Milestones.TryGetValue(quota, out value) && value != null;
			QuotaMode quotaMode = (flag ? value.Mode.Value : QuotaMode.TakeoverAndRewards);
			bool flag2 = QuotaModeEffects.HostPlaysTakeover(_enabled?.Value ?? false, flag, quotaMode);
			if (QuotaPresentationGate.OnHostDecision(quota, flag2))
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)(flag2 ? $"[QuotaProgression] Quota {quota} plays its takeover; it is queued for orbit." : $"[QuotaProgression] Quota {quota} has Mode = {quotaMode}, which has no takeover; its ceremony, if any, runs at orbit."));
				}
			}
			return flag2;
		}

		private static void OnQuotaRolloverFinalized(QuotaRolloverFinalized rollover)
		{
			Networ