Decompiled source of ShopPreorder v1.1.0

ShopPreorder.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using MenuLib;
using MenuLib.MonoBehaviors;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ShopPreorder")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ShopPreorder")]
[assembly: AssemblyTitle("ShopPreorder")]
[assembly: AssemblyVersion("1.0.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 ShopPreorder
{
	internal class CatalogInfo
	{
		internal static readonly string[] Categories = new string[9] { "All", "Upgrades", "Weapons", "Explosives", "Health", "Drones", "Carts & Vehicles", "Tools", "Other" };

		public bool Allowed = true;

		public string DeniedReason = "";

		public int Money;

		public string Status = "";

		public bool HasPending;

		public bool CanCancel;

		public string PendingName = "";

		public int Refund;

		public readonly List<string> Keys = new List<string>();

		public readonly List<string> Names = new List<string>();

		public readonly List<int> Prices = new List<int>();

		public readonly List<int> CategoryIds = new List<int>();

		internal static int CategoryOf(int itemType)
		{
			switch (itemType)
			{
			case 3:
				return 1;
			case 7:
			case 9:
			case 15:
				return 2;
			case 6:
			case 11:
				return 3;
			case 8:
				return 4;
			case 0:
			case 1:
				return 5;
			case 2:
			case 12:
			case 14:
				return 6;
			case 10:
			case 13:
				return 7;
			default:
				return 8;
			}
		}

		public object[] ToNetwork()
		{
			return new object[12]
			{
				Allowed,
				DeniedReason ?? "",
				Money,
				Status ?? "",
				HasPending,
				CanCancel,
				PendingName ?? "",
				Refund,
				Keys.ToArray(),
				Names.ToArray(),
				Prices.ToArray(),
				CategoryIds.ToArray()
			};
		}

		public static CatalogInfo FromNetwork(object[] d)
		{
			CatalogInfo catalogInfo = new CatalogInfo();
			if (d == null || d.Length < 12)
			{
				catalogInfo.Allowed = false;
				catalogInfo.DeniedReason = "The host sent a broken catalog.";
				return catalogInfo;
			}
			object obj = d[0];
			bool flag = default(bool);
			int num;
			if (obj is bool)
			{
				flag = (bool)obj;
				num = 1;
			}
			else
			{
				num = 0;
			}
			catalogInfo.Allowed = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			catalogInfo.DeniedReason = (d[1] as string) ?? "";
			catalogInfo.Money = ((d[2] is int num2) ? num2 : 0);
			catalogInfo.Status = (d[3] as string) ?? "";
			obj = d[4];
			bool flag2 = default(bool);
			int num3;
			if (obj is bool)
			{
				flag2 = (bool)obj;
				num3 = 1;
			}
			else
			{
				num3 = 0;
			}
			catalogInfo.HasPending = (byte)((uint)num3 & (flag2 ? 1u : 0u)) != 0;
			obj = d[5];
			bool flag3 = default(bool);
			int num4;
			if (obj is bool)
			{
				flag3 = (bool)obj;
				num4 = 1;
			}
			else
			{
				num4 = 0;
			}
			catalogInfo.CanCancel = (byte)((uint)num4 & (flag3 ? 1u : 0u)) != 0;
			catalogInfo.PendingName = (d[6] as string) ?? "";
			catalogInfo.Refund = ((d[7] is int num5) ? num5 : 0);
			if (d[8] is string[] collection)
			{
				catalogInfo.Keys.AddRange(collection);
			}
			if (d[9] is string[] collection2)
			{
				catalogInfo.Names.AddRange(collection2);
			}
			if (d[10] is int[] collection3)
			{
				catalogInfo.Prices.AddRange(collection3);
			}
			if (d[11] is int[] collection4)
			{
				catalogInfo.CategoryIds.AddRange(collection4);
			}
			return catalogInfo;
		}
	}
	internal static class CatalogMenu
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ShouldCloseMenuDelegate <>9__7_0;

			public static BuilderDelegate <>9__7_1;

			public static ScrollViewBuilderDelegate <>9__7_4;

			public static Action <>9__11_0;

			internal bool <Open>b__7_0()
			{
				return true;
			}

			internal void <Open>b__7_1(Transform parent)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				MenuAPI.CreateREPOButton("Close", (Action)Close, parent, new Vector2(66f, 18f));
			}

			internal RectTransform <Open>b__7_4(Transform scroll)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				return ((REPOElement)MenuAPI.CreateREPOSpacer(scroll, default(Vector2), new Vector2(0f, 10f))).rectTransform;
			}

			internal void <ConfirmCancel>b__11_0()
			{
				Close();
				Preorders.OnLocalCommand("cancel");
			}
		}

		private const string Gold = "#FFCC1A";

		private const string Grey = "#7F7F7F";

		private static REPOPopupPage _page;

		private static readonly List<KeyValuePair<REPOButton, int>> Rows = new List<KeyValuePair<REPOButton, int>>();

		internal static bool IsOpen => Object.op_Implicit((Object)(object)_page);

		internal static void Close()
		{
			try
			{
				if (Object.op_Implicit((Object)(object)_page))
				{
					_page.ClosePage(true);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Closing catalog: " + ex.Message));
			}
			_page = null;
			Rows.Clear();
		}

		internal static void Open(CatalogInfo info)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Expected O, but got Unknown
			Close();
			if (!info.Allowed)
			{
				Plugin.ShowMessages(new string[1] { info.DeniedReason });
				return;
			}
			REPOPopupPage val = MenuAPI.CreateREPOPopupPage("Preorder Catalog", (PresetSide)0, false, true, 0f);
			object obj = <>c.<>9__7_0;
			if (obj == null)
			{
				ShouldCloseMenuDelegate val2 = () => true;
				<>c.<>9__7_0 = val2;
				obj = (object)val2;
			}
			val.onEscapePressed = (ShouldCloseMenuDelegate)obj;
			_page = val;
			object obj2 = <>c.<>9__7_1;
			if (obj2 == null)
			{
				BuilderDelegate val3 = delegate(Transform parent)
				{
					//IL_002b: Unknown result type (might be due to invalid IL or missing references)
					MenuAPI.CreateREPOButton("Close", (Action)Close, parent, new Vector2(66f, 18f));
				};
				<>c.<>9__7_1 = val3;
				obj2 = (object)val3;
			}
			val.AddElement((BuilderDelegate)obj2);
			AddLabel(val, string.Format("Team money: <color={0}>${1}K</color>", "#FFCC1A", info.Money));
			AddLabel(val, "<size=70%>" + info.Status + "</size>");
			if (info.CanCancel)
			{
				val.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform scroll) => ((REPOElement)MenuAPI.CreateREPOButton(string.Format("Cancel {0} preorder <color={1}>(+${2}K)</color>", info.PendingName, "#FFCC1A", info.Refund), (Action)delegate
				{
					ConfirmCancel(info);
				}, scroll, default(Vector2))).rectTransform), 0f, 0f);
			}
			if (info.HasPending)
			{
				if (info.CanCancel)
				{
					AddLabel(val, "<size=70%>Cancel it to pick something else.</size>");
				}
				val.OpenPage(false);
				return;
			}
			if (info.Keys.Count == 0)
			{
				AddLabel(val, "<size=70%>Everything is already on the shelves!</size>");
				val.OpenPage(false);
				return;
			}
			Action<string> onCategory = ShowCategory;
			val.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform scroll) => ((REPOElement)MenuAPI.CreateREPOSlider("Category", "", onCategory, scroll, CatalogInfo.Categories, CatalogInfo.Categories[0], default(Vector2), "", "", (BarBehavior)0)).rectTransform), 0f, 0f);
			object obj3 = <>c.<>9__7_4;
			if (obj3 == null)
			{
				ScrollViewBuilderDelegate val4 = (Transform scroll) => ((REPOElement)MenuAPI.CreateREPOSpacer(scroll, default(Vector2), new Vector2(0f, 10f))).rectTransform;
				<>c.<>9__7_4 = val4;
				obj3 = (object)val4;
			}
			val.AddElementToScrollView((ScrollViewBuilderDelegate)obj3, 0f, 0f);
			for (int num = 0; num < info.Keys.Count; num++)
			{
				string key = info.Keys[num];
				string name = info.Names[num];
				int price = info.Prices[num];
				int category = info.CategoryIds[num];
				bool affordable = price <= info.Money;
				string label = (affordable ? string.Format("{0}  <color={1}>${2}K</color>", name, "#FFCC1A", price) : string.Format("<color={0}>{1}  ${2}K</color>", "#7F7F7F", name, price));
				val.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform scroll)
				{
					//IL_0028: 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)
					REPOButton val5 = MenuAPI.CreateREPOButton(label, (Action)delegate
					{
						OnItemClicked(key, name, price, affordable, info.Money);
					}, scroll, default(Vector2));
					Rows.Add(new KeyValuePair<REPOButton, int>(val5, category));
					return ((REPOElement)val5).rectTransform;
				}, 0f, 0f);
			}
			val.OpenPage(false);
		}

		private static void AddLabel(REPOPopupPage page, string text)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			page.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform scroll) => ((REPOElement)MenuAPI.CreateREPOLabel(text, scroll, default(Vector2))).rectTransform), 0f, 0f);
		}

		private static void ShowCategory(string category)
		{
			int num = Array.IndexOf(CatalogInfo.Categories, category);
			foreach (KeyValuePair<REPOButton, int> row in Rows)
			{
				if (Object.op_Implicit((Object)(object)row.Key))
				{
					((REPOElement)row.Key).repoScrollViewElement.visibility = num <= 0 || row.Value == num;
				}
			}
			try
			{
				if (Object.op_Implicit((Object)(object)_page) && Object.op_Implicit((Object)(object)_page.scrollView))
				{
					_page.scrollView.SetScrollPosition(0f);
				}
			}
			catch
			{
			}
		}

		private static void OnItemClicked(string key, string name, int price, bool affordable, int money)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (!affordable)
			{
				Plugin.ShowMessages(new string[1] { $"{name} costs ${price}K to preorder. The team has ${money}K." });
				return;
			}
			MenuAPI.OpenPopup("Preorder?", new Color(1f, 0.8f, 0.1f), $"Preorder <b>{name}</b> for <b>${price}K</b>?\nIt will be waiting on a shelf in the next shop.\n" + "<size=80%>The shopkeeper might even give you a discount...</size>", (Action)delegate
			{
				Close();
				Preorders.OnLocalCommand("#key " + key);
			}, (Action)null);
		}

		private static void ConfirmCancel(CatalogInfo info)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			MenuAPI.OpenPopup("Cancel preorder?", Color.red, $"Cancel the <b>{info.PendingName}</b> preorder and get <b>${info.Refund}K</b> back?", (Action)delegate
			{
				Close();
				Preorders.OnLocalCommand("cancel");
			}, (Action)null);
		}
	}
	internal static class Net
	{
		private const byte RequestEvent = 147;

		private const byte MessageEvent = 148;

		private const byte CatalogRequestEvent = 149;

		private const byte CatalogDataEvent = 150;

		private const byte ShopStateEvent = 151;

		private static bool _awaitingReply;

		private static LoadBalancingClient _hookedClient;

		private static readonly RaiseEventOptions ToHost = new RaiseEventOptions
		{
			Receivers = (ReceiverGroup)2
		};

		private static readonly RaiseEventOptions ToOthers = new RaiseEventOptions
		{
			Receivers = (ReceiverGroup)0
		};

		internal static int LocalActor
		{
			get
			{
				if (PhotonNetwork.LocalPlayer == null)
				{
					return 0;
				}
				return PhotonNetwork.LocalPlayer.ActorNumber;
			}
		}

		internal static string LocalName
		{
			get
			{
				if (PhotonNetwork.LocalPlayer == null || string.IsNullOrEmpty(PhotonNetwork.LocalPlayer.NickName))
				{
					return "Host";
				}
				return PhotonNetwork.LocalPlayer.NickName;
			}
		}

		internal static Requester LocalRequester()
		{
			return new Requester
			{
				IsHost = true,
				ActorNumber = LocalActor,
				Name = LocalName,
				Reply = Plugin.ShowMessages
			};
		}

		private static Requester RemoteRequester(int actor)
		{
			Player val = ((PhotonNetwork.CurrentRoom != null) ? PhotonNetwork.CurrentRoom.GetPlayer(actor, false) : null);
			return new Requester
			{
				IsHost = false,
				ActorNumber = actor,
				Name = ((val != null && !string.IsNullOrEmpty(val.NickName)) ? val.NickName : "Someone"),
				Reply = delegate(string[] msgs)
				{
					SendMessages(actor, msgs);
				}
			};
		}

		internal static void EnsureHooked()
		{
			try
			{
				LoadBalancingClient networkingClient = PhotonNetwork.NetworkingClient;
				if (networkingClient != null && networkingClient != _hookedClient)
				{
					if (_hookedClient != null)
					{
						_hookedClient.EventReceived -= OnEvent;
					}
					networkingClient.EventReceived += OnEvent;
					_hookedClient = networkingClient;
					Plugin.Log.LogInfo((object)"Listening for preorder messages.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not hook Photon events: " + ex));
			}
		}

		private static void Raise(byte code, object data, RaiseEventOptions options)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			EnsureHooked();
			PhotonNetwork.RaiseEvent(code, data, options, SendOptions.SendReliable);
		}

		private static void SendTo(int actor, byte code, object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			RaiseEventOptions val = new RaiseEventOptions();
			val.TargetActors = new int[1] { actor };
			Raise(code, data, val);
		}

		internal static void SendRequest(string args)
		{
			_awaitingReply = true;
			Raise(147, args, ToHost);
			((MonoBehaviour)Runner.Ensure()).StartCoroutine(ReplyTimeout());
		}

		internal static void RequestCatalog()
		{
			_awaitingReply = true;
			Raise(149, "", ToHost);
			((MonoBehaviour)Runner.Ensure()).StartCoroutine(ReplyTimeout());
		}

		private static IEnumerator ReplyTimeout()
		{
			yield return (object)new WaitForSeconds(3f);
			if (_awaitingReply)
			{
				_awaitingReply = false;
				Plugin.ShowMessages(new string[1] { "No answer - the host needs ShopPreorder installed to preorder." });
			}
		}

		internal static void SendMessages(int actor, string[] messages)
		{
			SendTo(actor, 148, messages);
		}

		internal static void SendToOthers(string[] messages, int exceptActor)
		{
			if (!SemiFunc.IsMultiplayer() || PhotonNetwork.CurrentRoom == null)
			{
				return;
			}
			Player[] playerListOthers = PhotonNetwork.PlayerListOthers;
			foreach (Player val in playerListOthers)
			{
				if (val.ActorNumber != exceptActor)
				{
					SendMessages(val.ActorNumber, messages);
				}
			}
		}

		internal static void BroadcastShopState()
		{
			if (!SemiFunc.IsMultiplayer() || PhotonNetwork.CurrentRoom == null)
			{
				return;
			}
			try
			{
				Raise(151, ShopState.ToNetwork(), ToOthers);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not send shop state: " + ex.Message));
			}
		}

		private static void OnEvent(EventData e)
		{
			try
			{
				switch (e.Code)
				{
				case 147:
					if (PhotonNetwork.IsMasterClient)
					{
						Preorders.HandleOnHost((e.CustomData as string) ?? "", RemoteRequester(e.Sender));
					}
					break;
				case 149:
					if (PhotonNetwork.IsMasterClient)
					{
						SendTo(e.Sender, 150, Preorders.BuildCatalog(RemoteRequester(e.Sender)).ToNetwork());
						SendTo(e.Sender, 151, ShopState.ToNetwork());
					}
					break;
				case 148:
					_awaitingReply = false;
					if (e.CustomData is string[] messages)
					{
						Plugin.ShowMessages(messages);
					}
					break;
				case 150:
					_awaitingReply = false;
					Plugin.OpenCatalog(CatalogInfo.FromNetwork(e.CustomData as object[]));
					break;
				case 151:
					if (!PhotonNetwork.IsMasterClient)
					{
						ShopState.FromNetwork(e.CustomData as object[]);
					}
					break;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Preorder network event failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(ChatManager), "MessageSend")]
	internal static class ChatCommandPatch
	{
		private static readonly FieldRef<ChatManager, string> ChatMessage = AccessTools.FieldRefAccess<ChatManager, string>("chatMessage");

		private static readonly FieldRef<ChatManager, bool> ChatActive = AccessTools.FieldRefAccess<ChatManager, bool>("chatActive");

		private static bool Prefix(ChatManager __instance)
		{
			string text = (ChatMessage.Invoke(__instance) ?? "").Trim();
			string args;
			if (text.StartsWith("/preorder", StringComparison.OrdinalIgnoreCase))
			{
				args = text.Substring(9);
			}
			else
			{
				if (!text.Equals("/po", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("/po ", StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
				args = text.Substring(3);
			}
			ChatMessage.Invoke(__instance) = "";
			ChatActive.Invoke(__instance) = false;
			try
			{
				TMP_Text value = Traverse.Create((object)__instance).Field("chatText").GetValue<TMP_Text>();
				if (Object.op_Implicit((Object)(object)value))
				{
					value.text = "";
				}
			}
			catch
			{
			}
			Preorders.OnLocalCommand(args);
			return false;
		}
	}
	[HarmonyPatch(typeof(PunManager), "Start")]
	internal static class PunManagerStartPatch
	{
		private static void Postfix()
		{
			Runner.Ensure();
			Net.EnsureHooked();
		}
	}
	[HarmonyPatch]
	internal static class ShopInitializePatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.GetDeclaredMethods(typeof(ShopManager)).First((MethodInfo m) => m.Name == "ShopInitialize" && m.GetParameters().Length == 1);
		}

		private static void Prefix()
		{
			if (SemiFunc.RunIsShop() && ShopState.IsHost)
			{
				Preorders.DiscountRolls.Clear();
				ShopState.Reset();
				ShopState.HostRefreshAndBroadcast();
			}
		}
	}
	[HarmonyPatch(typeof(SemiFunc), "UIItemInfoText")]
	internal static class HoverHintPatch
	{
		private static readonly FieldRef<ItemAttributes, bool> ShopItem = AccessTools.FieldRefAccess<ItemAttributes, bool>("shopItem");

		private static void Prefix(ItemAttributes itemAttributes, ref string message)
		{
			try
			{
				if (Object.op_Implicit((Object)(object)itemAttributes) && SemiFunc.RunIsShop())
				{
					if (ShopState.IsPreordered(itemAttributes))
					{
						message += "\n<size=75%><color=#5CFF7A>PREORDERED - PAID</color></size>";
					}
					else if (ShopItem.Invoke(itemAttributes) && ShopState.LocalCanPreorder)
					{
						message = string.Concat(str2: (!string.IsNullOrEmpty(ShopState.PendingItemName)) ? (ShopState.PendingItemName + " is preordered for the next shop.") : ((!Plugin.HasMenuLib) ? "Not what you wanted? Type /preorder list in chat." : ("Not what you wanted? Press [" + Plugin.CatalogKeyName + "] to preorder something else.")), str0: message, str1: "\n<size=70%><color=#FFCC1A>", str3: "</color></size>");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Hover hint failed: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(WorldSpaceUIValue), "Show", new Type[]
	{
		typeof(PhysGrabObject),
		typeof(int),
		typeof(bool),
		typeof(Vector3)
	})]
	internal static class PriceTagPatch
	{
		private static readonly FieldRef<WorldSpaceUIValue, PhysGrabObject> Current = AccessTools.FieldRefAccess<WorldSpaceUIValue, PhysGrabObject>("currentPhysGrabObject");

		private static readonly FieldRef<WorldSpaceUIValue, TextMeshProUGUI> Text = AccessTools.FieldRefAccess<WorldSpaceUIValue, TextMeshProUGUI>("text");

		private static void Postfix(WorldSpaceUIValue __instance, PhysGrabObject _grabObject, bool _cost)
		{
			try
			{
				if (_cost && Object.op_Implicit((Object)(object)_grabObject) && !((Object)(object)Current.Invoke(__instance) != (Object)(object)_grabObject) && ShopState.IsPreordered(((Component)_grabObject).GetComponent<ItemAttributes>()))
				{
					TextMeshProUGUI val = Text.Invoke(__instance);
					if (Object.op_Implicit((Object)(object)val))
					{
						((TMP_Text)val).text = "<size=55%><color=#5CFF7A>PREORDERED - PAID</color></size>";
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Price tag failed: " + ex.Message));
			}
		}
	}
	internal static class Delivery
	{
		internal static Item ExpectedItem;

		internal static Vector3 ExpectedPosition;

		internal static bool Waiting;
	}
	[HarmonyPatch]
	internal static class ShopPopulatePatch
	{
		private static readonly MethodInfo SpawnShopItem = AccessTools.Method(typeof(PunManager), "SpawnShopItem", (Type[])null, (Type[])null);

		private static MethodBase TargetMethod()
		{
			return AccessTools.GetDeclaredMethods(typeof(PunManager)).First((MethodInfo m) => m.Name == "ShopPopulateItemVolumes" && m.GetParameters().Length == 1);
		}

		private static void Prefix(PunManager __instance, object[] __args)
		{
			try
			{
				Deliver(__instance, __args[0]);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Preorder delivery failed: " + ex));
			}
		}

		private static void Deliver(PunManager pun, object spawns)
		{
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: 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)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			if (SemiFunc.IsNotMasterClient() || !SemiFunc.RunIsShop())
			{
				return;
			}
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder == null)
			{
				return;
			}
			ShopManager instance = ShopManager.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.itemVolumes == null)
			{
				return;
			}
			if (!StatsManager.instance.itemDictionary.TryGetValue(pendingPreorder.ItemKey, out var value) || !Object.op_Implicit((Object)(object)value))
			{
				Plugin.Log.LogWarning((object)$"Preordered item '{pendingPreorder.ItemKey}' no longer exists. Refunding ${pendingPreorder.PricePaid}K.");
				SemiFunc.StatSetRunCurrency(SemiFunc.StatGetRunCurrency() + pendingPreorder.PricePaid);
				PreorderStore.Clear();
				Plugin.AnnounceToAllLater(8f, $"The preorder vanished from the catalog. ${pendingPreorder.PricePaid}K refunded.");
				return;
			}
			Item item = value;
			bool flag = false;
			if (Random.Range(0, 100) < Plugin.ConfusionChancePercent.Value)
			{
				Item val = Preorders.PickConfusedItem(value);
				if (Object.op_Implicit((Object)(object)val))
				{
					item = val;
					flag = true;
				}
			}
			ItemVolume val2 = ((IEnumerable<ItemVolume>)instance.itemVolumes).FirstOrDefault((Func<ItemVolume, bool>)((ItemVolume v) => Object.op_Implicit((Object)(object)v) && v.itemVolume == item.itemVolume)) ?? ((IEnumerable<ItemVolume>)instance.itemVolumes).FirstOrDefault((Func<ItemVolume, bool>)((ItemVolume v) => Object.op_Implicit((Object)(object)v)));
			if (!Object.op_Implicit((Object)(object)val2))
			{
				Plugin.Log.LogWarning((object)"No free shelf spot for the preorder - it will try again next shop.");
				return;
			}
			val2.itemVolume = item.itemVolume;
			Delivery.ExpectedItem = item;
			Delivery.ExpectedPosition = ((Component)val2).transform.position;
			Delivery.Waiting = true;
			object[] parameters = new object[5]
			{
				val2,
				new List<Item> { item },
				0,
				false,
				spawns
			};
			if (!(bool)SpawnShopItem.Invoke(pun, parameters))
			{
				Delivery.Waiting = false;
				Plugin.Log.LogWarning((object)"Could not spawn the preordered item - it will try again next shop.");
				return;
			}
			instance.itemVolumes.Remove(val2);
			Object.Destroy((Object)(object)((Component)val2).gameObject);
			PreorderStore.Clear();
			ShopState.HostRefreshAndBroadcast();
			string text = Preorders.DisplayName(value);
			string text2 = Preorders.DisplayName(item);
			Plugin.Log.LogInfo((object)(flag ? ("Delivered " + ((Object)item).name + " instead of " + ((Object)value).name + " (shopkeeper confused).") : ("Delivered preordered " + ((Object)item).name + ".")));
			if (flag)
			{
				Plugin.AnnounceToAllLater(8f, "!THE SHOPKEEPER GOT CONFUSED", pendingPreorder.OrderedBy + " ordered " + text + "... but got " + text2 + ". It's free, at least!");
			}
			else
			{
				Plugin.AnnounceToAllLater(8f, pendingPreorder.OrderedBy + "'s preordered " + text2 + " is on the shelf - already paid for!");
			}
		}
	}
	[HarmonyPatch(typeof(ItemAttributes), "GetValue")]
	internal static class FreeItemPatch
	{
		private static readonly FieldRef<ItemAttributes, int> Value = AccessTools.FieldRefAccess<ItemAttributes, int>("value");

		private static readonly FieldRef<ItemAttributes, PhotonView> View = AccessTools.FieldRefAccess<ItemAttributes, PhotonView>("photonView");

		private static void Postfix(ItemAttributes __instance)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (Delivery.Waiting && SemiFunc.IsMasterClientOrSingleplayer() && !((Object)(object)__instance.item != (Object)(object)Delivery.ExpectedItem) && !(Vector3.Distance(((Component)__instance).transform.position, Delivery.ExpectedPosition) > 2f))
			{
				Delivery.Waiting = false;
				Value.Invoke(__instance) = 0;
				PhotonView val = View.Invoke(__instance);
				if (SemiFunc.IsMultiplayer() && Object.op_Implicit((Object)(object)val) && val.ViewID != 0)
				{
					val.RPC("GetValueRPC", (RpcTarget)1, new object[1] { 0 });
				}
				SemiFunc.ShopUpdateCost();
				Plugin.Log.LogInfo((object)("Made preordered " + ((Object)__instance.item).name + " free."));
				ShopState.LocalPreordered = __instance;
				ShopState.PreorderedViewId = ShopState.ViewIdOf(__instance);
				ShopState.HostRefreshAndBroadcast();
			}
		}
	}
	[BepInPlugin("shoppreorder.repo", "ShopPreorder", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "shoppreorder.repo";

		public const string Name = "ShopPreorder";

		public const string Version = "1.1.0";

		private const string MenuLibGuid = "nickklmao.menulib";

		internal static ManualLogSource Log;

		internal static bool HasMenuLib;

		internal static ConfigEntry<bool> AllowEveryone;

		internal static ConfigEntry<Key> CatalogKey;

		internal static ConfigEntry<int> MarkupPercent;

		internal static ConfigEntry<int> DiscountChancePercent;

		internal static ConfigEntry<int> DiscountMinPercent;

		internal static ConfigEntry<int> DiscountMaxPercent;

		internal static ConfigEntry<int> ConfusionChancePercent;

		private const float SecondsPerMessage = 3.5f;

		private static Coroutine _messageRoutine;

		private static readonly FieldRef<MenuManager, MenuPage> CurrentMenuPage = AccessTools.FieldRefAccess<MenuManager, MenuPage>("currentMenuPage");

		private static readonly Color Gold = new Color(1f, 0.8f, 0.1f);

		internal static string CatalogKeyName => ((object)CatalogKey.Value/*cast due to .constrained prefix*/).ToString();

		private void Awake()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_01ac: 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)
			Log = ((BaseUnityPlugin)this).Logger;
			AllowEveryone = ((BaseUnityPlugin)this).Config.Bind<bool>("Permissions", "AllowEveryone", false, "Host setting. Off: only the host can preorder. On: any player with the mod can preorder (the team still gets one preorder per round, paid from the team's money).");
			CatalogKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "CatalogKey", (Key)30, "Key that opens the Preorder Catalog while in the shop.");
			MarkupPercent = ((BaseUnityPlugin)this).Config.Bind<int>("Pricing", "MarkupPercent", 50, new ConfigDescription("Extra fee on top of the shop price for preordering.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			DiscountChancePercent = ((BaseUnityPlugin)this).Config.Bind<int>("Shopkeeper", "DiscountChancePercent", 33, new ConfigDescription("Chance the shopkeeper gives a discount when you preorder.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			DiscountMinPercent = ((BaseUnityPlugin)this).Config.Bind<int>("Shopkeeper", "DiscountMinPercent", 20, new ConfigDescription("Smallest possible discount.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			DiscountMaxPercent = ((BaseUnityPlugin)this).Config.Bind<int>("Shopkeeper", "DiscountMaxPercent", 50, new ConfigDescription("Largest possible discount.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfusionChancePercent = ((BaseUnityPlugin)this).Config.Bind<int>("Shopkeeper", "ConfusionChancePercent", 10, new ConfigDescription("Chance the shopkeeper gets confused and delivers the wrong item.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			AllowEveryone.SettingChanged += delegate
			{
				ShopState.HostRefreshAndBroadcast();
			};
			HasMenuLib = Chainloader.PluginInfos.ContainsKey("nickklmao.menulib");
			if (!HasMenuLib)
			{
				Log.LogWarning((object)"MenuLib not found - the catalog menu is off. /preorder in chat still works.");
			}
			Runner.Ensure();
			new Harmony("shoppreorder.repo").PatchAll(typeof(Plugin).Assembly);
			Log.LogInfo((object)string.Format("{0} {1} loaded. Press {2} in the shop, or type /preorder in chat.", "ShopPreorder", "1.1.0", CatalogKey.Value));
		}

		internal static void OpenCatalog(CatalogInfo info)
		{
			if (!HasMenuLib)
			{
				if (!info.Allowed)
				{
					ShowMessages(new string[1] { info.DeniedReason });
				}
				else
				{
					ShowMessages(new string[1] { "Install MenuLib for the catalog. For now: type /preorder list in chat." });
				}
				return;
			}
			try
			{
				OpenCatalogMenuLib(info);
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Could not open the catalog: " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void OpenCatalogMenuLib(CatalogInfo info)
		{
			CatalogMenu.Open(info);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool CatalogMenuIsOpen()
		{
			return CatalogMenu.IsOpen;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void CatalogMenuClose()
		{
			CatalogMenu.Close();
		}

		private static bool InShop()
		{
			try
			{
				return Object.op_Implicit((Object)(object)RunManager.instance) && SemiFunc.RunIsShop();
			}
			catch
			{
				return false;
			}
		}

		internal static void CatalogKeyTick()
		{
			//IL_0025: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (HasMenuLib && CatalogMenuIsOpen() && !InShop())
			{
				CatalogMenuClose();
			}
			Keyboard current = Keyboard.current;
			Key value = CatalogKey.Value;
			if (current == null || (int)value == 0)
			{
				return;
			}
			bool wasPressedThisFrame;
			try
			{
				wasPressedThisFrame = ((ButtonControl)current[value]).wasPressedThisFrame;
			}
			catch
			{
				return;
			}
			if (!wasPressedThisFrame)
			{
				return;
			}
			if (HasMenuLib && CatalogMenuIsOpen())
			{
				CatalogMenuClose();
			}
			else if (InShop() && (!Object.op_Implicit((Object)(object)ChatManager.instance) || !ChatManager.instance.StateIsActive()) && SemiFunc.NoTextInputsActive() && (!Object.op_Implicit((Object)(object)MenuManager.instance) || !Object.op_Implicit((Object)(object)CurrentMenuPage.Invoke(MenuManager.instance))))
			{
				if (ShopState.IsHost)
				{
					OpenCatalog(Preorders.BuildCatalog(Net.LocalRequester()));
				}
				else
				{
					Net.RequestCatalog();
				}
			}
		}

		private static void Say(string message, float seconds)
		{
			//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)
			Log.LogInfo((object)("[msg] " + message));
			try
			{
				SemiFunc.UIFocusText(message, Color.white, Gold, seconds);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not show message: " + ex.Message));
			}
		}

		private static void Shout(string message)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			Log.LogInfo((object)("[big] " + message));
			try
			{
				SemiFunc.UIBigMessage(message, "{!}", 25f, Gold, Color.white);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not show big message: " + ex.Message));
			}
		}

		internal static void ShowMessages(string[] messages)
		{
			if (messages != null && messages.Length != 0)
			{
				Runner runner = Runner.Ensure();
				if (_messageRoutine != null)
				{
					((MonoBehaviour)runner).StopCoroutine(_messageRoutine);
				}
				_messageRoutine = ((MonoBehaviour)runner).StartCoroutine(MessageRoutine(messages));
			}
		}

		private static IEnumerator MessageRoutine(string[] messages)
		{
			foreach (string text in messages)
			{
				if (text.StartsWith("!"))
				{
					Shout(text.Substring(1));
				}
				else
				{
					Say(text, 3.5f);
				}
				yield return (object)new WaitForSeconds(3.5f);
			}
		}

		internal static void AnnounceToOthers(Requester who, string[] messages)
		{
			if (!who.IsHost)
			{
				ShowMessages(messages);
			}
			Net.SendToOthers(messages, (!who.IsHost) ? who.ActorNumber : 0);
		}

		internal static void AnnounceToAllLater(float delay, params string[] messages)
		{
			((MonoBehaviour)Runner.Ensure()).StartCoroutine(AnnounceLaterRoutine(delay, messages));
		}

		private static IEnumerator AnnounceLaterRoutine(float delay, string[] messages)
		{
			yield return (object)new WaitForSeconds(delay);
			ShowMessages(messages);
			Net.SendToOthers(messages, 0);
		}
	}
	internal class Runner : MonoBehaviour
	{
		private static Runner _instance;

		internal static Runner Ensure()
		{
			//IL_0017: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (Object.op_Implicit((Object)(object)_instance))
			{
				return _instance;
			}
			GameObject val = new GameObject("ShopPreorder.Runner")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			_instance = val.AddComponent<Runner>();
			return _instance;
		}

		private void Update()
		{
			try
			{
				Plugin.CatalogKeyTick();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Catalog key check failed: " + ex));
			}
		}
	}
	internal class Requester
	{
		public bool IsHost;

		public int ActorNumber;

		public string Name;

		public Action<string[]> Reply;
	}
	internal static class Preorders
	{
		private const int TypeUpgrade = 3;

		private const int TypeCrystal = 5;

		private const int TypeHealthPack = 8;

		private static readonly FieldRef<ShopManager, float> ItemValueMultiplier = AccessTools.FieldRefAccess<ShopManager, float>("itemValueMultiplier");

		private static readonly FieldRef<ItemAttributes, bool> ShopItemField = AccessTools.FieldRefAccess<ItemAttributes, bool>("shopItem");

		internal static readonly Dictionary<string, int> DiscountRolls = new Dictionary<string, int>();

		internal static List<KeyValuePair<string, Item>> AllSellableItems()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Invalid comparison between Unknown and I4
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<string, Item>> list = new List<KeyValuePair<string, Item>>();
			StatsManager instance = StatsManager.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.itemDictionary == null)
			{
				return list;
			}
			int num = ((!Object.op_Implicit((Object)(object)GameDirector.instance) || GameDirector.instance.PlayerList == null) ? 1 : GameDirector.instance.PlayerList.Count);
			foreach (KeyValuePair<string, Item> item in instance.itemDictionary)
			{
				Item value = item.Value;
				if (Object.op_Implicit((Object)(object)value) && !value.disabled && (int)value.status == 1 && (int)value.itemSecretShopType == 0 && (value.minPlayerCount <= 1 || num >= value.minPlayerCount) && SemiFunc.StatGetItemsPurchased(((Object)value).name) < value.maxAmountInShop && (!value.maxPurchase || instance.GetItemsUpgradesPurchasedTotal(((Object)value).name) < value.maxPurchaseAmount))
				{
					list.Add(item);
				}
			}
			return list;
		}

		internal static HashSet<Item> ItemsOnShelves()
		{
			HashSet<Item> hashSet = new HashSet<Item>();
			ItemAttributes[] array = Object.FindObjectsByType<ItemAttributes>((FindObjectsSortMode)0);
			foreach (ItemAttributes val in array)
			{
				if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.item) && ShopItemField.Invoke(val))
				{
					hashSet.Add(val.item);
				}
			}
			return hashSet;
		}

		internal static List<KeyValuePair<string, Item>> PreorderableItems()
		{
			HashSet<Item> onShelves = ItemsOnShelves();
			return (from kv in AllSellableItems()
				where !onShelves.Contains(kv.Value)
				orderby ShopPrice(kv.Value), DisplayName(kv.Value)
				select kv).ToList();
		}

		internal static string DisplayName(Item item)
		{
			if (!string.IsNullOrEmpty(item.itemName))
			{
				return item.itemName;
			}
			return ((Object)item).name;
		}

		internal static int ShopPrice(Item item)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected I4, but got Unknown
			ShopManager instance = ShopManager.instance;
			float num = (Object.op_Implicit((Object)(object)instance) ? ItemValueMultiplier.Invoke(instance) : 1f);
			float num2 = (item.value.valueMin + item.value.valueMax) * 0.5f * num;
			if (num2 < 1000f)
			{
				num2 = 1000f;
			}
			num2 = Mathf.Ceil(num2 / 1000f);
			if (Object.op_Implicit((Object)(object)instance))
			{
				switch ((int)item.itemType)
				{
				case 3:
					num2 = instance.UpgradeValueGet(num2, item);
					break;
				case 8:
					num2 = instance.HealthPackValueGet(num2);
					break;
				case 5:
					num2 = instance.CrystalValueGet(num2);
					break;
				}
			}
			return Mathf.Max(1, Mathf.CeilToInt(num2));
		}

		internal static int PreorderPrice(Item item)
		{
			float num = 1f + (float)Plugin.MarkupPercent.Value / 100f;
			return Mathf.Max(1, Mathf.CeilToInt((float)ShopPrice(item) * num));
		}

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

		internal static List<KeyValuePair<string, Item>> Match(string query, List<KeyValuePair<string, Item>> pool)
		{
			string q = Normalize(query);
			if (q.Length == 0)
			{
				return new List<KeyValuePair<string, Item>>();
			}
			List<KeyValuePair<string, Item>> list = pool.Where((KeyValuePair<string, Item> kv) => Normalize(DisplayName(kv.Value)) == q).ToList();
			if (list.Count > 0)
			{
				return list;
			}
			string[] words = (from w in query.ToLowerInvariant().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(Normalize)
				where w.Length > 0
				select w).ToArray();
			return pool.Where(delegate(KeyValuePair<string, Item> kv)
			{
				string name = Normalize(DisplayName(kv.Value));
				string key = Normalize(kv.Key);
				return words.All((string w) => name.Contains(w) || key.Contains(w));
			}).ToList();
		}

		internal static void OnLocalCommand(string args)
		{
			args = (args ?? "").Trim();
			if (ShopState.IsHost)
			{
				HandleOnHost(args, Net.LocalRequester());
			}
			else
			{
				Net.SendRequest(args);
			}
		}

		internal static void HandleOnHost(string args, Requester who)
		{
			try
			{
				HandleOnHostInner(args.Trim(), who);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Preorder command failed: " + ex));
				who.Reply(new string[1] { "Preorder failed - see the host's BepInEx log." });
			}
		}

		private static void HandleOnHostInner(string args, Requester who)
		{
			if (!who.IsHost && !Plugin.AllowEveryone.Value)
			{
				who.Reply(new string[1] { "The host has preorders set to host-only." });
				return;
			}
			if (!SemiFunc.RunIsShop())
			{
				who.Reply(new string[1] { "You can only preorder while in the shop." });
				return;
			}
			switch (args.ToLowerInvariant())
			{
			case "":
			case "help":
				who.Reply(new string[4] { "/preorder <item> - pay now, it's in the next shop", "/preorder list - what you can preorder", "/preorder status - this round's preorder", "/preorder cancel - refund this round's preorder" });
				break;
			case "list":
				ShowList(who);
				break;
			case "status":
				ShowStatus(who);
				break;
			case "cancel":
				Cancel(who);
				break;
			default:
				if (args.StartsWith("#key "))
				{
					PlaceOrderByKey(args.Substring(5), who);
				}
				else
				{
					PlaceOrder(args, who);
				}
				break;
			}
		}

		internal static string ItemNameForKey(string key)
		{
			if (!StatsManager.instance.itemDictionary.TryGetValue(key, out var value) || !Object.op_Implicit((Object)(object)value))
			{
				return key;
			}
			return DisplayName(value);
		}

		private static void ShowList(Requester who)
		{
			List<KeyValuePair<string, Item>> list = PreorderableItems();
			if (list.Count == 0)
			{
				who.Reply(new string[1] { "Everything is already on the shelves!" });
				return;
			}
			List<string> list2 = new List<string>();
			for (int i = 0; i < list.Count; i += 3)
			{
				list2.Add(string.Join("   ", from kv in list.Skip(i).Take(3)
					select $"{DisplayName(kv.Value)} ${PreorderPrice(kv.Value)}K"));
			}
			Plugin.Log.LogInfo((object)("Preorderable items:\n  " + string.Join("\n  ", list2)));
			who.Reply(list2.ToArray());
		}

		private static void ShowStatus(Requester who)
		{
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder == null)
			{
				who.Reply(new string[1] { "No preorder yet. The team gets one per round!" });
			}
			else
			{
				who.Reply(new string[1] { $"{pendingPreorder.OrderedBy} preordered {ItemNameForKey(pendingPreorder.ItemKey)} (paid ${pendingPreorder.PricePaid}K)." });
			}
		}

		private static void Cancel(Requester who)
		{
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder == null)
			{
				who.Reply(new string[1] { "Nothing to cancel." });
				return;
			}
			if (!who.IsHost && pendingPreorder.OrderedBy != who.Name)
			{
				who.Reply(new string[1] { "Only " + pendingPreorder.OrderedBy + " or the host can cancel that preorder." });
				return;
			}
			SemiFunc.StatSetRunCurrency(SemiFunc.StatGetRunCurrency() + pendingPreorder.PricePaid);
			PreorderStore.Clear();
			string text = $"{who.Name} cancelled the {ItemNameForKey(pendingPreorder.ItemKey)} preorder. ${pendingPreorder.PricePaid}K refunded.";
			who.Reply(new string[1] { text });
			Plugin.AnnounceToOthers(who, new string[1] { text });
			ShopState.HostRefreshAndBroadcast();
		}

		private static void PlaceOrderByKey(string key, Requester who)
		{
			KeyValuePair<string, Item> keyValuePair = PreorderableItems().FirstOrDefault((KeyValuePair<string, Item> kv) => kv.Key == key);
			if ((Object)(object)keyValuePair.Value == (Object)null)
			{
				who.Reply(new string[1] { ItemNameForKey(key) + " can't be preordered right now." });
			}
			else
			{
				Purchase(keyValuePair.Key, keyValuePair.Value, who);
			}
		}

		private static void PlaceOrder(string query, Requester who)
		{
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder != null)
			{
				who.Reply(new string[1] { pendingPreorder.OrderedBy + " already preordered " + ItemNameForKey(pendingPreorder.ItemKey) + " this round." });
				return;
			}
			List<KeyValuePair<string, Item>> pool = PreorderableItems();
			List<KeyValuePair<string, Item>> list = Match(query, pool);
			if (list.Count == 0)
			{
				bool flag = Match(query, AllSellableItems()).Count > 0;
				who.Reply(new string[1] { flag ? ("\"" + query + "\" is already on the shelves - just buy it!") : ("The shopkeeper doesn't know \"" + query + "\". Try /preorder list") });
			}
			else if (list.Count > 1)
			{
				string text = string.Join(", ", from kv in list.Take(4)
					select DisplayName(kv.Value));
				who.Reply(new string[1] { "Which one? " + text + ((list.Count > 4) ? "..." : "") });
			}
			else
			{
				Purchase(list[0].Key, list[0].Value, who);
			}
		}

		private static void Purchase(string key, Item item, Requester who)
		{
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder != null)
			{
				who.Reply(new string[1] { pendingPreorder.OrderedBy + " already preordered " + ItemNameForKey(pendingPreorder.ItemKey) + " this round." });
				return;
			}
			int num = PreorderPrice(item);
			if (!DiscountRolls.TryGetValue(key, out var value))
			{
				value = 0;
				if (Random.Range(0, 100) < Plugin.DiscountChancePercent.Value)
				{
					int num2 = Mathf.Min(Plugin.DiscountMinPercent.Value, Plugin.DiscountMaxPercent.Value);
					int num3 = Mathf.Max(Plugin.DiscountMinPercent.Value, Plugin.DiscountMaxPercent.Value);
					value = Random.Range(num2, num3 + 1);
				}
				DiscountRolls[key] = value;
			}
			if (value > 0)
			{
				num = Mathf.Max(1, Mathf.CeilToInt((float)num * (1f - (float)value / 100f)));
			}
			int num4 = SemiFunc.StatGetRunCurrency();
			if (num4 < num)
			{
				who.Reply(new string[1] { $"{DisplayName(item)} costs ${num}K to preorder. The team has ${num4}K." });
				return;
			}
			SemiFunc.StatSetRunCurrency(num4 - num);
			PreorderStore.Save(new PendingPreorder
			{
				ItemKey = key,
				PricePaid = num,
				OrderedBy = who.Name
			});
			Plugin.Log.LogInfo((object)$"{who.Name} preordered {key} for ${num}K (discount {value}%).");
			string text = $"{who.Name} preordered {DisplayName(item)} for ${num}K. See you next shop!";
			string[] array = ((value <= 0) ? new string[1] { text } : new string[2]
			{
				$"!SHOPKEEPER DISCOUNT -{value}%",
				text
			});
			who.Reply(array);
			Plugin.AnnounceToOthers(who, array);
			ShopState.HostRefreshAndBroadcast();
		}

		internal static CatalogInfo BuildCatalog(Requester who)
		{
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected I4, but got Unknown
			CatalogInfo catalogInfo = new CatalogInfo();
			if (!who.IsHost && !Plugin.AllowEveryone.Value)
			{
				catalogInfo.Allowed = false;
				catalogInfo.DeniedReason = "The host has preorders set to host-only.";
				return catalogInfo;
			}
			if (!SemiFunc.RunIsShop())
			{
				catalogInfo.Allowed = false;
				catalogInfo.DeniedReason = "You can only preorder while in the shop.";
				return catalogInfo;
			}
			catalogInfo.Money = SemiFunc.StatGetRunCurrency();
			PendingPreorder pendingPreorder = PreorderStore.Load();
			if (pendingPreorder != null)
			{
				catalogInfo.HasPending = true;
				catalogInfo.PendingName = ItemNameForKey(pendingPreorder.ItemKey);
				catalogInfo.Refund = pendingPreorder.PricePaid;
				catalogInfo.CanCancel = who.IsHost || pendingPreorder.OrderedBy == who.Name;
				catalogInfo.Status = $"{pendingPreorder.OrderedBy} preordered {catalogInfo.PendingName} for the next shop (${pendingPreorder.PricePaid}K).";
				return catalogInfo;
			}
			catalogInfo.Status = "Pick one item for the next shop. The team gets one preorder per round.";
			foreach (KeyValuePair<string, Item> item in PreorderableItems())
			{
				catalogInfo.Keys.Add(item.Key);
				catalogInfo.Names.Add(DisplayName(item.Value));
				catalogInfo.Prices.Add(PreorderPrice(item.Value));
				catalogInfo.CategoryIds.Add(CatalogInfo.CategoryOf((int)item.Value.itemType));
			}
			return catalogInfo;
		}

		internal static Item PickConfusedItem(Item ordered)
		{
			List<Item> list = (from kv in AllSellableItems()
				select kv.Value into i
				where (Object)(object)i != (Object)(object)ordered
				select i).ToList();
			if (list.Count == 0)
			{
				return null;
			}
			List<Item> list2 = list.Where((Item i) => i.itemType == ordered.itemType).ToList();
			List<Item> list3 = ((list2.Count > 0 && Random.value < 0.7f) ? list2 : list);
			return list3[Random.Range(0, list3.Count)];
		}
	}
	internal class PendingPreorder
	{
		public string ItemKey;

		public int PricePaid;

		public string OrderedBy;
	}
	internal static class PreorderStore
	{
		private static readonly FieldRef<StatsManager, string> SaveFileCurrent = AccessTools.FieldRefAccess<StatsManager, string>("saveFileCurrent");

		private static string Folder => Path.Combine(Paths.ConfigPath, "ShopPreorder");

		private static string FilePath
		{
			get
			{
				string text = null;
				try
				{
					if (Object.op_Implicit((Object)(object)StatsManager.instance))
					{
						text = SaveFileCurrent.Invoke(StatsManager.instance);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Could not read save name: " + ex.Message));
				}
				if (string.IsNullOrEmpty(text))
				{
					text = "unsaved-run";
				}
				char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
				foreach (char oldChar in invalidFileNameChars)
				{
					text = text.Replace(oldChar, '_');
				}
				return Path.Combine(Folder, text + ".txt");
			}
		}

		public static PendingPreorder Load()
		{
			try
			{
				string filePath = FilePath;
				if (!File.Exists(filePath))
				{
					return null;
				}
				string[] array = File.ReadAllText(filePath).Trim().Split('|');
				if (array.Length < 2 || string.IsNullOrEmpty(array[0]))
				{
					return null;
				}
				int.TryParse(array[1], out var result);
				return new PendingPreorder
				{
					ItemKey = array[0],
					PricePaid = result,
					OrderedBy = ((array.Length > 2 && array[2].Length > 0) ? array[2] : "The host")
				};
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not load preorder: " + ex));
				return null;
			}
		}

		public static void Save(PendingPreorder order)
		{
			try
			{
				Directory.CreateDirectory(Folder);
				string text = (order.OrderedBy ?? "").Replace("|", "/");
				File.WriteAllText(FilePath, order.ItemKey + "|" + order.PricePaid + "|" + text);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not save preorder: " + ex));
			}
		}

		public static void Clear()
		{
			try
			{
				string filePath = FilePath;
				if (File.Exists(filePath))
				{
					File.Delete(filePath);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not clear preorder: " + ex));
			}
		}
	}
	internal static class ShopState
	{
		private static readonly FieldRef<ItemAttributes, PhotonView> View = AccessTools.FieldRefAccess<ItemAttributes, PhotonView>("photonView");

		internal static bool AllowEveryone;

		internal static int PreorderedViewId;

		internal static ItemAttributes LocalPreordered;

		internal static string PendingItemName = "";

		internal static bool IsHost
		{
			get
			{
				if (SemiFunc.IsMultiplayer())
				{
					return SemiFunc.IsMasterClient();
				}
				return true;
			}
		}

		internal static bool LocalCanPreorder
		{
			get
			{
				if (!IsHost)
				{
					return AllowEveryone;
				}
				return true;
			}
		}

		internal static void Reset()
		{
			PreorderedViewId = 0;
			LocalPreordered = null;
			PendingItemName = "";
		}

		internal static bool IsPreordered(ItemAttributes attr)
		{
			if (!Object.op_Implicit((Object)(object)attr))
			{
				return false;
			}
			if (Object.op_Implicit((Object)(object)LocalPreordered) && (Object)(object)attr == (Object)(object)LocalPreordered)
			{
				return true;
			}
			if (PreorderedViewId == 0)
			{
				return false;
			}
			PhotonView val = View.Invoke(attr);
			if (Object.op_Implicit((Object)(object)val))
			{
				return val.ViewID == PreorderedViewId;
			}
			return false;
		}

		internal static int ViewIdOf(ItemAttributes attr)
		{
			PhotonView val = (Object.op_Implicit((Object)(object)attr) ? View.Invoke(attr) : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return 0;
			}
			return val.ViewID;
		}

		internal static void HostRefreshAndBroadcast()
		{
			if (IsHost)
			{
				AllowEveryone = Plugin.AllowEveryone.Value;
				PendingPreorder pendingPreorder = PreorderStore.Load();
				PendingItemName = ((pendingPreorder != null) ? Preorders.ItemNameForKey(pendingPreorder.ItemKey) : "");
				Net.BroadcastShopState();
			}
		}

		internal static object[] ToNetwork()
		{
			return new object[3]
			{
				AllowEveryone,
				PreorderedViewId,
				PendingItemName ?? ""
			};
		}

		internal static void FromNetwork(object[] data)
		{
			if (data != null && data.Length >= 3)
			{
				object obj = data[0];
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				AllowEveryone = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				PreorderedViewId = ((data[1] is int num2) ? num2 : 0);
				PendingItemName = (data[2] as string) ?? "";
			}
		}
	}
}