Decompiled source of PirateTokenShopAccess v0.4.0

PirateShopAccess.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ModMenu;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("PirateTokenCheck")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PirateShopAccess")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: AssemblyInformationalVersion("0.4.0+278623b0560e8ca9b106d5dc614bccae21df5ac4")]
[assembly: AssemblyProduct("PirateShopAccess")]
[assembly: AssemblyTitle("PirateShopAccess")]
[assembly: AssemblyVersion("0.4.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PirateShopAccess
{
	internal sealed class FirstFind
	{
		private sealed class ReferenceComparer : IEqualityComparer<object>
		{
			internal static readonly ReferenceComparer Instance = new ReferenceComparer();

			public new bool Equals(object a, object b)
			{
				return a == b;
			}

			public int GetHashCode(object o)
			{
				return RuntimeHelpers.GetHashCode(o);
			}
		}

		private readonly HashSet<object> _found = new HashSet<object>(ReferenceComparer.Instance);

		public int Count => _found.Count;

		public bool Claim(object token)
		{
			if (token != null)
			{
				return _found.Add(token);
			}
			return false;
		}

		public bool WasFound(object token)
		{
			if (token != null)
			{
				return _found.Contains(token);
			}
			return false;
		}

		public void Reset()
		{
			_found.Clear();
		}
	}
	internal static class Hud
	{
		public static void AnnounceStateChange(bool active)
		{
			HUDManager instance = HUDManager.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (active)
				{
					instance.DisplayTip("Pirate Shop active!", "Plunder the shop: 1 of each item, upgrade and decor is free each day until you reach 71 Gordion.", false, false, "LC_Tip1");
				}
				else
				{
					instance.DisplayTip("Pirate Shop closed", "Your Pirate Shop access has ended.", false, false, "LC_Tip1");
				}
			}
		}
	}
	internal static class MenuHooks
	{
		internal const string ModMenuGuid = "daniel.lethalcompany.modmenu";

		private const string Tab = "Pirate Token";

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void Register()
		{
			MenuApi.Button("Pirate Token", "Spawn pirate token", (Func<string>)SpawnToken, true, true, (Func<string>)(() => (!((Object)(object)TokenRegistry.Prefab == (Object)null)) ? NoPlayer() : "token item not built"), (string)null);
			MenuApi.Toggle("Pirate Token", "Pirate Shop", (Func<bool>)(() => State.Active), (Func<bool, string>)delegate(bool on)
			{
				if (on)
				{
					State.HostActivate();
				}
				else
				{
					State.HostDeactivate("Mod Menu");
				}
				if (State.Active != on)
				{
					return (string)null;
				}
				return (!on) ? "closed the Pirate Shop" : "opened the Pirate Shop";
			}, true, true, (Func<string>)NoPlayer, (string)null);
			MenuApi.Button("Pirate Token", "Play token popup", (Func<string>)PreviewReveal, false, false, (Func<string>)(() => Plugin.PopupEnabled.Value ? null : "popup off in config"), "only you see it");
		}

		private static string PreviewReveal()
		{
			string text = GameNetworkManager.Instance?.localPlayerController?.playerUsername;
			Popup.Reveal(string.IsNullOrEmpty(text) ? "You" : text);
			return "previewed the token popup";
		}

		private static string NoPlayer()
		{
			if (!((Object)(object)GameNetworkManager.Instance?.localPlayerController == (Object)null))
			{
				return null;
			}
			return "not in a game";
		}

		private static string SpawnToken()
		{
			//IL_0011: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (!TokenRegistry.TrySpawn(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 1.5f + Vector3.up * 0.5f))
			{
				return null;
			}
			return "spawned a pirate token";
		}
	}
	internal static class Net
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequest;

			public static HandleNamedMessageDelegate <1>__OnUse;

			public static HandleNamedMessageDelegate <2>__OnActivate;

			public static HandleNamedMessageDelegate <3>__OnFound;

			public static HandleNamedMessageDelegate <4>__OnState;

			public static HandleNamedMessageDelegate <5>__OnReveal;
		}

		private const string MsgState = "DanielLC.PirateShop.State";

		private const string MsgRequest = "DanielLC.PirateShop.Request";

		private const string MsgUse = "DanielLC.PirateShop.Use";

		private const string MsgActivate = "DanielLC.PirateShop.Activate";

		private const string MsgFound = "DanielLC.PirateShop.Found";

		private const string MsgReveal = "DanielLC.PirateShop.Reveal";

		private static readonly string[] AllMessages = new string[6] { "DanielLC.PirateShop.State", "DanielLC.PirateShop.Request", "DanielLC.PirateShop.Use", "DanielLC.PirateShop.Activate", "DanielLC.PirateShop.Found", "DanielLC.PirateShop.Reveal" };

		internal static readonly FirstFind Found = new FirstFind();

		private static bool _registered;

		public static bool IsHost
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsServer;
				}
				return false;
			}
		}

		public static void Register()
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if (_registered || (Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
			if (singleton.IsServer)
			{
				object obj = <>O.<0>__OnRequest;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequest;
					<>O.<0>__OnRequest = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.Request", (HandleNamedMessageDelegate)obj);
				object obj2 = <>O.<1>__OnUse;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnUse;
					<>O.<1>__OnUse = val2;
					obj2 = (object)val2;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.Use", (HandleNamedMessageDelegate)obj2);
				object obj3 = <>O.<2>__OnActivate;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val3 = OnActivate;
					<>O.<2>__OnActivate = val3;
					obj3 = (object)val3;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.Activate", (HandleNamedMessageDelegate)obj3);
				object obj4 = <>O.<3>__OnFound;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val4 = OnFound;
					<>O.<3>__OnFound = val4;
					obj4 = (object)val4;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.Found", (HandleNamedMessageDelegate)obj4);
			}
			else
			{
				object obj5 = <>O.<4>__OnState;
				if (obj5 == null)
				{
					HandleNamedMessageDelegate val5 = OnState;
					<>O.<4>__OnState = val5;
					obj5 = (object)val5;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.State", (HandleNamedMessageDelegate)obj5);
				object obj6 = <>O.<5>__OnReveal;
				if (obj6 == null)
				{
					HandleNamedMessageDelegate val6 = OnReveal;
					<>O.<5>__OnReveal = val6;
					obj6 = (object)val6;
				}
				customMessagingManager.RegisterNamedMessageHandler("DanielLC.PirateShop.Reveal", (HandleNamedMessageDelegate)obj6);
				SendToHost("DanielLC.PirateShop.Request", null);
			}
			_registered = true;
		}

		public static void Unregister()
		{
			CustomMessagingManager val = (((Object)(object)NetworkManager.Singleton != (Object)null) ? NetworkManager.Singleton.CustomMessagingManager : null);
			if (val != null)
			{
				string[] allMessages = AllMessages;
				foreach (string text in allMessages)
				{
					try
					{
						val.UnregisterNamedMessageHandler(text);
					}
					catch (Exception)
					{
					}
				}
			}
			_registered = false;
			Found.Reset();
		}

		public static void ReportUsed(string key)
		{
			if (IsHost)
			{
				State.HostMarkUsed(key);
				return;
			}
			State.LocalMarkUsed(key);
			SendToHost("DanielLC.PirateShop.Use", delegate(FastBufferWriter w)
			{
				((FastBufferWriter)(ref w)).WriteValueSafe(key, false);
			});
		}

		public static void RequestActivate()
		{
			if (IsHost)
			{
				State.HostActivate();
			}
			else
			{
				SendToHost("DanielLC.PirateShop.Activate", null);
			}
		}

		public static void ReportFound(PirateTokenItem token, string finder)
		{
			if ((Object)(object)token == (Object)null)
			{
				return;
			}
			if (IsHost)
			{
				HostFound(token, finder);
				return;
			}
			NetworkObject networkObject = ((NetworkBehaviour)token).NetworkObject;
			if ((Object)(object)networkObject == (Object)null || !networkObject.IsSpawned)
			{
				Plugin.Log.LogWarning((object)"Pirate token reveal: picked up a token that isn't spawned on the network.");
				return;
			}
			ulong id = networkObject.NetworkObjectId;
			SendToHost("DanielLC.PirateShop.Found", delegate(FastBufferWriter w)
			{
				//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)
				((FastBufferWriter)(ref w)).WriteValueSafe<ulong>(ref id, default(ForPrimitives));
				((FastBufferWriter)(ref w)).WriteValueSafe(finder ?? "", false);
			});
		}

		private static void HostFound(PirateTokenItem token, string finder)
		{
			if (Found.Claim(token))
			{
				finder = (string.IsNullOrEmpty(finder) ? "A crewmate" : finder);
				Plugin.Log.LogInfo((object)("Pirate token: first pickup by " + finder + "; revealing it to the whole crew."));
				BroadcastReveal(finder);
				Popup.Reveal(finder);
			}
		}

		private static void BroadcastReveal(string finder)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null)
			{
				return;
			}
			List<ulong> list = singleton.ConnectedClientsIds.Where((ulong id) => id != 0).ToList();
			if (list.Count == 0)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(128, (Allocator)2, 4096);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(finder, false);
				singleton.CustomMessagingManager.SendNamedMessage("DanielLC.PirateShop.Reveal", (IReadOnlyList<ulong>)list, val, (NetworkDelivery)3);
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void BroadcastState(ulong? onlyClient = null)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null)
			{
				return;
			}
			List<ulong> list = (onlyClient.HasValue ? new List<ulong> { onlyClient.Value } : singleton.ConnectedClientsIds.Where((ulong id) => id != 0).ToList());
			if (list.Count == 0)
			{
				return;
			}
			string[] array = State.Used.ToArray();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 65536);
			try
			{
				bool active = State.Active;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref active, default(ForPrimitives));
				int activatedAtQuota = State.ActivatedAtQuota;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref activatedAtQuota, default(ForPrimitives));
				activatedAtQuota = array.Length;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref activatedAtQuota, default(ForPrimitives));
				string[] array2 = array;
				foreach (string text in array2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(text, false);
				}
				singleton.CustomMessagingManager.SendNamedMessage("DanielLC.PirateShop.State", (IReadOnlyList<ulong>)list, val, (NetworkDelivery)4);
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void OnState(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			bool active = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref active, default(ForPrimitives));
			int quota = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref quota, default(ForPrimitives));
			int val = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref val, default(ForPrimitives));
			string[] array = new string[Math.Max(0, Math.Min(val, 4096))];
			for (int i = 0; i < array.Length; i++)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref array[i], false);
			}
			State.ApplyFromHost(active, quota, array);
		}

		private static void OnRequest(ulong sender, FastBufferReader reader)
		{
			BroadcastState(sender);
		}

		private static void OnUse(ulong sender, FastBufferReader reader)
		{
			string key = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref key, false);
			State.HostMarkUsed(key);
		}

		private static void OnActivate(ulong sender, FastBufferReader reader)
		{
			State.HostActivate();
		}

		private static void OnFound(ulong sender, FastBufferReader reader)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			ulong key = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref key, default(ForPrimitives));
			string text = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.SpawnManager == null || !singleton.SpawnManager.SpawnedObjects.TryGetValue(key, out var value) || (Object)(object)value == (Object)null)
			{
				return;
			}
			PirateTokenItem component = ((Component)value).GetComponent<PirateTokenItem>();
			if (!((Object)(object)component == (Object)null))
			{
				StartOfRound instance = StartOfRound.Instance;
				PlayerControllerB val = (((Object)(object)instance != (Object)null) ? ((IEnumerable<PlayerControllerB>)instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => (Object)(object)x != (Object)null && x.actualClientId == sender && (x.isPlayerControlled || x.isPlayerDead))) : null);
				HostFound(component, ((Object)(object)val != (Object)null) ? val.playerUsername : text);
			}
		}

		private static void OnReveal(ulong sender, FastBufferReader reader)
		{
			string finder = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref finder, false);
			Popup.Reveal(finder);
		}

		private static void SendToHost(string name, Action<FastBufferWriter> write)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 4096);
			try
			{
				write?.Invoke(val);
				singleton.CustomMessagingManager.SendNamedMessage(name, 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
	internal static class ScrapRoll
	{
		private static readonly Random Rng = new Random();

		public static double PerItemChance
		{
			get
			{
				double num = Math.Max(0.01, Plugin.TargetDaysPerDrop.Value);
				double num2 = Math.Max(0.01, Plugin.BaselineScrapPerDay.Value);
				return Math.Min(1.0, 1.0 / (num * num2));
			}
		}

		[HarmonyPostfix]
		private static void Postfix(RoundManager __instance)
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((NetworkBehaviour)__instance).IsServer || (State.Active && !Plugin.SpawnWhileActive.Value))
				{
					return;
				}
				List<GrabbableObject> list = (from g in Object.FindObjectsOfType<GrabbableObject>()
					where (Object)(object)g != (Object)null && (Object)(object)g.itemProperties != (Object)null && g.itemProperties.isScrap && !g.isInShipRoom && !g.isInElevator && !(g is PirateTokenItem)
					select g).ToList();
				double perItemChance = PerItemChance;
				int num = 0;
				for (int num2 = 0; num2 < list.Count; num2++)
				{
					if (Rng.NextDouble() < perItemChance)
					{
						num++;
					}
				}
				num = Math.Min(num, Math.Max(0, Plugin.MaxPerDay.Value));
				Plugin.Log.LogInfo((object)$"Pirate Shop roll: {list.Count} scrap x {perItemChance:P3} -> {num} token(s).");
				for (int num3 = 0; num3 < num; num3++)
				{
					if (list.Count <= 0)
					{
						break;
					}
					TokenRegistry.TrySpawn(((Component)list[Rng.Next(list.Count)]).transform.position + Vector3.up * 0.25f);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop scrap roll failed: {arg}");
			}
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "daniel.lethalcompany.pirateshopaccess";

		public const string Name = "Pirate Token Shop Access";

		public const string Version = "0.4.0";
	}
	[BepInPlugin("daniel.lethalcompany.pirateshopaccess", "Pirate Token Shop Access", "0.4.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		internal static ConfigEntry<float> TargetDaysPerDrop;

		internal static ConfigEntry<float> BaselineScrapPerDay;

		internal static ConfigEntry<int> MaxPerDay;

		internal static ConfigEntry<bool> SpawnWhileActive;

		internal static ConfigEntry<bool> PopupEnabled;

		internal static ConfigEntry<string> PopupFile;

		internal static ConfigEntry<float> PopupVolume;

		internal static ConfigEntry<float> TokenSize;

		private readonly Harmony _harmony = new Harmony("daniel.lethalcompany.pirateshopaccess");

		private void Awake()
		{
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			TargetDaysPerDrop = ((BaseUnityPlugin)this).Config.Bind<float>("Drop rate", "Target days per drop", 15f, "Average number of days between tokens on a typical moon. The roll is per spawned scrap item, so moons with more scrap find it more often (the per-item rate never changes).");
			BaselineScrapPerDay = ((BaseUnityPlugin)this).Config.Bind<float>("Drop rate", "Baseline scrap per day", 15f, "The scrap count of a 'typical' day. Per-item chance = 1 / (Target days per drop x Baseline scrap per day).");
			MaxPerDay = ((BaseUnityPlugin)this).Config.Bind<int>("Drop rate", "Max tokens per day", 1, "Upper limit on tokens spawned in one day.");
			SpawnWhileActive = ((BaseUnityPlugin)this).Config.Bind<bool>("Drop rate", "Spawn while active", false, "Allow new tokens to spawn while a Pirate Shop is already active.");
			PopupEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Popup", "Enabled", true, "Play the 'You found Pirate Shop Access' video when you first pick up a token. Skipped quietly if the file is missing.");
			PopupFile = ((BaseUnityPlugin)this).Config.Bind<string>("Popup", "File", "token-popup.webm", "Video file next to PirateShopAccess.dll (VP8 WebM with alpha recommended).");
			PopupVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Popup", "Volume", 0.8f, "Popup audio volume, 0 to 1.");
			TokenSize = ((BaseUnityPlugin)this).Config.Bind<float>("Token", "Size", 0.6f, "How wide the token medallion is, in game units (the player is about 2.6 tall).");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			GameObject val = new GameObject("PirateShopAccess.Runner");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<Runner>();
			TokenRegistry.Register();
			if (Chainloader.PluginInfos.ContainsKey("daniel.lethalcompany.modmenu"))
			{
				MenuHooks.Register();
			}
			Log.LogInfo((object)string.Format("{0} {1} loaded. Per-scrap token chance: {2:P3}", "Pirate Token Shop Access", "0.4.0", ScrapRoll.PerItemChance));
		}
	}
	internal static class Plunder
	{
		private enum Kind
		{
			Item,
			Unlockable
		}

		private class Entry
		{
			public string Name;

			public string Key;

			public string Section;

			public Kind Kind;

			public int Index;

			public bool Picked;

			public string Blocked;
		}

		public const int MaxPicks = 12;

		private const int WindowRows = 14;

		private static readonly FieldRef<Terminal, bool> ModifyingText = AccessTools.FieldRefAccess<Terminal, bool>("modifyingText");

		private static List<Entry> _entries;

		private static int _cursor;

		private static string _rendered;

		private static bool _savedRichText;

		private static Terminal _terminal;

		public static bool IsOpen => _entries != null;

		public static string StoreHint => "Pirate Shop: type 'plunder' to take what's free today (pick up to " + 12 + ").";

		public static void Open(Terminal t)
		{
			_terminal = t;
			_entries = BuildEntries(t);
			_cursor = 0;
			_savedRichText = t.screenText.richText;
			t.screenText.richText = true;
			Plugin.Log.LogInfo((object)$"Pirate Shop: plunder opened with {_entries.Count} free entries.");
			Render();
		}

		public static void Close(bool reloadStore)
		{
			if (!IsOpen)
			{
				return;
			}
			Terminal terminal = _terminal;
			_entries = null;
			_rendered = null;
			_terminal = null;
			if ((Object)(object)terminal == (Object)null)
			{
				return;
			}
			terminal.screenText.richText = _savedRichText;
			if (reloadStore)
			{
				TerminalNode val = FindStoreNode(terminal);
				if ((Object)(object)val != (Object)null)
				{
					terminal.LoadNewNode(val);
				}
			}
		}

		private static TerminalNode FindStoreNode(Terminal t)
		{
			TerminalKeyword val = t.terminalNodes?.allKeywords?.FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword k) => (Object)(object)k != (Object)null && k.word == "store"));
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.specialKeywordResult;
		}

		private static List<Entry> BuildEntries(Terminal t)
		{
			List<Entry> list = new List<Entry>();
			if (t.buyableItemsList != null)
			{
				for (int i = 0; i < t.buyableItemsList.Length; i++)
				{
					Item val = t.buyableItemsList[i];
					string key = "i:" + i;
					if (!((Object)(object)val == (Object)null) && !string.IsNullOrWhiteSpace(val.itemName) && State.IsFree(key))
					{
						list.Add(new Entry
						{
							Name = val.itemName,
							Key = key,
							Kind = Kind.Item,
							Index = i,
							Section = "ITEMS"
						});
					}
				}
			}
			StartOfRound instance = StartOfRound.Instance;
			List<UnlockableItem> unlockables = ((!((Object)(object)instance != (Object)null)) ? null : instance.unlockablesList?.unlockables);
			HashSet<int> seen;
			if (unlockables != null)
			{
				seen = new HashSet<int>();
				foreach (int item in from index in Enumerable.Range(0, unlockables.Count)
					where unlockables[index] != null && unlockables[index].alwaysInStock
					orderby unlockables[index].unlockableName
					select index)
				{
					AddUnlockable(item, "SHIP UPGRADES");
				}
				if (t.ShipDecorSelection != null)
				{
					foreach (TerminalNode item2 in t.ShipDecorSelection)
					{
						if ((Object)(object)item2 != (Object)null)
						{
							AddUnlockable(item2.shipUnlockableID, "DECOR");
						}
					}
				}
			}
			return list;
			void AddUnlockable(int id, string section)
			{
				if (id >= 0 && id < unlockables.Count && seen.Add(id))
				{
					UnlockableItem val2 = unlockables[id];
					string key2 = "u:" + id;
					if (val2 != null && !string.IsNullOrWhiteSpace(val2.unlockableName) && !val2.hasBeenUnlockedByPlayer && !val2.alreadyUnlocked && State.IsFree(key2))
					{
						list.Add(new Entry
						{
							Name = val2.unlockableName,
							Key = key2,
							Kind = Kind.Unlockable,
							Index = id,
							Section = section
						});
					}
				}
			}
		}

		private static int ItemSpace(Terminal t)
		{
			if (!t.vehicleInDropship)
			{
				return Math.Max(0, 12 - t.numberOfItemsInDropship);
			}
			return 0;
		}

		private static bool ShipReady()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (!instance.inShipPhase && !instance.shipHasLanded)
			{
				return false;
			}
			if (!((Object)(object)instance.shipAnimator == (Object)null))
			{
				AnimatorStateInfo currentAnimatorStateInfo = instance.shipAnimator.GetCurrentAnimatorStateInfo(0);
				return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).tagHash == Animator.StringToHash("ShipIdle");
			}
			return true;
		}

		private static void UpdateBlocked(Terminal t)
		{
			int num = _entries.Count((Entry e) => e.Picked);
			int num2 = _entries.Count((Entry e) => e.Picked && e.Kind == Kind.Item);
			int num3 = ItemSpace(t);
			bool flag = ShipReady();
			foreach (Entry entry in _entries)
			{
				entry.Blocked = null;
				if (!entry.Picked)
				{
					if (num >= 12)
					{
						entry.Blocked = "12 picked";
					}
					else if (entry.Kind == Kind.Item && t.vehicleInDropship)
					{
						entry.Blocked = "Cruiser on the way";
					}
					else if (entry.Kind == Kind.Item && num2 >= num3)
					{
						entry.Blocked = "drop ship full";
					}
					else if (entry.Kind == Kind.Unlockable && !flag)
					{
						entry.Blocked = "wait until the ship is still";
					}
				}
			}
		}

		public static void Tick()
		{
			if (!IsOpen)
			{
				return;
			}
			Terminal terminal = _terminal;
			if ((Object)(object)terminal == (Object)null || !terminal.terminalInUse || !State.Active)
			{
				Close(reloadStore: false);
				return;
			}
			Keyboard current = Keyboard.current;
			bool flag = false;
			if (current != null && _entries.Count > 0)
			{
				if (((ButtonControl)current.upArrowKey).wasPressedThisFrame)
				{
					_cursor = (_cursor + _entries.Count - 1) % _entries.Count;
					flag = true;
				}
				if (((ButtonControl)current.downArrowKey).wasPressedThisFrame)
				{
					_cursor = (_cursor + 1) % _entries.Count;
					flag = true;
				}
				if (((ButtonControl)current.leftArrowKey).wasPressedThisFrame || ((ButtonControl)current.rightArrowKey).wasPressedThisFrame || ((ButtonControl)current.spaceKey).wasPressedThisFrame)
				{
					Toggle(terminal, _entries[_cursor]);
					flag = true;
				}
			}
			if (current != null && ((ButtonControl)current.backspaceKey).wasPressedThisFrame)
			{
				Close(reloadStore: true);
			}
			else if (flag || terminal.screenText.text != _rendered)
			{
				Render();
			}
		}

		private static void Toggle(Terminal t, Entry e)
		{
			if (e.Picked)
			{
				e.Picked = false;
				return;
			}
			UpdateBlocked(t);
			if (e.Blocked == null)
			{
				e.Picked = true;
			}
		}

		private static void Render()
		{
			Terminal terminal = _terminal;
			UpdateBlocked(terminal);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("\n\nPIRATE SHOP: PLUNDER\n");
			int num = _entries.Count((Entry e) => e.Picked);
			stringBuilder.Append($"Picked {num}/{12}. Up/Down: move   Left/Right/Space: tick\nEnter: take them   Backspace: back\n\n");
			if (_entries.Count == 0)
			{
				stringBuilder.Append("Nothing left to plunder today.\n");
			}
			else
			{
				int num2 = Mathf.Clamp(_cursor - 7, 0, Math.Max(0, _entries.Count - 14));
				int num3 = Math.Min(_entries.Count, num2 + 14);
				if (num2 > 0)
				{
					stringBuilder.Append("   ...\n");
				}
				string text = ((num2 > 0) ? _entries[num2 - 1].Section : null);
				for (int num4 = num2; num4 < num3; num4++)
				{
					Entry entry = _entries[num4];
					if (entry.Section != text)
					{
						stringBuilder.Append(entry.Section).Append(":\n");
						text = entry.Section;
					}
					string text2 = (entry.Picked ? "[x]" : ((entry.Blocked != null) ? "[-]" : "[ ]"));
					string text3 = ((num4 == _cursor) ? ">" : " ") + " " + text2 + " " + entry.Name;
					if (entry.Blocked != null)
					{
						text3 = "<color=#3f6b3f>" + text3 + ((num4 == _cursor) ? ("  (" + entry.Blocked + ")") : "") + "</color>";
					}
					stringBuilder.Append(text3).Append('\n');
				}
				if (num3 < _entries.Count)
				{
					stringBuilder.Append("   ...\n");
				}
			}
			stringBuilder.Append('\n');
			_rendered = stringBuilder.ToString();
			ModifyingText.Invoke(terminal) = true;
			terminal.screenText.text = _rendered;
			terminal.currentText = _rendered;
			terminal.textAdded = 0;
			terminal.screenText.caretPosition = _rendered.Length;
		}

		public static void Confirm()
		{
			Terminal terminal = _terminal;
			UpdateBlocked(terminal);
			List<Entry> picks = _entries.Where((Entry e) => e.Picked && State.IsFree(e.Key)).ToList();
			if (picks.Count == 0)
			{
				Render();
				return;
			}
			List<string> list = new List<string>();
			List<Entry> list2 = picks.Where((Entry e) => e.Kind == Kind.Item).Take(ItemSpace(terminal)).ToList();
			if (list2.Count > 0)
			{
				foreach (Entry item in list2)
				{
					terminal.orderedItemsFromTerminal.Add(item.Index);
					terminal.numberOfItemsInDropship++;
				}
				if (!((NetworkBehaviour)terminal).IsServer)
				{
					terminal.useCreditsCooldown = true;
					terminal.BuyItemsServerRpc(terminal.orderedItemsFromTerminal.ToArray(), terminal.groupCredits, terminal.numberOfItemsInDropship);
					terminal.orderedItemsFromTerminal.Clear();
				}
				else
				{
					terminal.SyncGroupCreditsClientRpc(terminal.groupCredits, terminal.numberOfItemsInDropship);
				}
				foreach (Entry item2 in list2)
				{
					Net.ReportUsed(item2.Key);
					list.Add(item2.Name);
				}
			}
			if (ShipReady())
			{
				StartOfRound instance = StartOfRound.Instance;
				foreach (Entry item3 in picks.Where((Entry e) => e.Kind == Kind.Unlockable))
				{
					instance.BuyShipUnlockableServerRpc(item3.Index, terminal.groupCredits);
					Net.ReportUsed(item3.Key);
					list.Add(item3.Name);
				}
			}
			Plugin.Log.LogInfo((object)string.Format("Pirate Shop: plundered {0}: {1}", list.Count, string.Join(", ", list)));
			Terminal val = terminal;
			Close(reloadStore: false);
			StringBuilder stringBuilder = new StringBuilder("\n\nPIRATE SHOP: PLUNDERED\n\n");
			foreach (string item4 in list)
			{
				stringBuilder.Append("* ").Append(item4).Append('\n');
			}
			if (list2.Count > 0)
			{
				stringBuilder.Append($"\nItems arrive on the drop ship ({val.numberOfItemsInDropship} on route).\n");
			}
			if (list.Any((string n) => picks.Any((Entry p) => p.Name == n && p.Kind == Kind.Unlockable)))
			{
				stringBuilder.Append("Press B to move and place objects in the ship.\n");
			}
			stringBuilder.Append('\n');
			ModifyingText.Invoke(val) = true;
			val.screenText.text = stringBuilder.ToString();
			val.currentText = val.screenText.text;
			val.textAdded = 0;
		}
	}
	[HarmonyPatch(typeof(Terminal), "OnSubmit")]
	internal static class PlunderSubmitPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(Terminal __instance)
		{
			try
			{
				if (!__instance.terminalInUse)
				{
					return true;
				}
				if (Plunder.IsOpen)
				{
					Plunder.Confirm();
					Refocus(__instance);
					return false;
				}
				if (!State.Active || __instance.textAdded <= 0)
				{
					return true;
				}
				string text = __instance.screenText.text;
				if (text.Substring(Math.Max(0, text.Length - __instance.textAdded)).Trim().ToLowerInvariant() != "plunder")
				{
					return true;
				}
				Plunder.Open(__instance);
				Refocus(__instance);
				return false;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop plunder failed: {arg}");
				Plunder.Close(reloadStore: false);
				return true;
			}
		}

		private static void Refocus(Terminal t)
		{
			t.screenText.ActivateInputField();
			((Selectable)t.screenText).Select();
		}
	}
	[HarmonyPatch(typeof(Terminal), "QuitTerminal")]
	internal static class PlunderQuitPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			Plunder.Close(reloadStore: false);
		}
	}
	internal static class Popup
	{
		private sealed class BannerFade : MonoBehaviour
		{
			private const float In = 0.35f;

			private const float Hold = 4.5f;

			private const float Out = 0.8f;

			private CanvasGroup _group;

			private float _t;

			internal void Init(CanvasGroup group, AudioSource audio)
			{
				_group = group;
				HUDManager instance = HUDManager.Instance;
				if ((Object)(object)audio != (Object)null && (Object)(object)instance != (Object)null && (Object)(object)instance.globalNotificationSFX != (Object)null)
				{
					audio.PlayOneShot(instance.globalNotificationSFX);
				}
			}

			private void Update()
			{
				_t += Time.unscaledDeltaTime;
				if ((Object)(object)_group != (Object)null)
				{
					_group.alpha = ((_t < 0.35f) ? (_t / 0.35f) : ((_t < 4.85f) ? 1f : (1f - (_t - 0.35f - 4.5f) / 0.8f)));
				}
				if (_t >= 5.65f)
				{
					Object.Destroy((Object)(object)((Component)this).gameObject);
				}
			}
		}

		private static GameObject _current;

		private static GameObject _banner;

		public static string FilePath => Path.Combine(Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? "", Plugin.PopupFile.Value ?? "");

		public static void Reveal(string finder)
		{
			if (Plugin.PopupEnabled.Value)
			{
				if (File.Exists(FilePath))
				{
					Play();
				}
				else
				{
					Banner(finder);
				}
			}
		}

		public static void Banner(string finder)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: 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)
			try
			{
				if ((Object)(object)_banner != (Object)null)
				{
					Object.Destroy((Object)(object)_banner);
				}
				GameObject val = new GameObject("PirateShopAccess.Banner");
				Object.DontDestroyOnLoad((Object)(object)val);
				Canvas obj = val.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 32000;
				CanvasScaler obj2 = val.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 1f;
				CanvasGroup val2 = val.AddComponent<CanvasGroup>();
				val2.alpha = 0f;
				val2.interactable = false;
				val2.blocksRaycasts = false;
				GameObject val3 = new GameObject("Band");
				val3.transform.SetParent(val.transform, false);
				Image obj3 = val3.AddComponent<Image>();
				((Graphic)obj3).raycastTarget = false;
				((Graphic)obj3).color = new Color(0.05f, 0.02f, 0f, 0.72f);
				RectTransform rectTransform = ((Graphic)obj3).rectTransform;
				rectTransform.anchorMin = new Vector2(0f, 0.62f);
				rectTransform.anchorMax = new Vector2(1f, 0.8f);
				Vector2 offsetMin = (rectTransform.offsetMax = Vector2.zero);
				rectTransform.offsetMin = offsetMin;
				HUDManager instance = HUDManager.Instance;
				TMP_FontAsset font = (((Object)(object)instance != (Object)null && instance.controlTipLines != null && instance.controlTipLines.Length != 0 && (Object)(object)instance.controlTipLines[0] != (Object)null) ? ((TMP_Text)instance.controlTipLines[0]).font : null);
				Line(val3.transform, "PIRATE TOKEN FOUND", 64f, new Color(1f, 0.62f, 0.15f), font, 0.48f, 1f);
				Line(text: (string.IsNullOrEmpty(finder) ? "A crewmate" : finder) + " found Pirate Shop Access. Use it to open the Pirate Shop for the crew.", parent: val3.transform, size: 30f, colour: new Color(1f, 0.93f, 0.82f), font: font, yMin: 0f, yMax: 0.46f);
				AudioSource val4 = val.AddComponent<AudioSource>();
				val4.spatialBlend = 0f;
				val4.volume = Mathf.Clamp01(Plugin.PopupVolume.Value);
				val.AddComponent<BannerFade>().Init(val2, val4);
				_banner = val;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Pirate Shop banner error: {arg}");
			}
		}

		private static void Line(Transform parent, string text, float size, Color colour, TMP_FontAsset font, float yMin, float yMax)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Text");
			val.transform.SetParent(parent, false);
			TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)val2).font = font;
			}
			((TMP_Text)val2).text = text;
			((TMP_Text)val2).fontSize = size;
			((Graphic)val2).color = colour;
			((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val2).enableWordWrapping = true;
			((Graphic)val2).raycastTarget = false;
			RectTransform rectTransform = ((TMP_Text)val2).rectTransform;
			rectTransform.anchorMin = new Vector2(0.05f, yMin);
			rectTransform.anchorMax = new Vector2(0.95f, yMax);
			Vector2 offsetMin = (rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
		}

		public static void Play()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Expected O, but got Unknown
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			try
			{
				if (!Plugin.PopupEnabled.Value || (Object)(object)_current != (Object)null)
				{
					return;
				}
				string filePath = FilePath;
				if (!File.Exists(filePath))
				{
					Plugin.Log.LogDebug((object)("Pirate Shop popup skipped: no video at " + filePath + "."));
					return;
				}
				GameObject root = new GameObject("PirateShopAccess.Popup");
				Object.DontDestroyOnLoad((Object)(object)root);
				Canvas obj = root.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 32000;
				GameObject val = new GameObject("Video");
				val.transform.SetParent(root.transform, false);
				RawImage image = val.AddComponent<RawImage>();
				((Graphic)image).raycastTarget = false;
				((Behaviour)image).enabled = false;
				RectTransform rectTransform = ((Graphic)image).rectTransform;
				rectTransform.anchorMin = Vector2.zero;
				rectTransform.anchorMax = Vector2.one;
				rectTransform.offsetMin = Vector2.zero;
				rectTransform.offsetMax = Vector2.zero;
				AspectRatioFitter obj2 = val.AddComponent<AspectRatioFitter>();
				obj2.aspectMode = (AspectMode)3;
				obj2.aspectRatio = 1.7777778f;
				RenderTexture texture = new RenderTexture(1920, 1080, 0, (RenderTextureFormat)0);
				texture.Create();
				image.texture = (Texture)(object)texture;
				AudioSource val2 = root.AddComponent<AudioSource>();
				val2.playOnAwake = false;
				val2.spatialBlend = 0f;
				val2.volume = Mathf.Clamp01(Plugin.PopupVolume.Value);
				VideoPlayer obj3 = root.AddComponent<VideoPlayer>();
				obj3.playOnAwake = false;
				obj3.isLooping = false;
				obj3.source = (VideoSource)1;
				obj3.url = filePath;
				obj3.renderMode = (VideoRenderMode)2;
				obj3.targetTexture = texture;
				obj3.audioOutputMode = (VideoAudioOutputMode)1;
				obj3.controlledAudioTrackCount = 1;
				obj3.EnableAudioTrack((ushort)0, true);
				obj3.SetTargetAudioSource((ushort)0, val2);
				obj3.prepareCompleted += (EventHandler)delegate(VideoPlayer p)
				{
					((Behaviour)image).enabled = true;
					p.Play();
				};
				obj3.loopPointReached += (EventHandler)delegate
				{
					Finish(root, texture);
				};
				obj3.errorReceived += (ErrorEventHandler)delegate(VideoPlayer p, string message)
				{
					Plugin.Log.LogWarning((object)("Pirate Shop popup failed to play: " + message));
					Finish(root, texture);
				};
				_current = root;
				obj3.Prepare();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Pirate Shop popup error: {arg}");
			}
		}

		private static void Finish(GameObject root, RenderTexture texture)
		{
			if ((Object)(object)texture != (Object)null)
			{
				texture.Release();
			}
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			_current = null;
		}
	}
	internal class Runner : MonoBehaviour
	{
		private void Update()
		{
			Plunder.Tick();
		}
	}
	internal static class State
	{
		private const string SaveKey = "DanielLC_PirateShopAccess";

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

		public static bool Active { get; private set; }

		public static int ActivatedAtQuota { get; private set; } = -1;

		public static IReadOnlyCollection<string> Used => UsedToday;

		public static bool IsFree(string key)
		{
			if (Active && key != null)
			{
				return !UsedToday.Contains(key);
			}
			return false;
		}

		public static void HostActivate()
		{
			if (Net.IsHost)
			{
				if (Active)
				{
					Plugin.Log.LogInfo((object)"Pirate Shop is already active; token ignored.");
					return;
				}
				int num = (((Object)(object)TimeOfDay.Instance != (Object)null) ? TimeOfDay.Instance.timesFulfilledQuota : 0);
				Set(active: true, num, Array.Empty<string>());
				Plugin.Log.LogInfo((object)$"Pirate Shop activated (quota #{num}).");
				Net.BroadcastState();
			}
		}

		public static void HostDeactivate(string reason)
		{
			if (Net.IsHost && Active)
			{
				Set(active: false, -1, Array.Empty<string>());
				Plugin.Log.LogInfo((object)("Pirate Shop ended: " + reason + "."));
				Net.BroadcastState();
			}
		}

		public static void HostNewDay()
		{
			if (Net.IsHost && Active && UsedToday.Count != 0)
			{
				UsedToday.Clear();
				Plugin.Log.LogInfo((object)"Pirate Shop: new day, free items reset.");
				Net.BroadcastState();
			}
		}

		public static void HostMarkUsed(string key)
		{
			if (Net.IsHost && Active && !string.IsNullOrEmpty(key) && UsedToday.Add(key))
			{
				Net.BroadcastState();
			}
		}

		public static void LocalMarkUsed(string key)
		{
			if (Active && !string.IsNullOrEmpty(key))
			{
				UsedToday.Add(key);
			}
		}

		public static void ApplyFromHost(bool active, int quota, string[] used)
		{
			Set(active, quota, used);
		}

		public static void ResetLocal()
		{
			Active = false;
			ActivatedAtQuota = -1;
			UsedToday.Clear();
		}

		private static void Set(bool active, int quota, IEnumerable<string> used)
		{
			bool active2 = Active;
			Active = active;
			ActivatedAtQuota = (active ? quota : (-1));
			UsedToday.Clear();
			if (active)
			{
				foreach (string item in used)
				{
					if (!string.IsNullOrEmpty(item))
					{
						UsedToday.Add(item);
					}
				}
			}
			if (active2 != active)
			{
				Hud.AnnounceStateChange(active);
			}
		}

		public static string Serialize()
		{
			if (!Active)
			{
				return "0";
			}
			return string.Format("1|{0}|{1}", ActivatedAtQuota, string.Join(",", UsedToday));
		}

		public static void Save(string saveFile)
		{
			try
			{
				ES3.Save<string>("DanielLC_PirateShopAccess", Serialize(), saveFile);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not save Pirate Shop state: {arg}");
			}
		}

		public static void Load(string saveFile)
		{
			string text = "0";
			try
			{
				if (ES3.KeyExists("DanielLC_PirateShopAccess", saveFile))
				{
					text = ES3.Load<string>("DanielLC_PirateShopAccess", saveFile, "0");
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not load Pirate Shop state: {arg}");
			}
			string[] array = (text ?? "0").Split('|');
			if (array[0] == "1" && array.Length >= 2 && int.TryParse(array[1], out var result))
			{
				object source = ((array.Length >= 3 && array[2].Length > 0) ? ((object)array[2].Split(',')) : ((object)Array.Empty<string>()));
				Active = true;
				ActivatedAtQuota = result;
				UsedToday.Clear();
				foreach (string item in ((IEnumerable<string>)source).Where((string k) => k.Length > 0))
				{
					UsedToday.Add(item);
				}
				Plugin.Log.LogInfo((object)$"Pirate Shop restored from save (quota #{result}, {UsedToday.Count} used today).");
			}
			else
			{
				ResetLocal();
			}
		}

		public static void DeleteSave(string saveFile)
		{
			try
			{
				if (ES3.KeyExists("DanielLC_PirateShopAccess", saveFile))
				{
					ES3.DeleteKey("DanielLC_PirateShopAccess", saveFile);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not clear Pirate Shop save: {arg}");
			}
		}
	}
	public class PirateTokenItem : GrabbableObject
	{
		private bool _announced;

		private Transform _model;

		private Vector3 _meshCentre;

		private Light _light;

		private BoxCollider _collider;

		private Renderer _renderer;

		private MaterialPropertyBlock _mpb;

		private float _phase;

		private SkinnedMeshRenderer _handRig;

		private Transform _handL;

		private Transform _handR;

		public override void Start()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0051: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			((GrabbableObject)this).Start();
			_model = ((Component)this).transform.Find("Model");
			_renderer = (Renderer)(object)base.mainObjectRenderer;
			if ((Object)(object)_model != (Object)null && (Object)(object)_renderer != (Object)null)
			{
				Transform model = _model;
				Bounds bounds = _renderer.bounds;
				_meshCentre = model.InverseTransformPoint(((Bounds)(ref bounds)).center);
			}
			_light = ((Component)this).GetComponentInChildren<Light>(true);
			_collider = ((Component)this).GetComponent<BoxCollider>();
			_mpb = new MaterialPropertyBlock();
			_phase = Random.value * 10f;
		}

		public override void LateUpdate()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: 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_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			((GrabbableObject)this).LateUpdate();
			if ((Object)(object)_model == (Object)null)
			{
				return;
			}
			float num = Time.time + _phase;
			if ((Object)(object)_light != (Object)null)
			{
				((Behaviour)_light).enabled = !base.isPocketed;
			}
			if (base.isPocketed)
			{
				return;
			}
			if (!base.isHeld || !((Object)(object)base.parentObject != (Object)null) || !((Object)(object)base.playerHeldBy != (Object)null) || !HandPose(out var centre, out var rot))
			{
				if (base.isHeld && (Object)(object)base.parentObject != (Object)null && (Object)(object)base.playerHeldBy != (Object)null)
				{
					centre = ((Component)this).transform.position;
					rot = Quaternion.LookRotation(((Component)base.playerHeldBy).transform.forward, Vector3.up);
				}
				else
				{
					float num2 = Plugin.TokenSize.Value * 0.5f;
					bool flag = base.hasHitGround && base.reachedFloorTarget && !base.isHeld;
					float num3 = (flag ? (num2 + 0.1f - base.itemProperties.verticalOffset) : 0f);
					Vector3 val = ((Component)this).transform.position + Vector3.up * num3;
					float num4 = (flag ? ((0.5f + 0.5f * Mathf.Sin(num * 2f)) * 0.08f) : 0f);
					centre = val + Vector3.up * num4;
					rot = Quaternion.Euler(0f, num * 90f % 360f, 0f);
					if ((Object)(object)_collider != (Object)null && flag)
					{
						Vector3 val2 = ((Component)this).transform.InverseTransformPoint(val + Vector3.up * 0.04f);
						Vector3 val3 = _collider.center - val2;
						if (((Vector3)(ref val3)).sqrMagnitude > 1E-06f)
						{
							_collider.center = val2;
							_collider.size = Vector3.one * (2f * num2 + 0.08f);
						}
					}
				}
			}
			_model.rotation = rot;
			_model.position = centre - _model.TransformVector(_meshCentre);
			if (!((Object)(object)_renderer != (Object)null))
			{
				return;
			}
			float num5 = Mathf.Repeat(num, 3.5f);
			float num6 = ((num5 < 0.6f) ? Mathf.Sin(num5 / 0.6f * MathF.PI) : 0f);
			Material[] sharedMaterials = _renderer.sharedMaterials;
			for (int i = 0; i < sharedMaterials.Length; i++)
			{
				if ((Object)(object)sharedMaterials[i] == (Object)null)
				{
					continue;
				}
				if (((Object)sharedMaterials[i]).name.StartsWith("M_Token_Gold"))
				{
					_mpb.SetColor("_EmissiveColor", new Color(1f, 0.7f, 0.25f) * (num6 * 3f));
				}
				else
				{
					if (!((Object)sharedMaterials[i]).name.StartsWith("M_Token_Amber"))
					{
						continue;
					}
					_mpb.SetColor("_EmissiveColor", TokenRegistry.GlowColor * 6f);
				}
				_renderer.SetPropertyBlock(_mpb, i);
			}
		}

		private bool HandPose(out Vector3 centre, out Quaternion rot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: 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_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			centre = default(Vector3);
			rot = default(Quaternion);
			PlayerControllerB playerHeldBy = base.playerHeldBy;
			SkinnedMeshRenderer val = (((Object)(object)base.parentObject == (Object)(object)playerHeldBy.localItemHolder && (Object)(object)playerHeldBy.thisPlayerModelArms != (Object)null && ((Renderer)playerHeldBy.thisPlayerModelArms).enabled) ? playerHeldBy.thisPlayerModelArms : playerHeldBy.thisPlayerModel);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if ((Object)(object)val != (Object)(object)_handRig)
			{
				_handRig = val;
				_handL = (_handR = null);
				Transform[] bones = val.bones;
				foreach (Transform val2 in bones)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						if (((Object)val2).name == "hand.L")
						{
							_handL = val2;
						}
						else if (((Object)val2).name == "hand.R")
						{
							_handR = val2;
						}
					}
				}
			}
			if ((Object)(object)_handL == (Object)null || (Object)(object)_handR == (Object)null)
			{
				return false;
			}
			Vector3 val3 = Vector3.ProjectOnPlane(((Component)playerHeldBy).transform.forward, Vector3.up);
			Vector3 normalized = ((Vector3)(ref val3)).normalized;
			Vector3 val4 = Vector3.up;
			if ((Object)(object)playerHeldBy.gameplayCamera != (Object)null)
			{
				val4 = Quaternion.AngleAxis(Vector3.SignedAngle(normalized, ((Component)playerHeldBy.gameplayCamera).transform.forward, Vector3.Cross(Vector3.up, normalized)) * 0.5f, Vector3.Cross(Vector3.up, normalized)) * Vector3.up;
			}
			val3 = Vector3.Cross(Vector3.Cross(val4, normalized), val4);
			rot = Quaternion.LookRotation(((Vector3)(ref val3)).normalized, val4);
			centre = (_handL.position + _handR.position) * 0.5f + normalized * 0.1f + val4 * 0f;
			return true;
		}

		public override void GrabItem()
		{
			((GrabbableObject)this).GrabItem();
			if (!_announced && !((Object)(object)base.playerHeldBy == (Object)null) && !((Object)(object)base.playerHeldBy != (Object)(object)GameNetworkManager.Instance.localPlayerController))
			{
				_announced = true;
				Net.ReportFound(this, base.playerHeldBy.playerUsername);
			}
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (!buttonDown || (Object)(object)base.playerHeldBy == (Object)null || (Object)(object)base.playerHeldBy != (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				return;
			}
			if (State.Active)
			{
				HUDManager instance = HUDManager.Instance;
				if (instance != null)
				{
					instance.DisplayTip("Pirate Shop", "Your Pirate Shop is already active. Save this token for later.", false, false, "LC_Tip1");
				}
				return;
			}
			Net.RequestActivate();
			base.playerHeldBy.DespawnHeldObject();
			HUDManager instance2 = HUDManager.Instance;
			if (instance2 != null)
			{
				instance2.ClearControlTips();
			}
		}
	}
	internal static class TokenRegistry
	{
		private static readonly string[] Templates = new string[4] { "Cookie mold pan", "Whoopie cushion", "Hair brush", "Gold bar" };

		private static readonly string[] HoldTemplates = new string[3] { "Apparatus", "V-type engine", "Large axle" };

		private const float ModelBuiltSize = 0.2f;

		internal const float BobHeight = 0.08f;

		internal const float HoverGap = 0.1f;

		internal const float SpinSpeed = 90f;

		internal static readonly Color GlowColor = new Color(1f, 0.45f, 0.05f);

		internal const float GemGlow = 6f;

		internal const float LightLumen = 125f;

		internal const float HoldAhead = 0.1f;

		internal const float HoldRaise = 0f;

		private const string HoldAnim = "HoldForward";

		internal const float LightRange = 3f;

		internal const float GlintStrength = 3f;

		private static GameObject _model;

		private static GameObject _container;

		public static Vector3 HoldCentre { get; private set; }

		public static Vector3 HoldAxis { get; private set; } = Vector3.right;

		public static GameObject Prefab { get; private set; }

		public static Item Item { get; private set; }

		public static void Register()
		{
			try
			{
				using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PirateShopAccess.pirate_token"))
				{
					if (stream == null)
					{
						Plugin.Log.LogError((object)"Pirate Shop: the embedded token bundle is missing.");
						return;
					}
					AssetBundle val = AssetBundle.LoadFromStream(stream);
					_model = (((Object)(object)val != (Object)null) ? val.LoadAsset<GameObject>("PirateTokenModel") : null);
				}
				if ((Object)(object)_model == (Object)null)
				{
					Plugin.Log.LogError((object)"Pirate Shop: couldn't load PirateTokenModel from the token bundle.");
				}
				else
				{
					Plugin.Log.LogInfo((object)"Pirate Shop: token model loaded from the bundle.");
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop: token bundle failed to load: {arg}");
			}
		}

		internal static void BuildPrefab()
		{
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Invalid comparison between Unknown and I4
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_052e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0544: Unknown result type (might be due to invalid IL or missing references)
			//IL_0579: Unknown result type (might be due to invalid IL or missing references)
			//IL_057e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0582: Unknown result type (might be due to invalid IL or missing references)
			//IL_058e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0839: Unknown result type (might be due to invalid IL or missing references)
			//IL_084d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0861: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_064e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0662: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Prefab != (Object)null)
			{
				return;
			}
			if ((Object)(object)_model == (Object)null)
			{
				Plugin.Log.LogError((object)"Pirate Shop: no token model, so no token item.");
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null)
			{
				Plugin.Log.LogError((object)"Pirate Shop: no NetworkManager at GameNetworkManager.Start.");
				return;
			}
			List<GrabbableObject> candidates = (from p in singleton.NetworkConfig.Prefabs.Prefabs
				select (!((Object)(object)p.Prefab != (Object)null)) ? null : p.Prefab.GetComponent<GrabbableObject>() into g
				where (Object)(object)g != (Object)null && (Object)(object)g.itemProperties != (Object)null
				select g).ToList();
			GrabbableObject val = Templates.Select((string n) => ((IEnumerable<GrabbableObject>)candidates).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject g) => g.itemProperties.itemName == n))).FirstOrDefault<GrabbableObject>((Func<GrabbableObject, bool>)((GrabbableObject g) => (Object)(object)g != (Object)null)) ?? ((IEnumerable<GrabbableObject>)candidates).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject g) => g.itemProperties.isScrap && !g.itemProperties.twoHanded));
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"Pirate Shop: no vanilla scrap item to base the token on.");
				return;
			}
			_container = new GameObject("PirateShopAccess.Prefabs");
			_container.SetActive(false);
			((Object)_container).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)_container);
			GameObject val2 = new GameObject("PirateShopToken");
			val2.transform.SetParent(_container.transform, false);
			val2.layer = ((Component)val).gameObject.layer;
			val2.tag = ((Component)val).gameObject.tag;
			NetworkObject obj = val2.AddComponent<NetworkObject>();
			AccessTools.Field(typeof(NetworkObject), "GlobalObjectIdHash").SetValue(obj, StableHash("daniel.lethalcompany.pirateshopaccess.PirateShopToken"));
			AudioSource component = ((Component)val).GetComponent<AudioSource>();
			AudioSource val3 = val2.AddComponent<AudioSource>();
			val3.playOnAwake = false;
			if ((Object)(object)component != (Object)null)
			{
				val3.outputAudioMixerGroup = component.outputAudioMixerGroup;
				val3.spatialBlend = component.spatialBlend;
				val3.rolloffMode = component.rolloffMode;
				val3.minDistance = component.minDistance;
				val3.maxDistance = component.maxDistance;
				val3.dopplerLevel = component.dopplerLevel;
				val3.volume = component.volume;
				val3.priority = component.priority;
				if ((int)component.rolloffMode == 2)
				{
					val3.SetCustomCurve((AudioSourceCurveType)0, component.GetCustomCurve((AudioSourceCurveType)0));
				}
			}
			GameObject val4 = Object.Instantiate<GameObject>(_model, val2.transform, false);
			((Object)val4).name = "Model";
			int num = ThinAxis(LocalBounds(((Component)val).transform, ((Component)val).gameObject));
			val4.transform.localRotation = (Quaternion)(num switch
			{
				1 => Quaternion.Euler(-90f, 0f, 0f), 
				0 => Quaternion.Euler(0f, 90f, 0f), 
				_ => Quaternion.identity, 
			});
			val4.transform.localScale = Vector3.one * (Plugin.TokenSize.Value / 0.2f);
			Bounds val5 = LocalBounds(val2.transform, val4);
			val4.transform.localPosition = -((Bounds)(ref val5)).center;
			val5 = LocalBounds(val2.transform, val4);
			Transform[] componentsInChildren = val4.GetComponentsInChildren<Transform>(true);
			for (int num2 = 0; num2 < componentsInChildren.Length; num2++)
			{
				((Component)componentsInChildren[num2]).gameObject.layer = val2.layer;
			}
			BoxCollider obj2 = val2.AddComponent<BoxCollider>();
			obj2.center = ((Bounds)(ref val5)).center;
			obj2.size = Vector3.Max(((Bounds)(ref val5)).size, Vector3.one * 0.05f);
			ScanNodeProperties componentInChildren = ((Component)val).GetComponentInChildren<ScanNodeProperties>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				ScanNodeProperties component2 = Object.Instantiate<GameObject>(((Component)componentInChildren).gameObject, val2.transform, false).GetComponent<ScanNodeProperties>();
				((Component)component2).transform.localPosition = Vector3.zero;
				component2.headerText = "Pirate Token Shop Access";
				component2.subText = "Use it to open the Pirate Shop";
				component2.scrapValue = 0;
			}
			Item = Object.Instantiate<Item>(val.itemProperties);
			((Object)Item).name = "PirateShopToken";
			Item.itemName = "Pirate Token Shop Access";
			Item.spawnPrefab = val2;
			Item.isScrap = true;
			Item.minValue = (Item.maxValue = 0);
			GrabbableObject val6 = HoldTemplates.Select((string n) => ((IEnumerable<GrabbableObject>)candidates).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject g) => g.itemProperties.itemName == n))).FirstOrDefault<GrabbableObject>((Func<GrabbableObject, bool>)((GrabbableObject g) => (Object)(object)g != (Object)null)) ?? ((IEnumerable<GrabbableObject>)candidates).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject g) => g.itemProperties.isScrap && g.itemProperties.twoHanded));
			if ((Object)(object)val6 != (Object)null)
			{
				Item itemProperties = val6.itemProperties;
				Item.twoHanded = true;
				Item.twoHandedAnimation = itemProperties.twoHandedAnimation;
				Item.grabAnim = "HoldForward";
				Item.positionOffset = itemProperties.positionOffset;
				Item.rotationOffset = itemProperties.rotationOffset;
				Item.grabSFX = itemProperties.grabSFX;
				Item.dropSFX = itemProperties.dropSFX;
				Bounds val7 = LocalBounds(((Component)val6).transform, ((Component)val6).gameObject);
				int num3 = ((!(((Bounds)(ref val7)).size.x >= ((Bounds)(ref val7)).size.y) || !(((Bounds)(ref val7)).size.x >= ((Bounds)(ref val7)).size.z)) ? ((((Bounds)(ref val7)).size.y >= ((Bounds)(ref val7)).size.z) ? 1 : 2) : 0);
				HoldCentre = ((Bounds)(ref val7)).center;
				HoldAxis = (Vector3)(num3 switch
				{
					1 => Vector3.up, 
					0 => Vector3.right, 
					_ => Vector3.forward, 
				});
				Plugin.Log.LogInfo((object)("Pirate Shop: token carried two-handed like \"" + itemProperties.itemName + "\" (anim HoldForward, " + $"its size {((Bounds)(ref val7)).size.x:F2} x {((Bounds)(ref val7)).size.y:F2} x {((Bounds)(ref val7)).size.z:F2}, centre {((Bounds)(ref val7)).center}, " + string.Format("hand-to-hand axis {0}).", "XYZ"[num3])));
			}
			else
			{
				Item.twoHanded = (Item.twoHandedAnimation = false);
				Plugin.Log.LogWarning((object)"Pirate Shop: no two-handed vanilla item found, so the token is one-handed.");
			}
			Item item = Item;
			float verticalOffset = Item.verticalOffset;
			Vector3 size = ((Bounds)(ref val5)).size;
			item.verticalOffset = Mathf.Max(verticalOffset, ((Vector3)(ref size))[num] / 2f + 0.01f);
			Item.requiresBattery = false;
			Item.isConductiveMetal = false;
			Item.isDefensiveWeapon = false;
			Item.holdButtonUse = false;
			Item.syncUseFunction = false;
			Item.saveItemVariable = false;
			Item.canBeGrabbedBeforeGameStart = true;
			Item.creditsWorth = 0;
			Item.meshVariants = (Mesh[])(object)new Mesh[0];
			Item.materialVariants = (Material[])(object)new Material[0];
			Item.spawnPositionTypes = new List<ItemGroup>();
			Item.toolTips = new string[1] { "Open the Pirate Shop : [LMB]" };
			PirateTokenItem pirateTokenItem = val2.AddComponent<PirateTokenItem>();
			((GrabbableObject)pirateTokenItem).itemProperties = Item;
			((GrabbableObject)pirateTokenItem).grabbable = true;
			((GrabbableObject)pirateTokenItem).grabbableToEnemies = true;
			((GrabbableObject)pirateTokenItem).isInFactory = true;
			((GrabbableObject)pirateTokenItem).scrapValue = 0;
			((GrabbableObject)pirateTokenItem).mainObjectRenderer = val4.GetComponentInChildren<MeshRenderer>();
			AddGlowLight(val2);
			Prefab = val2;
			singleton.AddNetworkPrefab(val2);
			Plugin.Log.LogInfo((object)("Pirate Shop: token item built from \"" + val.itemProperties.itemName + "\" " + string.Format("(thin axis {0}, size {1:F2} x {2:F2} x {3:F2}).", "XYZ"[num], ((Bounds)(ref val5)).size.x, ((Bounds)(ref val5)).size.y, ((Bounds)(ref val5)).size.z)));
		}

		private static void AddGlowLight(GameObject go)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			Transform val = go.transform.Find("Model");
			GameObject val2 = new GameObject("Glow");
			val2.transform.SetParent(((Object)(object)val != (Object)null) ? val : go.transform, false);
			val2.layer = go.layer;
			Light obj = val2.AddComponent<Light>();
			obj.type = (LightType)2;
			obj.color = GlowColor;
			obj.range = 3f;
			obj.shadows = (LightShadows)0;
			HDAdditionalLightData obj2 = val2.AddComponent<HDAdditionalLightData>();
			obj2.SetIntensity(125f, (LightUnit)0);
			obj2.SetRange(3f);
			obj2.SetColor(GlowColor, -1f);
			obj2.EnableShadows(false);
		}

		internal static void AddToItemList(StartOfRound sor)
		{
			if (!((Object)(object)Item == (Object)null) && sor?.allItemsList?.itemsList != null && !sor.allItemsList.itemsList.Contains(Item))
			{
				sor.allItemsList.itemsList.Add(Item);
			}
		}

		public static bool TrySpawn(Vector3 position)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			if (!Net.IsHost)
			{
				return false;
			}
			if ((Object)(object)Prefab == (Object)null)
			{
				Plugin.Log.LogWarning((object)$"Pirate Shop: a token would spawn at {position}, but the token item isn't built.");
				return false;
			}
			Transform val = (((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.spawnedScrapContainer != (Object)null) ? RoundManager.Instance.spawnedScrapContainer : null);
			GameObject obj = Object.Instantiate<GameObject>(Prefab, position, Quaternion.identity, val);
			GrabbableObject component = obj.GetComponent<GrabbableObject>();
			if ((Object)(object)component != (Object)null)
			{
				component.fallTime = 0f;
				component.scrapValue = 0;
			}
			obj.GetComponent<NetworkObject>().Spawn(false);
			Plugin.Log.LogInfo((object)$"Pirate Shop: token spawned at {position}.");
			return true;
		}

		private static uint StableHash(string s)
		{
			using MD5 mD = MD5.Create();
			return BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes(s)), 0);
		}

		private static int ThinAxis(Bounds b)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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)
			Vector3 size = ((Bounds)(ref b)).size;
			if (!(size.x <= size.y) || !(size.x <= size.z))
			{
				if (!(size.y <= size.z))
				{
					return 2;
				}
				return 1;
			}
			return 0;
		}

		private static Bounds LocalBounds(Transform root, GameObject obj)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			bool any = false;
			Bounds b = default(Bounds);
			MeshFilter[] componentsInChildren = obj.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val in componentsInChildren)
			{
				if ((Object)(object)((Component)val).GetComponent<MeshRenderer>() != (Object)null)
				{
					Add(((Component)val).transform, val.sharedMesh);
				}
			}
			SkinnedMeshRenderer[] componentsInChildren2 = obj.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val2 in componentsInChildren2)
			{
				Add(((Component)val2).transform, val2.sharedMesh);
			}
			return b;
			void Add(Transform t, Mesh mesh)
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: 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)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)mesh == (Object)null))
				{
					Matrix4x4 val3 = root.worldToLocalMatrix * t.localToWorldMatrix;
					Bounds bounds = mesh.bounds;
					for (int j = 0; j < 8; j++)
					{
						Vector3 val4 = ((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)(((j & 1) != 0) ? 1 : (-1)), (float)(((j & 2) != 0) ? 1 : (-1)), (float)(((j & 4) != 0) ? 1 : (-1))));
						Vector3 val5 = ((Matrix4x4)(ref val3)).MultiplyPoint3x4(val4);
						if (!any)
						{
							b = new Bounds(val5, Vector3.zero);
							any = true;
						}
						else
						{
							((Bounds)(ref b)).Encapsulate(val5);
						}
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class TokenPatches
	{
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPostfix]
		private static void GameNetworkManagerStart()
		{
			Build("GameNetworkManager.Start");
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuManagerStart()
		{
			Build("MenuManager.Start");
		}

		private static void Build(string from)
		{
			if ((Object)(object)TokenRegistry.Prefab != (Object)null)
			{
				return;
			}
			Plugin.Log.LogInfo((object)("Pirate Shop: building the token item (" + from + ")."));
			try
			{
				TokenRegistry.BuildPrefab();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop: building the token item failed: {arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void StartOfRoundAwake(StartOfRound __instance)
		{
			try
			{
				TokenRegistry.AddToItemList(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop: adding the token to the item list failed: {arg}");
			}
		}
	}
}
namespace PirateShopAccess.Patches
{
	[HarmonyPatch]
	internal static class LifecyclePatches
	{
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		private static void StartOfRoundStart(StartOfRound __instance)
		{
			State.ResetLocal();
			Net.Register();
			if (Net.IsHost && !__instance.isChallengeFile && (Object)(object)GameNetworkManager.Instance != (Object)null)
			{
				State.Load(GameNetworkManager.Instance.currentSaveFileName);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDestroy")]
		[HarmonyPrefix]
		private static void StartOfRoundDestroy()
		{
			Net.Unregister();
			State.ResetLocal();
		}

		[HarmonyPatch(typeof(TimeOfDay), "OnDayChanged")]
		[HarmonyPostfix]
		private static void DayChanged()
		{
			if (Net.IsHost)
			{
				State.HostNewDay();
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ArriveAtLevel")]
		[HarmonyPostfix]
		private static void ArriveAtLevel(StartOfRound __instance)
		{
			if (Net.IsHost && (Object)(object)__instance.currentLevel != (Object)null && __instance.currentLevel.levelID == 3)
			{
				State.HostDeactivate("arrived at 71 Gordion");
			}
		}

		[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
		[HarmonyPostfix]
		private static void NewQuota()
		{
			if (Net.IsHost)
			{
				State.HostDeactivate("quota complete");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		[HarmonyPostfix]
		private static void ShipReset()
		{
			if (Net.IsHost)
			{
				State.HostDeactivate("ship reset / game over");
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
		[HarmonyPostfix]
		private static void SaveGameValues(GameNetworkManager __instance)
		{
			try
			{
				if (__instance.isHostingGame && !((Object)(object)StartOfRound.Instance == (Object)null) && !StartOfRound.Instance.isChallengeFile)
				{
					State.Save(__instance.currentSaveFileName);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop save hook failed: {arg}");
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")]
		[HarmonyPostfix]
		private static void ResetSavedGameValues(GameNetworkManager __instance)
		{
			if (__instance.isHostingGame)
			{
				State.DeleteSave(__instance.currentSaveFileName);
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "LoadNewNodeIfAffordable")]
	internal static class TerminalCostPatch
	{
		private static readonly FieldRef<Terminal, int> TotalCost = AccessTools.FieldRefAccess<Terminal, int>("totalCostOfItems");

		private static string _pendingKey;

		private static TerminalNode _pendingNode;

		internal static bool TranspilerApplied { get; private set; }

		internal static TerminalNode PendingNode => _pendingNode;

		internal static bool ClampedAmount { get; private set; }

		[HarmonyPrefix]
		private static void Prefix(Terminal __instance, TerminalNode node)
		{
			_pendingKey = null;
			_pendingNode = null;
			ClampedAmount = false;
			try
			{
				if (State.Active && !((Object)(object)node == (Object)null) && node.buyItemIndex != -1 && State.IsFree(KeyFor(node)) && __instance.playerDefinedAmount > 1)
				{
					Plugin.Log.LogInfo((object)$"Pirate Shop: order of {__instance.playerDefinedAmount} cut to 1 (free item).");
					__instance.playerDefinedAmount = 1;
					ClampedAmount = true;
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop amount clamp failed: {arg}");
			}
		}

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			FieldInfo fieldInfo = AccessTools.Field(typeof(Terminal), "groupCredits");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(Terminal), "totalCostOfItems");
			for (int i = 0; i + 3 < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.LoadsField(list[i + 1], fieldInfo, false) && list[i + 2].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.LoadsField(list[i + 3], fieldInfo2, false))
				{
					CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					CodeInstructionExtensions.MoveLabelsTo(list[i], val);
					CodeInstructionExtensions.MoveBlocksTo(list[i], val);
					list.InsertRange(i, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
					{
						val,
						new CodeInstruction(OpCodes.Ldarg_1, (object)null),
						new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(TerminalCostPatch), "AdjustCost", (Type[])null, (Type[])null))
					});
					TranspilerApplied = true;
					return list;
				}
			}
			Plugin.Log.LogError((object)"Pirate Shop: couldn't find the affordability check in Terminal.LoadNewNodeIfAffordable (game update?). Shop items will NOT be free.");
			return list;
		}

		[HarmonyPostfix]
		private static void Postfix(Terminal __instance, TerminalNode node)
		{
			try
			{
				if (_pendingKey != null && !((Object)(object)node != (Object)(object)_pendingNode))
				{
					bool flag = !node.isConfirmationNode && (Object)(object)__instance.currentNode == (Object)(object)node;
					if (node.shipUnlockableID != -1 && node.buyItemIndex == -1 && node.buyVehicleIndex == -1 && !node.buyUnlockable)
					{
						flag = false;
					}
					if (flag)
					{
						Plugin.Log.LogInfo((object)("Pirate Shop: free " + _pendingKey + " taken."));
						Net.ReportUsed(_pendingKey);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop postfix failed: {arg}");
			}
			finally
			{
				_pendingKey = null;
				_pendingNode = null;
				ClampedAmount = false;
			}
		}

		public static void AdjustCost(Terminal terminal, TerminalNode node)
		{
			try
			{
				if (State.Active && !((Object)(object)node == (Object)null))
				{
					string text = KeyFor(node);
					if (State.IsFree(text) && (node.buyVehicleIndex == -1 || !terminal.hasWarrantyTicket))
					{
						int num = ((node.buyItemIndex == -1) ? 1 : Math.Max(1, terminal.playerDefinedAmount));
						ref int reference = ref TotalCost.Invoke(terminal);
						int num2 = reference / num;
						reference = Math.Max(0, reference - num2);
						_pendingKey = text;
						_pendingNode = node;
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop AdjustCost failed: {arg}");
			}
		}

		internal static string KeyFor(TerminalNode node)
		{
			if (node.buyRerouteToMoon != -1)
			{
				return null;
			}
			if (node.buyItemIndex != -1)
			{
				return "i:" + node.buyItemIndex;
			}
			if (node.buyVehicleIndex != -1)
			{
				return "v:" + node.buyVehicleIndex;
			}
			if (node.shipUnlockableID != -1)
			{
				return "u:" + node.shipUnlockableID;
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
	internal static class TerminalTextPatch
	{
		private static readonly Regex PriceLine = new Regex("^(?<pre>[ \\t]*\\*?[ \\t]*)(?<name>[^\\r\\n]*?)(?<mid>[ \\t]*//[ \\t]*Price:[ \\t]*)\\$\\d+(?:\\.\\d+)?(?<post>[^\\r\\n]*)", RegexOptions.Multiline | RegexOptions.Compiled);

		private static readonly Regex SaleNote = new Regex("[ \\t]*\\(\\d+% OFF!\\)", RegexOptions.Compiled);

		[HarmonyPrefix]
		private static void Prefix(Terminal __instance, ref string modifiedDisplayText, TerminalNode node)
		{
			try
			{
				if (State.Active && !((Object)(object)node == (Object)null) && modifiedDisplayText != null && !((Object)(object)node != (Object)(object)TerminalCostPatch.PendingNode))
				{
					modifiedDisplayText = modifiedDisplayText.Replace("[totalCost]", "FREE");
					if (TerminalCostPatch.ClampedAmount && node.isConfirmationNode)
					{
						modifiedDisplayText = modifiedDisplayText.TrimEnd() + "\n\nPirate Shop: only 1 of each item per order.\n\n";
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop confirm text failed: {arg}");
			}
		}

		internal static string Rewrite(Terminal terminal, string text)
		{
			if (!State.Active || string.IsNullOrEmpty(text) || !text.Contains("Price:"))
			{
				return text;
			}
			Dictionary<string, string> keys = KeysByName(terminal);
			return PriceLine.Replace(text, delegate(Match m)
			{
				string text2 = m.Groups["name"].Value.Trim();
				if (!keys.TryGetValue(text2.ToLowerInvariant(), out var value) || !State.IsFree(value))
				{
					return m.Value;
				}
				string text3 = SaleNote.Replace(m.Groups["post"].Value, "");
				return m.Groups["pre"].Value + m.Groups["name"].Value + m.Groups["mid"].Value + "FREE" + text3;
			});
		}

		private static Dictionary<string, string> KeysByName(Terminal t)
		{
			Dictionary<string, string> map = new Dictionary<string, string>();
			List<UnlockableItem> list = ((!((Object)(object)StartOfRound.Instance != (Object)null)) ? null : StartOfRound.Instance.unlockablesList?.unlockables);
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					Add(list[i].unlockableName, "u:" + i);
				}
			}
			if (t.ShipDecorSelection != null)
			{
				foreach (TerminalNode item in t.ShipDecorSelection)
				{
					if ((Object)(object)item != (Object)null && item.shipUnlockableID != -1)
					{
						Add(item.creatureName, "u:" + item.shipUnlockableID);
					}
				}
			}
			if (t.buyableVehicles != null)
			{
				for (int j = 0; j < t.buyableVehicles.Length; j++)
				{
					Add(t.buyableVehicles[j].vehicleDisplayName, "v:" + j);
				}
			}
			if (t.buyableItemsList != null)
			{
				for (int k = 0; k < t.buyableItemsList.Length; k++)
				{
					Add(t.buyableItemsList[k].itemName, "i:" + k);
				}
			}
			return map;
			void Add(string name, string key)
			{
				if (!string.IsNullOrWhiteSpace(name))
				{
					map[name.Trim().ToLowerInvariant()] = key;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
	internal static class TerminalScreenPatch
	{
		private static readonly FieldRef<Terminal, bool> ModifyingText = AccessTools.FieldRefAccess<Terminal, bool>("modifyingText");

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(Terminal __instance)
		{
			try
			{
				if (State.Active && !((Object)(object)__instance.screenText == (Object)null) && !Plunder.IsOpen)
				{
					string text = __instance.screenText.text;
					string text2 = TerminalTextPatch.Rewrite(__instance, text);
					if (text2 != null && text2.Contains("SHIP UPGRADES:") && !text2.Contains(Plunder.StoreHint))
					{
						text2 = text2.TrimEnd() + "\n\n" + Plunder.StoreHint + "\n\n";
					}
					if (!(text2 == text))
					{
						__instance.currentText = text2;
						__instance.textAdded = 0;
						ModifyingText.Invoke(__instance) = true;
						__instance.screenText.text = text2;
						ModifyingText.Invoke(__instance) = false;
						__instance.screenText.caretPosition = text2.Length;
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Pirate Shop store text failed: {arg}");
			}
		}
	}
}