Decompiled source of SupplyRun v1.0.0

Mods/SupplyRun.dll

Decompiled 39 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Text.Json.Serialization;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.Delivery;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dialogue;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Items;
using Il2CppScheduleOne.UI.Phone.Delivery;
using Il2CppScheduleOne.UI.Shop;
using Il2CppScheduleOne.Variables;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using SupplyRun;
using SupplyRunLogic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Mod), "Supply Run", "1.0.0", "purplehaxttv", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SupplyRun")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c0714fcb3c24b50db2ddd41c0bd6ff24df28cddf")]
[assembly: AssemblyProduct("SupplyRun")]
[assembly: AssemblyTitle("SupplyRun")]
[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 SupplyRunLogic
{
	internal static class Game
	{
		private static LoadManager load;

		private static DeliveryManager deliveries;

		private static MoneyManager money;

		private static SaveManager save;

		internal static LoadManager Load
		{
			get
			{
				if ((Object)(object)load == (Object)null)
				{
					load = Object.FindObjectOfType<LoadManager>();
				}
				return load;
			}
		}

		internal static DeliveryManager Deliveries
		{
			get
			{
				if ((Object)(object)deliveries == (Object)null)
				{
					deliveries = Object.FindObjectOfType<DeliveryManager>();
				}
				return deliveries;
			}
		}

		internal static MoneyManager Money
		{
			get
			{
				if ((Object)(object)money == (Object)null)
				{
					money = Object.FindObjectOfType<MoneyManager>();
				}
				return money;
			}
		}

		internal static SaveManager Save
		{
			get
			{
				if ((Object)(object)save == (Object)null)
				{
					save = Object.FindObjectOfType<SaveManager>();
				}
				return save;
			}
		}

		internal static DeliveryApp App
		{
			get
			{
				try
				{
					if (PlayerSingleton<DeliveryApp>.InstanceExists)
					{
						return PlayerSingleton<DeliveryApp>.Instance;
					}
				}
				catch
				{
				}
				return null;
			}
		}

		internal static bool IsHost
		{
			get
			{
				try
				{
					return InstanceFinder.IsServer;
				}
				catch
				{
					return false;
				}
			}
		}

		internal static bool InGame
		{
			get
			{
				try
				{
					LoadManager val = Load;
					return (Object)(object)val != (Object)null && val.IsGameLoaded && Core.Scene != "Menu";
				}
				catch
				{
					return false;
				}
			}
		}
	}
	internal static class Core
	{
		internal static Instance Log;

		internal static string Scene = "";

		private static Harmony harmony;

		private static float nextTick;

		internal static void Init(Instance log, string scene)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			Log = log;
			Scene = scene ?? "";
			Config.Init();
			harmony = new Harmony("purplehax.supplyrun." + Guid.NewGuid().ToString("N"));
			Patches.Apply(harmony);
			Log.Msg("Supply Run courier ready.");
		}

		internal static void Shutdown()
		{
			try
			{
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
			}
			catch (Exception ex)
			{
				Instance log = Log;
				if (log != null)
				{
					log.Warning("unpatch: " + ex.Message);
				}
			}
			State.DetachSaveHook();
			try
			{
				FixerUnlock.Teardown();
			}
			catch (Exception ex2)
			{
				Instance log2 = Log;
				if (log2 != null)
				{
					log2.Warning("fixer teardown: " + ex2.Message);
				}
			}
			try
			{
				Courier.Teardown();
			}
			catch (Exception ex3)
			{
				Instance log3 = Log;
				if (log3 != null)
				{
					log3.Warning("courier teardown: " + ex3.Message);
				}
			}
		}

		internal static void OnScene(string scene)
		{
			Scene = scene ?? "";
			if (Scene == "Menu")
			{
				Courier.Forget();
				FixerUnlock.Forget();
				State.Reset();
			}
		}

		internal static void Tick()
		{
			if (!(Time.unscaledTime < nextTick))
			{
				nextTick = Time.unscaledTime + 0.5f;
				State.AttachSaveHook();
				if (Game.InGame)
				{
					State.Sync();
					FixerUnlock.Tick();
					Courier.Tick();
				}
			}
		}
	}
	internal static class Config
	{
		private static MelonPreferences_Category cat;

		private static MelonPreferences_Entry<int> unlockPrice;

		private static MelonPreferences_Entry<int> deliveryFee;

		private static MelonPreferences_Entry<string> rackName;

		private static MelonPreferences_Entry<bool> requireRack;

		private static MelonPreferences_Entry<bool> requireUnlock;

		private static MelonPreferences_Entry<string> serviceName;

		private static MelonPreferences_Entry<string> shopNames;

		private static MelonPreferences_Entry<string> accentColor;

		private static string parsedNamesSource;

		private static Dictionary<string, string> parsedNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		internal static int UnlockPrice
		{
			get
			{
				if (unlockPrice == null)
				{
					return 5000;
				}
				return Math.Max(0, unlockPrice.Value);
			}
		}

		internal static int DeliveryFee
		{
			get
			{
				if (deliveryFee == null)
				{
					return 200;
				}
				return Math.Max(0, deliveryFee.Value);
			}
		}

		internal static string RackName
		{
			get
			{
				if (rackName == null || string.IsNullOrWhiteSpace(rackName.Value))
				{
					return "Courier";
				}
				return rackName.Value.Trim();
			}
		}

		internal static bool RequireRack
		{
			get
			{
				if (requireRack != null)
				{
					return requireRack.Value;
				}
				return true;
			}
		}

		internal static bool RequireUnlock
		{
			get
			{
				if (requireUnlock != null)
				{
					return requireUnlock.Value;
				}
				return true;
			}
		}

		internal static string ServiceName
		{
			get
			{
				if (serviceName == null || string.IsNullOrWhiteSpace(serviceName.Value))
				{
					return "Courier";
				}
				return serviceName.Value.Trim();
			}
		}

		internal static Color Accent
		{
			get
			{
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				Color result = default(Color);
				if (accentColor != null && ColorUtility.TryParseHtmlString(accentColor.Value, ref result))
				{
					return result;
				}
				return new Color(0.5f, 0.32f, 0.78f, 1f);
			}
		}

		internal static void Init()
		{
			cat = MelonPreferences.GetCategory("SupplyRun") ?? MelonPreferences.CreateCategory("SupplyRun");
			unlockPrice = Entry("UnlockPrice", 5000, "One-time cash price the Fixer charges to set up the courier service.");
			deliveryFee = Entry("DeliveryFee", 200, "Flat fee per courier run, paid from the bank balance. The cargo itself is free, you already own it.");
			rackName = Entry("CourierRackName", "Courier", "Storage whose name contains this text is a courier pick-up point. Rename a rack with the management clipboard.");
			requireRack = Entry("RequireCourierRack", def: true, "If true, only storage named after CourierRackName can be shipped from. If false, every storage unit in the property is offered.");
			requireUnlock = Entry("RequireFixerUnlock", def: true, "If true, the courier must first be bought from the Fixer. If false, it is always available.");
			serviceName = Entry("ServiceName", "Courier", "What the service is called in the Deliveries app.");
			shopNames = Entry("ShopNames", "", "Custom pick-up point names, as propertycode=Name pairs separated by semicolons. Example: bungalow=Stash House;barn=The Farm");
			accentColor = Entry("AccentColor", "#8052C7", "Colour used for courier entries in the Deliveries app (HTML colour).");
		}

		private static MelonPreferences_Entry<T> Entry<T>(string id, T def, string desc)
		{
			return cat.GetEntry<T>(id) ?? cat.CreateEntry<T>(id, def, (string)null, desc, false, false, (ValueValidator)null, (string)null);
		}

		internal static string CustomShopName(string propertyCode, string propertyName)
		{
			string text = ((shopNames != null) ? (shopNames.Value ?? "") : "");
			if (text != parsedNamesSource)
			{
				parsedNamesSource = text;
				parsedNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
				string[] array = text.Split(new char[2] { ';', '\n' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text2 in array)
				{
					int num = text2.IndexOf('=');
					if (num > 0)
					{
						string text3 = text2.Substring(0, num).Trim();
						string text4 = text2.Substring(num + 1).Trim();
						if (text3.Length > 0 && text4.Length > 0)
						{
							parsedNames[text3] = text4;
						}
					}
				}
			}
			if (propertyCode != null && parsedNames.TryGetValue(propertyCode, out var value))
			{
				return value;
			}
			if (propertyName != null && parsedNames.TryGetValue(propertyName, out value))
			{
				return value;
			}
			return null;
		}
	}
	internal class ManifestLine
	{
		public string ItemJson { get; set; }

		public string ItemId { get; set; }

		public string Name { get; set; }

		public int Quantity { get; set; }
	}
	internal class CourierRun
	{
		public string SourceCode { get; set; }

		public string SourceName { get; set; }

		public string VanShop { get; set; }

		[JsonIgnore]
		public bool Loaded { get; set; }

		public List<ManifestLine> Lines { get; set; } = new List<ManifestLine>();
	}
	internal class SaveData
	{
		public string Identity { get; set; }

		public bool Unlocked { get; set; }

		public Dictionary<string, CourierRun> Runs { get; set; } = new Dictionary<string, CourierRun>();
	}
	internal static class State
	{
		private const string InSaveFile = "SupplyRun.json";

		internal static SaveData Data = new SaveData();

		private static string loadedPath;

		private static string currentKey;

		private static SaveManager hookedManager;

		private static UnityAction saveListener;

		private static string Dir => Path.Combine(MelonEnvironment.UserDataDirectory, "SupplyRun");

		internal static string CurrentKey => currentKey;

		internal static bool Unlocked
		{
			get
			{
				if (Config.RequireUnlock)
				{
					return Data.Unlocked;
				}
				return true;
			}
		}

		private static string FileFor(string key)
		{
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
			foreach (char oldChar in invalidFileNameChars)
			{
				key = key.Replace(oldChar, '_');
			}
			return Path.Combine(Dir, key + ".json");
		}

		private static string KeyOf(string saveFolder)
		{
			string[] array = saveFolder.Replace('\\', '/').TrimEnd('/').Split('/');
			if (array.Length >= 2)
			{
				return array[^2] + "_" + array[^1];
			}
			return array[^1];
		}

		private unsafe static string CurrentIdentity(out string legacy)
		{
			//IL_0029: 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)
			legacy = null;
			try
			{
				SaveInfo val = (((Object)(object)Game.Load != (Object)null) ? Game.Load.ActiveSaveInfo : null);
				if (val == null)
				{
					return null;
				}
				DateTime dateCreated = val.DateCreated;
				try
				{
					legacy = val.OrganisationName + "|" + ((object)(*(DateTime*)(&dateCreated))/*cast due to .constrained prefix*/).ToString();
				}
				catch
				{
				}
				return $"{val.OrganisationName}|{((DateTime)(ref dateCreated)).Year:D4}{((DateTime)(ref dateCreated)).Month:D2}{((DateTime)(ref dateCreated)).Day:D2}{((DateTime)(ref dateCreated)).Hour:D2}{((DateTime)(ref dateCreated)).Minute:D2}{((DateTime)(ref dateCreated)).Second:D2}";
			}
			catch
			{
				return null;
			}
		}

		internal static void Reset()
		{
			loadedPath = null;
			currentKey = null;
			Data = new SaveData();
		}

		internal static void Sync()
		{
			LoadManager load = Game.Load;
			if (!((Object)(object)load == (Object)null))
			{
				string loadedGameFolderPath;
				try
				{
					loadedGameFolderPath = load.LoadedGameFolderPath;
				}
				catch
				{
					return;
				}
				if (!string.IsNullOrEmpty(loadedGameFolderPath) && !(loadedGameFolderPath == loadedPath))
				{
					loadedPath = loadedGameFolderPath;
					LoadFor(loadedGameFolderPath);
				}
			}
		}

		private static SaveData Read(string file)
		{
			try
			{
				if (!File.Exists(file))
				{
					return null;
				}
				SaveData saveData = JsonSerializer.Deserialize<SaveData>(File.ReadAllText(file));
				if (saveData == null)
				{
					return null;
				}
				if (saveData.Runs == null)
				{
					saveData.Runs = new Dictionary<string, CourierRun>();
				}
				foreach (CourierRun value in saveData.Runs.Values)
				{
					if (value.Lines == null)
					{
						value.Lines = new List<ManifestLine>();
					}
				}
				return saveData;
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not read " + file + ": " + ex.Message);
				return null;
			}
		}

		private static void LoadFor(string saveFolder)
		{
			currentKey = KeyOf(saveFolder);
			Data = new SaveData();
			string value = "none";
			SaveData saveData = Read(Path.Combine(saveFolder, "SupplyRun.json"));
			if (saveData != null)
			{
				Data = saveData;
				value = "save folder";
			}
			else
			{
				SaveData saveData2 = Read(FileFor(currentKey));
				if (saveData2 != null)
				{
					string legacy;
					string text = CurrentIdentity(out legacy);
					if (saveData2.Identity != null && text != null && saveData2.Identity != text && saveData2.Identity != legacy)
					{
						Core.Log.Msg("Courier: a different game now uses save slot '" + currentKey + "', starting with a clean courier state.");
					}
					else
					{
						Data = saveData2;
						value = "UserData";
					}
				}
			}
			Core.Log.Msg($"Courier: state for '{currentKey}' (from {value}): unlocked={Data.Unlocked}, runs in progress={Data.Runs.Count}.");
		}

		internal static void Commit()
		{
			if (string.IsNullOrEmpty(currentKey) || string.IsNullOrEmpty(loadedPath))
			{
				return;
			}
			string contents;
			try
			{
				string legacy;
				string text = CurrentIdentity(out legacy);
				if (text != null)
				{
					Data.Identity = text;
				}
				contents = JsonSerializer.Serialize(Data, new JsonSerializerOptions
				{
					WriteIndented = true
				});
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not serialise state: " + ex.Message);
				return;
			}
			try
			{
				Directory.CreateDirectory(Dir);
				File.WriteAllText(FileFor(currentKey), contents);
			}
			catch (Exception ex2)
			{
				Core.Log.Warning("Courier: could not write state to UserData: " + ex2.Message);
			}
			try
			{
				if (Directory.Exists(loadedPath))
				{
					File.WriteAllText(Path.Combine(loadedPath, "SupplyRun.json"), contents);
				}
			}
			catch (Exception ex3)
			{
				Core.Log.Warning("Courier: could not write state to the save folder: " + ex3.Message);
			}
		}

		internal static void AttachSaveHook()
		{
			SaveManager save = Game.Save;
			if (!((Object)(object)save == (Object)null) && (!((Object)(object)hookedManager != (Object)null) || !(((Il2CppObjectBase)hookedManager).Pointer == ((Il2CppObjectBase)save).Pointer)))
			{
				if ((Delegate)(object)saveListener == (Delegate)null)
				{
					saveListener = UnityAction.op_Implicit((Action)OnGameSaved);
				}
				save.onSaveComplete.AddListener(saveListener);
				hookedManager = save;
			}
		}

		internal static void DetachSaveHook()
		{
			try
			{
				if ((Object)(object)hookedManager != (Object)null && (Delegate)(object)saveListener != (Delegate)null)
				{
					hookedManager.onSaveComplete.RemoveListener(saveListener);
				}
			}
			catch
			{
			}
			hookedManager = null;
		}

		private static void OnGameSaved()
		{
			try
			{
				if (Game.IsHost)
				{
					Sync();
					Commit();
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: save hook failed: " + ex.Message);
			}
		}
	}
	internal static class Courier
	{
		internal class Row
		{
			public string Key;

			public string ItemId;

			public string Name;

			public string Label;

			public string Detail;

			public Sprite Icon;

			public int Available;

			public StorableItemDefinition Definition;

			public ListingEntry Entry;
		}

		internal class Shop
		{
			public string Code;

			public Property Source;

			public string Title;

			public DeliveryShop Panel;

			public IntPtr PanelPtr;

			public GameObject Card;

			public Text CardTitle;

			public Text CardDescription;

			public Text PanelTitle;

			public Text PanelDescription;

			public string CardDescriptionText;

			public List<Row> Rows = new List<Row>();

			public List<StorageEntity> Storages = new List<StorageEntity>();

			public List<StorableItemDefinition> TempDefinitions = new List<StorableItemDefinition>();

			public float NextVanCheck;

			public float StaleSince = -1f;
		}

		private static DeliveryApp app;

		private static readonly Dictionary<string, Shop> shops = new Dictionary<string, Shop>();

		private static readonly Dictionary<IntPtr, Shop> byPanel = new Dictionary<IntPtr, Shop>();

		private static GameObject hintCard;

		internal static Shop Submitting;

		private static CourierRun pendingRun;

		private static string capturedId;

		private static ShopInterface cachedVan;

		private static float cachedVanUntil;

		private static float nextPrune;

		private static float nextSync;

		internal static bool Usable
		{
			get
			{
				if (Game.IsHost && State.Unlocked)
				{
					return Patches.Healthy;
				}
				return false;
			}
		}

		internal static IEnumerable<Shop> Shops => shops.Values;

		internal static Shop ByPanel(DeliveryShop panel)
		{
			if ((Object)(object)panel == (Object)null || byPanel.Count == 0)
			{
				return null;
			}
			byPanel.TryGetValue(((Il2CppObjectBase)panel).Pointer, out var value);
			return value;
		}

		internal static Shop ByCode(string code)
		{
			if (code == null)
			{
				return null;
			}
			shops.TryGetValue(code.ToLowerInvariant(), out var value);
			return value;
		}

		internal static string ShopTitle(Property p)
		{
			return Config.CustomShopName(p.PropertyCode, p.PropertyName) ?? p.PropertyName;
		}

		internal static string RunLabel(CourierRun run)
		{
			string text = run.SourceName;
			Property val = FindProperty(run.SourceCode);
			if ((Object)(object)val != (Object)null)
			{
				text = ShopTitle(val);
			}
			return Config.ServiceName + ": " + text;
		}

		private static Property FindProperty(string code)
		{
			if (string.IsNullOrEmpty(code))
			{
				return null;
			}
			List<Property> ownedProperties = Property.OwnedProperties;
			if (ownedProperties == null)
			{
				return null;
			}
			for (int i = 0; i < ownedProperties.Count; i++)
			{
				Property val = ownedProperties[i];
				if ((Object)(object)val != (Object)null && string.Equals(val.PropertyCode, code, StringComparison.OrdinalIgnoreCase))
				{
					return val;
				}
			}
			return null;
		}

		private static string RackName(PlaceableStorageEntity rack)
		{
			try
			{
				string managementName = ((BuildableItem)rack).GetManagementName();
				if (!string.IsNullOrEmpty(managementName))
				{
					return managementName;
				}
			}
			catch
			{
			}
			try
			{
				return rack.Name ?? "";
			}
			catch
			{
				return "";
			}
		}

		internal static bool IsCourierRack(PlaceableStorageEntity rack)
		{
			if (!Config.RequireRack)
			{
				return true;
			}
			return RackName(rack).IndexOf(Config.RackName, StringComparison.OrdinalIgnoreCase) >= 0;
		}

		internal static List<StorageEntity> SourceStorages(Property p)
		{
			List<StorageEntity> list = new List<StorageEntity>();
			if ((Object)(object)p == (Object)null)
			{
				return list;
			}
			List<BuildableItem> buildableItems = p.BuildableItems;
			if (buildableItems == null)
			{
				return list;
			}
			for (int i = 0; i < buildableItems.Count; i++)
			{
				BuildableItem val = buildableItems[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				PlaceableStorageEntity val2 = ((Il2CppObjectBase)val).TryCast<PlaceableStorageEntity>();
				if (!((Object)(object)val2 == (Object)null) && IsCourierRack(val2))
				{
					StorageEntity storageEntity = val2.StorageEntity;
					if ((Object)(object)storageEntity != (Object)null)
					{
						list.Add(storageEntity);
					}
				}
			}
			return list;
		}

		private static bool AnyInUse(List<StorageEntity> storages)
		{
			for (int i = 0; i < storages.Count; i++)
			{
				StorageEntity val = storages[i];
				try
				{
					if ((Object)(object)val != (Object)null && ((Object)(object)val.CurrentPlayerAccessor != (Object)null || val.IsOpened))
					{
						return true;
					}
				}
				catch
				{
				}
			}
			return false;
		}

		private static string KeyOf(ItemInstance inst)
		{
			return ((SaveData)inst.GetCopy(1).GetItemData()).GetJson(false);
		}

		private static bool Shippable(ItemSlot slot, out ItemInstance inst, out int quantity)
		{
			inst = null;
			quantity = 0;
			if (slot == null)
			{
				return false;
			}
			inst = slot.ItemInstance;
			if (inst == null)
			{
				return false;
			}
			quantity = slot.Quantity;
			if (quantity <= 0)
			{
				return false;
			}
			if (((Il2CppObjectBase)inst).TryCast<CashInstance>() != null)
			{
				return false;
			}
			return true;
		}

		private static string ItemLabel(ItemInstance inst)
		{
			try
			{
				return ((BaseItemInstance)inst).Name;
			}
			catch
			{
				return ((BaseItemInstance)inst).ID;
			}
		}

		private static string ItemDetail(ItemInstance inst)
		{
			//IL_0011: 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)
			QualityItemInstance val = ((Il2CppObjectBase)inst).TryCast<QualityItemInstance>();
			if (val == null)
			{
				return "";
			}
			return ((object)val.Quality/*cast due to .constrained prefix*/).ToString();
		}

		private static string ReadyText(Row row)
		{
			return ((row.Detail.Length > 0) ? (row.Detail + ", ") : "") + row.Available + " ready";
		}

		internal static List<Row> ScanRows(List<StorageEntity> storages)
		{
			List<Row> list = new List<Row>();
			Dictionary<string, Row> dictionary = new Dictionary<string, Row>();
			foreach (StorageEntity storage in storages)
			{
				List<ItemSlot> itemSlots = storage.ItemSlots;
				if (itemSlots == null)
				{
					continue;
				}
				for (int i = 0; i < itemSlots.Count; i++)
				{
					if (!Shippable(itemSlots[i], out var inst, out var quantity))
					{
						continue;
					}
					StorableItemDefinition val = (((Object)(object)inst.Definition != (Object)null) ? ((Il2CppObjectBase)inst.Definition).TryCast<StorableItemDefinition>() : null);
					if (!((Object)(object)val == (Object)null))
					{
						string key = KeyOf(inst);
						if (!dictionary.TryGetValue(key, out var value))
						{
							value = new Row
							{
								Key = key,
								ItemId = ((BaseItemInstance)inst).ID,
								Definition = val,
								Label = ItemLabel(inst),
								Detail = ItemDetail(inst),
								Icon = ((BaseItemInstance)inst).Icon
							};
							value.Name = ((value.Detail.Length > 0) ? (value.Label + " [" + value.Detail + "]") : value.Label);
							dictionary[key] = value;
							list.Add(value);
						}
						value.Available += quantity;
					}
				}
			}
			return list;
		}

		private static int RemoveFromSource(List<StorageEntity> storages, Row row, int quantity)
		{
			int num = quantity;
			foreach (StorageEntity storage in storages)
			{
				if (num <= 0)
				{
					break;
				}
				List<ItemSlot> itemSlots = storage.ItemSlots;
				if (itemSlots == null)
				{
					continue;
				}
				for (int i = 0; i < itemSlots.Count; i++)
				{
					if (num <= 0)
					{
						break;
					}
					ItemSlot val = itemSlots[i];
					if (Shippable(val, out var inst, out var quantity2) && !(((BaseItemInstance)inst).ID != row.ItemId) && !(KeyOf(inst) != row.Key))
					{
						int num2 = Math.Min(num, quantity2);
						val.ChangeQuantity(-num2, false);
						int num3;
						try
						{
							num3 = ((val.ItemInstance != null) ? val.Quantity : 0);
						}
						catch
						{
							num3 = 0;
						}
						int num4 = Math.Max(0, Math.Min(num2, quantity2 - num3));
						num -= num4;
					}
				}
			}
			return quantity - num;
		}

		private static bool IsBusy(string storeName)
		{
			DeliveryManager deliveries = Game.Deliveries;
			if ((Object)(object)deliveries == (Object)null)
			{
				return true;
			}
			List<DeliveryInstance> deliveries2 = deliveries.Deliveries;
			for (int i = 0; i < deliveries2.Count; i++)
			{
				DeliveryInstance val = deliveries2[i];
				if (val != null && val.StoreName == storeName)
				{
					return true;
				}
			}
			return false;
		}

		internal static ShopInterface PickVan()
		{
			if ((Object)(object)app == (Object)null)
			{
				return null;
			}
			ShopInterface val = null;
			List<DeliveryShopElement> shopElements = app._shopElements;
			if (shopElements == null)
			{
				return null;
			}
			for (int num = shopElements.Count - 1; num >= 0; num--)
			{
				DeliveryShopElement val2 = shopElements[num];
				if (val2 != null && !((Object)(object)val2.Shop == (Object)null))
				{
					ShopInterface matchingShop = val2.Shop.MatchingShop;
					if (!((Object)(object)matchingShop == (Object)null) && !((Object)(object)matchingShop.DeliveryVehicle == (Object)null) && !IsBusy(matchingShop.ShopName))
					{
						if ((Object)(object)val2.Button != (Object)null && !((Component)val2.Button).gameObject.activeSelf)
						{
							return matchingShop;
						}
						if ((Object)(object)val == (Object)null)
						{
							val = matchingShop;
						}
					}
				}
			}
			return val;
		}

		private static ShopInterface PickVanCached()
		{
			if (Time.unscaledTime > cachedVanUntil)
			{
				cachedVan = PickVan();
				cachedVanUntil = Time.unscaledTime + 0.5f;
			}
			return cachedVan;
		}

		private static ShopInterface AnyShopInterface()
		{
			List<DeliveryShopElement> shopElements = app._shopElements;
			for (int i = 0; i < shopElements.Count; i++)
			{
				DeliveryShopElement val = shopElements[i];
				if (val != null && (Object)(object)val.Shop != (Object)null && (Object)(object)val.Shop.MatchingShop != (Object)null)
				{
					return val.Shop.MatchingShop;
				}
			}
			return null;
		}

		private static void AssignVan(Shop s, ShopInterface van)
		{
			if ((Object)(object)van == (Object)null)
			{
				van = AnyShopInterface();
			}
			if (!((Object)(object)van == (Object)null))
			{
				s.Panel.MatchingShop = van;
				s.Panel.MatchingShopInterfaceName = van.ShopName;
			}
		}

		internal static void EnsureVan(Shop s)
		{
			if ((Object)(object)app == (Object)null || (Object)(object)s.Panel == (Object)null || Time.unscaledTime < s.NextVanCheck)
			{
				return;
			}
			s.NextVanCheck = Time.unscaledTime + 0.5f;
			if (IsBusy(s.Panel.MatchingShopInterfaceName))
			{
				ShopInterface val = PickVan();
				if ((Object)(object)val != (Object)null)
				{
					AssignVan(s, val);
				}
			}
		}

		private static DeliveryVehicle VanFor(string storeName)
		{
			List<ShopInterface> allShops = ShopInterface.AllShops;
			if (allShops == null)
			{
				return null;
			}
			for (int i = 0; i < allShops.Count; i++)
			{
				ShopInterface val = allShops[i];
				if ((Object)(object)val != (Object)null && val.ShopName == storeName && (Object)(object)val.DeliveryVehicle != (Object)null)
				{
					return val.DeliveryVehicle;
				}
			}
			return null;
		}

		private static Text FindText(Transform root, string path)
		{
			Transform val = root.Find(path);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((Component)val).GetComponent<Text>();
		}

		private static void SetIcon(Transform root, string path)
		{
			try
			{
				Transform val = root.Find(path);
				Image val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Image>() : null);
				if ((Object)(object)val2 != (Object)null && (Object)(object)((App<DeliveryApp>)(object)app).AppIcon != (Object)null)
				{
					val2.sprite = ((App<DeliveryApp>)(object)app).AppIcon;
				}
			}
			catch
			{
			}
		}

		private static DeliveryShopElement TemplateElement()
		{
			List<DeliveryShopElement> shopElements = app._shopElements;
			if (shopElements == null || shopElements.Count == 0)
			{
				return null;
			}
			DeliveryShopElement val = null;
			for (int i = 0; i < shopElements.Count; i++)
			{
				DeliveryShopElement val2 = shopElements[i];
				if (val2 != null && !((Object)(object)val2.Shop == (Object)null) && !((Object)(object)val2.Button == (Object)null) && !((Object)(object)val2.Shop.MatchingShop == (Object)null))
				{
					if (val == null)
					{
						val = val2;
					}
					if (val2.Shop.AvailableByDefault)
					{
						return val2;
					}
				}
			}
			return val;
		}

		private static GameObject CloneCard(DeliveryShopElement tpl, string name, string title, string description, out Text titleText, out Text descText)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: 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)
			GameObject val = Object.Instantiate<GameObject>(((Component)tpl.Button).gameObject, ((Component)tpl.Button).transform.parent);
			((Object)val).name = name;
			val.SetActive(true);
			titleText = FindText(val.transform, "Title");
			descText = FindText(val.transform, "Description");
			if ((Object)(object)titleText != (Object)null)
			{
				titleText.text = title;
			}
			if ((Object)(object)descText != (Object)null)
			{
				descText.text = description;
			}
			SetIcon(val.transform, "Icon/Image");
			try
			{
				Image component = val.GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					((Graphic)component).color = Config.Accent;
				}
				Transform val2 = val.transform.Find("Icon");
				Image val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<Image>() : null);
				if ((Object)(object)val3 != (Object)null)
				{
					((Graphic)val3).color = Color.Lerp(Config.Accent, Color.black, 0.35f);
				}
			}
			catch
			{
			}
			((UnityEventBase)val.GetComponent<Button>().onClick).RemoveAllListeners();
			try
			{
				UISelectable component2 = val.GetComponent<UISelectable>();
				if ((Object)(object)component2 != (Object)null && (Object)(object)app._listingPanel != (Object)null)
				{
					app._listingPanel.AddSelectable(component2);
				}
			}
			catch
			{
			}
			return val;
		}

		private static void DestroyCard(GameObject card)
		{
			if ((Object)(object)card == (Object)null)
			{
				return;
			}
			try
			{
				UISelectable component = card.GetComponent<UISelectable>();
				if ((Object)(object)component != (Object)null && (Object)(object)app != (Object)null && (Object)(object)app._listingPanel != (Object)null)
				{
					app._listingPanel.RemoveSelectable(component, true);
				}
			}
			catch
			{
			}
			Object.Destroy((Object)(object)card);
		}

		private static Shop CreateShop(Property p)
		{
			//IL_00c0: 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_01b9: 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_01c8: Unknown result type (might be due to invalid IL or missing references)
			DeliveryShopElement val = TemplateElement();
			if (val == null)
			{
				return null;
			}
			string text = p.PropertyCode.ToLowerInvariant();
			Shop s = new Shop
			{
				Code = text,
				Source = p,
				Title = ShopTitle(p)
			};
			GameObject val2 = Object.Instantiate<GameObject>(((Component)val.Shop).gameObject, ((Component)val.Shop).transform.parent);
			((Object)val2).name = "SupplyRun " + text;
			val2.SetActive(false);
			DeliveryShop panel = val2.GetComponent<DeliveryShop>();
			s.Panel = panel;
			s.PanelPtr = ((Il2CppObjectBase)panel).Pointer;
			panel.AvailableByDefault = false;
			panel.ShopColor = Config.Accent;
			panel.MatchingShop = val.Shop.MatchingShop;
			panel.MatchingShopInterfaceName = val.Shop.MatchingShopInterfaceName;
			ClearRows(s);
			s.PanelTitle = FindText(val2.transform, "Container/Header/Container/Labels/Container/Title");
			s.PanelDescription = FindText(val2.transform, "Container/Header/Container/Labels/Container/Description");
			SetIcon(val2.transform, "Container/Header/Container/Icon/Image");
			try
			{
				Transform val3 = val2.transform.Find("Container/Header");
				Image val4 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<Image>() : null);
				if ((Object)(object)val4 != (Object)null)
				{
					((Graphic)val4).color = Config.Accent;
				}
				Transform val5 = val2.transform.Find("Container/Header/Container/Icon");
				Image val6 = (((Object)(object)val5 != (Object)null) ? ((Component)val5).GetComponent<Image>() : null);
				if ((Object)(object)val6 != (Object)null)
				{
					((Graphic)val6).color = Color.Lerp(Config.Accent, Color.black, 0.35f);
				}
			}
			catch
			{
			}
			DeliveryApp theApp = app;
			((UnityEventBase)panel.BackButton.onClick).RemoveAllListeners();
			((UnityEvent)panel.BackButton.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
			{
				theApp.CloseShop(panel);
			}));
			((UnityEventBase)panel.DestinationDropdown.onValueChanged).RemoveAllListeners();
			((UnityEvent<int>)(object)panel.DestinationDropdown.onValueChanged).AddListener(UnityAction<int>.op_Implicit((Action<int>)delegate(int i)
			{
				panel.DestinationDropdownSelected(i);
			}));
			((UnityEventBase)panel.LoadingDockDropdown.onValueChanged).RemoveAllListeners();
			((UnityEvent<int>)(object)panel.LoadingDockDropdown.onValueChanged).AddListener(UnityAction<int>.op_Implicit((Action<int>)delegate(int i)
			{
				panel.LoadingDockDropdownSelected(i);
			}));
			((UnityEventBase)panel.OrderButton.onClick).RemoveAllListeners();
			((UnityEvent)panel.OrderButton.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
			{
				PlaceOrder(s);
			}));
			s.Card = CloneCard(val, "SupplyRun " + text + " Button", s.Title, "", out s.CardTitle, out s.CardDescription);
			((UnityEvent)s.Card.GetComponent<Button>().onClick).AddListener(UnityAction.op_Implicit((Action)delegate
			{
				OpenShop(s);
			}));
			app.deliveryShops.Add(panel);
			try
			{
				List<UIPanel> panels = panel.Panels;
				if (panels != null && (Object)(object)app._deliveryScreen != (Object)null)
				{
					for (int num = 0; num < panels.Count; num++)
					{
						if ((Object)(object)panels[num] != (Object)null)
						{
							app._deliveryScreen.AddPanel(panels[num]);
						}
					}
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: controller navigation not registered: " + ex.Message);
			}
			shops[text] = s;
			byPanel[s.PanelPtr] = s;
			RefreshTexts(s, 0);
			Core.Log.Msg("Courier: pick-up point '" + s.Title + "' added to the Deliveries app.");
			return s;
		}

		private static bool SafeToRemove(Shop s)
		{
			try
			{
				if ((Object)(object)s.Panel == (Object)null)
				{
					return true;
				}
				if (s.Panel.IsOpen)
				{
					s.StaleSince = -1f;
					return false;
				}
				if (!((Component)s.Panel).gameObject.activeSelf)
				{
					return true;
				}
				if (s.StaleSince < 0f)
				{
					s.StaleSince = Time.time;
				}
				return Time.time - s.StaleSince > 1.5f;
			}
			catch
			{
				return true;
			}
		}

		private static void DestroyTempDefinitions(Shop s)
		{
			foreach (StorableItemDefinition tempDefinition in s.TempDefinitions)
			{
				try
				{
					if ((Object)(object)tempDefinition != (Object)null)
					{
						Object.Destroy((Object)(object)tempDefinition);
					}
				}
				catch
				{
				}
			}
			s.TempDefinitions.Clear();
		}

		private static void DestroyShop(Shop s)
		{
			shops.Remove(s.Code);
			byPanel.Remove(s.PanelPtr);
			try
			{
				if ((Object)(object)app != (Object)null && (Object)(object)s.Panel != (Object)null)
				{
					if (s.Panel.IsOpen)
					{
						app.CloseShop(s.Panel);
					}
					app.deliveryShops.Remove(s.Panel);
					List<UIPanel> panels = s.Panel.Panels;
					if (panels != null && (Object)(object)app._deliveryScreen != (Object)null)
					{
						for (int i = 0; i < panels.Count; i++)
						{
							if ((Object)(object)panels[i] != (Object)null)
							{
								app._deliveryScreen.RemovePanel(panels[i]);
							}
						}
					}
				}
			}
			catch
			{
			}
			DestroyTempDefinitions(s);
			DestroyCard(s.Card);
			if ((Object)(object)s.Panel != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)s.Panel).gameObject);
			}
		}

		private static void RefreshTexts(Shop s, int items)
		{
			s.Title = ShopTitle(s.Source);
			string text = ((items > 0) ? $"{Config.ServiceName} pick-up, {items} item{((items == 1) ? "" : "s")} ready" : (Config.ServiceName + " pick-up, nothing on the rack"));
			if ((Object)(object)s.CardTitle != (Object)null && s.CardTitle.text != s.Title)
			{
				s.CardTitle.text = s.Title;
			}
			if ((Object)(object)s.CardDescription != (Object)null && s.CardDescriptionText != text)
			{
				s.CardDescription.text = text;
				s.CardDescriptionText = text;
			}
			if ((Object)(object)s.PanelTitle != (Object)null && s.PanelTitle.text != s.Title)
			{
				s.PanelTitle.text = s.Title;
			}
			string text2 = Config.ServiceName + " pick-up at " + s.Source.PropertyName;
			if ((Object)(object)s.PanelDescription != (Object)null && s.PanelDescription.text != text2)
			{
				s.PanelDescription.text = text2;
			}
		}

		private static int CountItems(List<StorageEntity> storages)
		{
			int num = 0;
			foreach (StorageEntity storage in storages)
			{
				try
				{
					num += storage.ItemCount;
				}
				catch
				{
				}
			}
			return num;
		}

		internal static void SyncShops()
		{
			if ((Object)(object)app == (Object)null)
			{
				return;
			}
			Dictionary<string, KeyValuePair<Property, int>> dictionary = new Dictionary<string, KeyValuePair<Property, int>>();
			if (Usable)
			{
				List<Property> ownedProperties = Property.OwnedProperties;
				if (ownedProperties != null)
				{
					for (int i = 0; i < ownedProperties.Count; i++)
					{
						Property val = ownedProperties[i];
						if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(val.PropertyCode))
						{
							List<StorageEntity> list = SourceStorages(val);
							if (list.Count != 0)
							{
								dictionary[val.PropertyCode.ToLowerInvariant()] = new KeyValuePair<Property, int>(val, CountItems(list));
							}
						}
					}
				}
			}
			List<Shop> list2 = new List<Shop>();
			foreach (Shop value2 in shops.Values)
			{
				if (dictionary.ContainsKey(value2.Code))
				{
					value2.StaleSince = -1f;
				}
				else if (SafeToRemove(value2))
				{
					list2.Add(value2);
				}
			}
			foreach (Shop item in list2)
			{
				DestroyShop(item);
			}
			foreach (KeyValuePair<string, KeyValuePair<Property, int>> item2 in dictionary)
			{
				if (!shops.TryGetValue(item2.Key, out var value))
				{
					value = CreateShop(item2.Value.Key);
				}
				if (value != null)
				{
					RefreshTexts(value, item2.Value.Value);
				}
			}
			bool flag = Usable && dictionary.Count == 0;
			if (flag && (Object)(object)hintCard == (Object)null)
			{
				DeliveryShopElement val2 = TemplateElement();
				if (val2 != null)
				{
					hintCard = CloneCard(val2, "SupplyRun Hint Button", Config.ServiceName, "Name a storage rack \"" + Config.RackName + "\" to ship from it", out var _, out var _);
				}
			}
			else if (!flag && (Object)(object)hintCard != (Object)null)
			{
				DestroyCard(hintCard);
				hintCard = null;
			}
		}

		private static void ClearRows(Shop s)
		{
			DeliveryShop panel = s.Panel;
			RectTransform listingContainer = panel.ListingContainer;
			if ((Object)(object)listingContainer != (Object)null)
			{
				for (int num = ((Transform)listingContainer).childCount - 1; num >= 0; num--)
				{
					Transform child = ((Transform)listingContainer).GetChild(num);
					if (!((Object)(object)((Component)child).GetComponent<ListingEntry>() == (Object)null))
					{
						try
						{
							UISelectable component = ((Component)child).GetComponent<UISelectable>();
							if ((Object)(object)component != (Object)null && (Object)(object)panel._entriesPanel != (Object)null)
							{
								panel._entriesPanel.RemoveSelectable(component, false);
							}
						}
						catch
						{
						}
						((Component)child).gameObject.SetActive(false);
						Object.Destroy((Object)(object)((Component)child).gameObject);
					}
				}
			}
			if (panel.listingEntries != null)
			{
				panel.listingEntries.Clear();
			}
			s.Rows.Clear();
			DestroyTempDefinitions(s);
		}

		internal static void BuildCatalog(Shop s)
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			ClearRows(s);
			DeliveryShop panel = s.Panel;
			s.Storages = SourceStorages(s.Source);
			foreach (Row item in ScanRows(s.Storages))
			{
				StorableItemDefinition val = item.Definition;
				try
				{
					if (!val.IsUnlocked)
					{
						StorableItemDefinition val2 = Object.Instantiate<StorableItemDefinition>(item.Definition);
						val2.RequiresLevelToPurchase = false;
						s.TempDefinitions.Add(val2);
						val = val2;
					}
				}
				catch (Exception ex)
				{
					Core.Log.Warning("Courier: could not prepare '" + item.Name + "': " + ex.Message);
				}
				ShopListing val3 = new ShopListing();
				val3.name = item.Name;
				val3.Item = val;
				val3.OverridePrice = true;
				val3.OverriddenPrice = 0f;
				val3.LimitedStock = true;
				val3.DefaultStock = item.Available;
				val3.CurrentStock = item.Available;
				val3.CanBeDelivered = true;
				val3.StockVariableName = "";
				val3.PurchasedQuantityVariableName = "";
				val3.ConditionalVisibilityVariableName = "";
				GameObject val4 = Object.Instantiate<GameObject>(((Component)panel.ListingEntryPrefab).gameObject, (Transform)(object)panel.ListingContainer);
				val4.SetActive(true);
				ListingEntry component = val4.GetComponent<ListingEntry>();
				component.Initialize(val3);
				if ((Object)(object)component.ItemNameLabel != (Object)null)
				{
					component.ItemNameLabel.text = item.Label;
				}
				if ((Object)(object)component.ItemPriceLabel != (Object)null)
				{
					component.ItemPriceLabel.text = ReadyText(item);
				}
				if ((Object)(object)component.Icon != (Object)null && (Object)(object)item.Icon != (Object)null)
				{
					component.Icon.sprite = item.Icon;
				}
				item.Entry = component;
				Row captured = item;
				component.onQuantityChanged.AddListener(UnityAction.op_Implicit((Action)delegate
				{
					OnQuantityChanged(s, captured);
				}));
				try
				{
					UISelectable component2 = val4.GetComponent<UISelectable>();
					if ((Object)(object)component2 != (Object)null && (Object)(object)panel._entriesPanel != (Object)null)
					{
						panel._entriesPanel.AddSelectable(component2);
					}
				}
				catch
				{
				}
				panel.listingEntries.Add(component);
				s.Rows.Add(item);
			}
			try
			{
				LayoutRebuilder.ForceRebuildLayoutImmediate(panel.ListingContainer);
			}
			catch
			{
			}
			cachedVanUntil = 0f;
			s.NextVanCheck = 0f;
			AssignVan(s, PickVan());
			RefreshTexts(s, CountItems(s.Storages));
		}

		private static void OnQuantityChanged(Shop s, Row row)
		{
			try
			{
				if (!((Object)(object)row.Entry == (Object)null) && !((Object)(object)s.Panel == (Object)null))
				{
					if (row.Entry.SelectedQuantity > row.Available)
					{
						row.Entry.SetQuantity(row.Available, true);
						return;
					}
					s.Panel.RefreshCart();
					s.Panel.RefreshOrderButton();
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: quantity change failed: " + ex.Message);
			}
		}

		internal static void OpenShop(Shop s)
		{
			try
			{
				if (!((Object)(object)app == (Object)null) && Usable)
				{
					BuildCatalog(s);
					app.OpenShop(s.Panel);
					if ((Object)(object)s.Panel.DeliveryFeeLabel != (Object)null)
					{
						s.Panel.DeliveryFeeLabel.text = MoneyManager.FormatAmount((float)Config.DeliveryFee, false, false);
					}
					s.Panel.RefreshCart();
					s.Panel.RefreshOrderButton();
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not open pick-up point: " + ex);
			}
		}

		internal static bool CartHasItems(Shop s)
		{
			for (int i = 0; i < s.Rows.Count; i++)
			{
				ListingEntry entry = s.Rows[i].Entry;
				if ((Object)(object)entry != (Object)null && entry.SelectedQuantity > 0)
				{
					return true;
				}
			}
			return false;
		}

		internal static string BlockReason(Shop s)
		{
			if (!Game.IsHost)
			{
				return "Only the host can book the courier";
			}
			if (!State.Unlocked)
			{
				return "Courier service is not set up";
			}
			if (s.Rows.Count == 0)
			{
				if (!Config.RequireRack)
				{
					return "Nothing in storage here";
				}
				return "The \"" + Config.RackName + "\" rack here is empty";
			}
			if (AnyInUse(s.Storages))
			{
				return "Someone is using the rack";
			}
			if ((Object)(object)PickVanCached() == (Object)null)
			{
				return "All delivery vans are out";
			}
			return null;
		}

		private static void PlaceOrder(Shop s)
		{
			try
			{
				if (!Usable || (Object)(object)s.Panel == (Object)null)
				{
					return;
				}
				DeliveryShop panel = s.Panel;
				List<StorageEntity> storages = (s.Storages = SourceStorages(s.Source));
				if (AnyInUse(storages))
				{
					Core.Log.Msg("Courier: the rack is being used by a player, order not placed.");
					panel.RefreshOrderButton();
					return;
				}
				List<Row> list = ScanRows(storages);
				bool flag = false;
				foreach (Row row2 in s.Rows)
				{
					int num = 0;
					foreach (Row item in list)
					{
						if (item.Key == row2.Key)
						{
							num = item.Available;
							break;
						}
					}
					if (num != row2.Available)
					{
						row2.Available = num;
						if ((Object)(object)row2.Entry != (Object)null && (Object)(object)row2.Entry.ItemPriceLabel != (Object)null)
						{
							row2.Entry.ItemPriceLabel.text = ReadyText(row2);
						}
					}
					if ((Object)(object)row2.Entry != (Object)null && row2.Entry.SelectedQuantity > num)
					{
						row2.Entry.SetQuantity(num, true);
						flag = true;
					}
				}
				if (flag)
				{
					Core.Log.Msg("Courier: the rack holds less than was selected, quantities were adjusted. Order not placed yet.");
					panel.RefreshCart();
					panel.RefreshOrderButton();
					return;
				}
				cachedVanUntil = 0f;
				ShopInterface val = PickVan();
				if ((Object)(object)val == (Object)null)
				{
					panel.RefreshOrderButton();
					return;
				}
				AssignVan(s, val);
				CourierRun courierRun = new CourierRun
				{
					SourceCode = s.Code,
					SourceName = s.Title,
					VanShop = val.ShopName
				};
				List<KeyValuePair<Row, ManifestLine>> list2 = new List<KeyValuePair<Row, ManifestLine>>();
				List<ListingEntry> listingEntries = panel.listingEntries;
				for (int i = 0; i < listingEntries.Count; i++)
				{
					ListingEntry val2 = listingEntries[i];
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					int selectedQuantity = val2.SelectedQuantity;
					if (selectedQuantity <= 0)
					{
						continue;
					}
					Row row = null;
					foreach (Row row3 in s.Rows)
					{
						if ((Object)(object)row3.Entry != (Object)null && ((Il2CppObjectBase)row3.Entry).Pointer == ((Il2CppObjectBase)val2).Pointer)
						{
							row = row3;
							break;
						}
					}
					if (row != null)
					{
						ManifestLine manifestLine = new ManifestLine
						{
							ItemId = row.ItemId,
							ItemJson = row.Key,
							Name = row.Name,
							Quantity = selectedQuantity
						};
						courierRun.Lines.Add(manifestLine);
						list2.Add(new KeyValuePair<Row, ManifestLine>(row, manifestLine));
					}
				}
				if (courierRun.Lines.Count == 0)
				{
					panel.RefreshOrderButton();
					return;
				}
				Exception ex = null;
				pendingRun = courierRun;
				capturedId = null;
				Submitting = s;
				try
				{
					panel.SubmitOrder("");
				}
				catch (Exception ex2)
				{
					ex = ex2;
				}
				finally
				{
					Submitting = null;
					pendingRun = null;
				}
				if (capturedId == null)
				{
					if (ex != null)
					{
						Core.Log.Warning("Courier: the order could not be submitted: " + ex);
					}
					else
					{
						Core.Log.Msg("Courier: the order was not accepted (see the note under the order button).");
					}
					panel.RefreshOrderButton();
					return;
				}
				foreach (KeyValuePair<Row, ManifestLine> item2 in list2)
				{
					int quantity = item2.Value.Quantity;
					int num2 = RemoveFromSource(storages, item2.Key, quantity);
					if (num2 != quantity)
					{
						Core.Log.Warning($"Courier: expected to pick up {quantity}x {item2.Key.Name} but only {num2} left the rack.");
						item2.Value.Quantity = num2;
					}
				}
				courierRun.Lines.RemoveAll((ManifestLine l) => l.Quantity <= 0);
				if (ex != null)
				{
					Core.Log.Warning("Courier: the order went out but the game reported an error afterwards: " + ex.Message);
				}
				Core.Log.Msg($"Courier: run {capturedId} booked from '{s.Title}' with {courierRun.Lines.Count} line(s), using the {val.ShopName} van.");
				cachedVanUntil = 0f;
			}
			catch (Exception ex3)
			{
				Core.Log.Warning("Courier: order failed: " + ex3);
			}
		}

		internal static void OnDeliveryCreated(DeliveryInstance delivery)
		{
			if (pendingRun != null && delivery != null)
			{
				capturedId = delivery.DeliveryID;
				pendingRun.VanShop = delivery.StoreName;
				State.Data.Runs[capturedId] = pendingRun;
			}
		}

		internal static bool TryGetRun(string deliveryId, out CourierRun run)
		{
			run = null;
			if (string.IsNullOrEmpty(deliveryId))
			{
				return false;
			}
			return State.Data.Runs.TryGetValue(deliveryId, out run);
		}

		private static ItemInstance Rebuild(ManifestLine line)
		{
			ItemInstance val = null;
			try
			{
				val = ItemDeserializer.LoadItem(line.ItemJson);
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not rebuild '" + line.Name + "': " + ex.Message);
			}
			if (val != null)
			{
				return val;
			}
			try
			{
				ItemDefinition item = Registry.GetItem(line.ItemId);
				if ((Object)(object)item != (Object)null)
				{
					val = item.GetDefaultInstance(1);
				}
			}
			catch
			{
			}
			if (val != null)
			{
				Core.Log.Warning("Courier: '" + line.Name + "' is delivered as a plain '" + line.ItemId + "'.");
			}
			else
			{
				Core.Log.Error("Courier: '" + line.Name + "' could not be delivered at all.");
			}
			return val;
		}

		internal static int Store(StorageEntity storage, ItemInstance item, int quantity)
		{
			int num = quantity;
			List<ItemSlot> val = (((Object)(object)storage != (Object)null) ? storage.ItemSlots : null);
			if (val == null || item == null || quantity <= 0)
			{
				return 0;
			}
			string text = null;
			for (int i = 0; i < 2; i++)
			{
				if (num <= 0)
				{
					break;
				}
				for (int j = 0; j < val.Count && num > 0; j++)
				{
					ItemSlot val2 = val[j];
					if (val2 == null)
					{
						continue;
					}
					ItemInstance itemInstance = val2.ItemInstance;
					int num2 = ((itemInstance != null) ? val2.Quantity : 0);
					bool flag = itemInstance == null || num2 <= 0;
					if (flag != (i == 1))
					{
						continue;
					}
					if (!flag)
					{
						if (((BaseItemInstance)itemInstance).ID != ((BaseItemInstance)item).ID)
						{
							continue;
						}
						if (text == null)
						{
							text = KeyOf(item);
						}
						if (KeyOf(itemInstance) != text)
						{
							continue;
						}
					}
					int num3;
					try
					{
						num3 = val2.GetCapacityForItem(item, true);
					}
					catch
					{
						num3 = 0;
					}
					if (num3 > 0)
					{
						int num4 = Math.Min(num3, num);
						if (flag)
						{
							val2.SetStoredItem(item.GetCopy(num4), false);
						}
						else
						{
							val2.ChangeQuantity(num4, false);
						}
						int num5;
						try
						{
							num5 = ((val2.ItemInstance != null) ? val2.Quantity : 0);
						}
						catch
						{
							num5 = num2;
						}
						num -= Math.Max(0, Math.Min(num4, num5 - num2));
					}
				}
			}
			return quantity - num;
		}

		internal static bool LoadVan(DeliveryInstance delivery, CourierRun run)
		{
			DeliveryVehicle val = VanFor(delivery.StoreName);
			StorageEntity val2 = (((Object)(object)val != (Object)null && (Object)(object)val.Vehicle != (Object)null) ? val.Vehicle.Storage : null);
			if ((Object)(object)val2 == (Object)null)
			{
				Core.Log.Warning("Courier: no van storage for '" + delivery.StoreName + "', falling back to default loading.");
				return false;
			}
			run.Loaded = true;
			int num = 0;
			foreach (ManifestLine line in run.Lines)
			{
				ItemInstance val3 = Rebuild(line);
				if (val3 == null)
				{
					continue;
				}
				int num2 = 0;
				try
				{
					num2 = Store(val2, val3, line.Quantity);
				}
				catch (Exception ex)
				{
					Core.Log.Warning("Courier: loading " + line.Name + " failed: " + ex.Message);
				}
				num += num2;
				int num3 = line.Quantity - num2;
				if (num3 > 0)
				{
					Core.Log.Warning($"Courier: {num3}x {line.Name} did not fit in the van and goes back to the rack.");
					try
					{
						ReturnToSource(run, val3, num3);
					}
					catch (Exception ex2)
					{
						Core.Log.Error($"Courier: {num3}x {line.Name} could not be returned: {ex2.Message}");
					}
				}
			}
			Core.Log.Msg($"Courier: van loaded with {num} item(s) for run {delivery.DeliveryID}.");
			return true;
		}

		private static void ReturnToSource(CourierRun run, ItemInstance item, int quantity)
		{
			Property val = FindProperty(run.SourceCode);
			if ((Object)(object)val != (Object)null)
			{
				foreach (StorageEntity item2 in SourceStorages(val))
				{
					if (quantity <= 0)
					{
						break;
					}
					quantity -= Store(item2, item, quantity);
				}
			}
			if (quantity > 0)
			{
				Core.Log.Error($"Courier: {quantity}x {((BaseItemInstance)item).ID} could not be returned to the rack (no room).");
			}
		}

		internal static void ApplyRunLabel(DeliveryStatusDisplay display, CourierRun run, bool items)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)display == (Object)null)
			{
				return;
			}
			string text = RunLabel(run);
			if ((Object)(object)display.ShopLabel != (Object)null)
			{
				display.ShopLabel.text = text;
				((Graphic)display.ShopLabel).color = Color.Lerp(Config.Accent, Color.white, 0.35f);
			}
			if ((Object)(object)display._shopDescriptionLabel != (Object)null)
			{
				display._shopDescriptionLabel.text = "Your own stock, moved between properties";
			}
			if (!items || (Object)(object)display.ItemEntryContainer == (Object)null)
			{
				return;
			}
			Il2CppArrayBase<ItemEntryUI> componentsInChildren = ((Component)display.ItemEntryContainer).GetComponentsInChildren<ItemEntryUI>(true);
			DeliveryInstance deliveryInstance = display.DeliveryInstance;
			int num = ((deliveryInstance != null && deliveryInstance.Items != null) ? ((Il2CppArrayBase<StringIntPair>)(object)deliveryInstance.Items).Length : run.Lines.Count);
			if (num != run.Lines.Count)
			{
				return;
			}
			int maxItemsShown = display._maxItemsShown;
			int num2;
			int num3;
			if (maxItemsShown > 0)
			{
				num2 = ((num > maxItemsShown) ? 1 : 0);
				if (num2 != 0)
				{
					num3 = maxItemsShown;
					goto IL_00de;
				}
			}
			else
			{
				num2 = 0;
			}
			num3 = num;
			goto IL_00de;
			IL_00de:
			int num4 = num3;
			int num5 = ((num2 != 0) ? (maxItemsShown - 1) : num);
			int num6 = componentsInChildren.Length - num4;
			if (num6 < 0)
			{
				return;
			}
			for (int i = 0; i < num5; i++)
			{
				ManifestLine manifestLine = run.Lines[i];
				Sprite val = null;
				try
				{
					ItemInstance val2 = ItemDeserializer.LoadItem(manifestLine.ItemJson);
					if (val2 != null)
					{
						val = ((BaseItemInstance)val2).Icon;
					}
				}
				catch
				{
				}
				if ((Object)(object)val != (Object)null)
				{
					componentsInChildren[num6 + i].Set(manifestLine.Name, manifestLine.Quantity, val);
				}
			}
		}

		private static void RelabelDisplays()
		{
			if ((Object)(object)app == (Object)null || State.Data.Runs.Count == 0)
			{
				return;
			}
			List<DeliveryStatusDisplay> statusDisplays = app.statusDisplays;
			if (statusDisplays == null)
			{
				return;
			}
			for (int i = 0; i < statusDisplays.Count; i++)
			{
				DeliveryStatusDisplay val = statusDisplays[i];
				if (!((Object)(object)val == (Object)null) && val.DeliveryInstance != null && TryGetRun(val.DeliveryInstance.DeliveryID, out var run) && (Object)(object)val.ShopLabel != (Object)null && val.ShopLabel.text != RunLabel(run))
				{
					ApplyRunLabel(val, run, items: true);
				}
			}
		}

		private static void PruneRuns()
		{
			if (State.Data.Runs.Count == 0)
			{
				return;
			}
			LoadManager load = Game.Load;
			DeliveryManager deliveries = Game.Deliveries;
			if ((Object)(object)load == (Object)null || (Object)(object)deliveries == (Object)null || !load.IsGameLoaded || load.TimeSinceGameLoaded < 10f)
			{
				return;
			}
			HashSet<string> hashSet = new HashSet<string>();
			List<DeliveryInstance> deliveries2 = deliveries.Deliveries;
			for (int i = 0; i < deliveries2.Count; i++)
			{
				if (deliveries2[i] != null)
				{
					hashSet.Add(deliveries2[i].DeliveryID);
				}
			}
			List<string> list = new List<string>();
			foreach (string key in State.Data.Runs.Keys)
			{
				if (!hashSet.Contains(key))
				{
					list.Add(key);
				}
			}
			foreach (string item in list)
			{
				State.Data.Runs.Remove(item);
			}
		}

		internal static void Tick()
		{
			DeliveryApp val = Game.App;
			if ((Object)(object)val == (Object)null)
			{
				Forget();
				return;
			}
			if ((Object)(object)app == (Object)null || ((Il2CppObjectBase)app).Pointer != ((Il2CppObjectBase)val).Pointer)
			{
				Forget();
				app = val;
			}
			bool flag = false;
			try
			{
				flag = ((App<DeliveryApp>)(object)app).isOpen;
			}
			catch
			{
			}
			if ((flag && Time.unscaledTime > nextSync) || (shops.Count > 0 && !Usable))
			{
				nextSync = Time.unscaledTime + 1f;
				SyncShops();
			}
			if (flag)
			{
				foreach (Shop value in shops.Values)
				{
					try
					{
						if ((Object)(object)value.Panel != (Object)null && value.Panel.IsOpen)
						{
							value.Panel.RefreshOrderButton();
						}
					}
					catch
					{
					}
				}
			}
			RelabelDisplays();
			if (Time.unscaledTime > nextPrune)
			{
				nextPrune = Time.unscaledTime + 5f;
				PruneRuns();
			}
		}

		internal static void OnAppOpened(DeliveryApp opened)
		{
			if (Game.InGame)
			{
				State.Sync();
				if ((Object)(object)app == (Object)null || ((Il2CppObjectBase)app).Pointer != ((Il2CppObjectBase)opened).Pointer)
				{
					Forget();
					app = opened;
				}
				nextSync = Time.unscaledTime + 1f;
				SyncShops();
			}
		}

		internal static void Forget()
		{
			shops.Clear();
			byPanel.Clear();
			hintCard = null;
			app = null;
			cachedVan = null;
			cachedVanUntil = 0f;
		}

		internal static void Teardown()
		{
			foreach (Shop item in new List<Shop>(shops.Values))
			{
				DestroyShop(item);
			}
			if ((Object)(object)hintCard != (Object)null)
			{
				DestroyCard(hintCard);
				hintCard = null;
			}
			Forget();
		}
	}
	internal static class Patches
	{
		private const BindingFlags F = BindingFlags.Static | BindingFlags.NonPublic;

		internal static bool Healthy { get; private set; } = true;

		internal static void Apply(Harmony h)
		{
			Healthy = true;
			Patch(h, required: true, AccessTools.Method(typeof(DeliveryShop), "GetCartCost", (Type[])null, (Type[])null), null, "CartCostPost");
			Patch(h, required: true, AccessTools.Method(typeof(DeliveryShop), "GetDeliveryFee", (Type[])null, (Type[])null), null, "DeliveryFeePost");
			Patch(h, required: true, AccessTools.Method(typeof(DeliveryManager), "SendDelivery", (Type[])null, (Type[])null), "SendDeliveryPre", null);
			Patch(h, required: true, AccessTools.Method(typeof(MoneyManager), "CreateOnlineTransaction", (Type[])null, (Type[])null), "TransactionPre", null);
			Patch(h, required: true, AccessTools.Method(typeof(DeliveryInstance), "AddItemsToDeliveryVehicle", (Type[])null, (Type[])null), "AddItemsPre", null);
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryShop), "RefreshOrderButton", (Type[])null, (Type[])null), "OrderButtonPre", "OrderButtonPost");
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryShop), "GetPotentialDestinations", (Type[])null, (Type[])null), null, "DestinationsPost");
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryManager), "RecordDeliveryReceipt_Server", (Type[])null, (Type[])null), "SkipWhileSubmitting", null);
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryManager), "RpcWriter___Server_RecordDeliveryReceipt_Server_2582461062", (Type[])null, (Type[])null), "SkipWhileSubmitting", null);
			Patch(h, required: false, AccessTools.Method(typeof(VariableDatabase), "NotifyItemAcquired", (Type[])null, (Type[])null), "SkipWhileSubmitting", null);
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryStatusDisplay), "AssignDelivery", (Type[])null, (Type[])null), null, "AssignDeliveryPost");
			Patch(h, required: false, AccessTools.Method(typeof(DeliveryApp), "SetOpen", (Type[])null, (Type[])null), null, "SetOpenPost");
			if (!Healthy)
			{
				Core.Log.Error("Courier: a required game hook is missing (game update?). The courier is switched off until the mod is updated.");
			}
		}

		private static void Patch(Harmony h, bool required, MethodBase target, string prefix, string postfix)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			string text = prefix ?? postfix;
			try
			{
				if (target == null)
				{
					Core.Log.Warning("Courier: hook target missing for " + text);
					if (required)
					{
						Healthy = false;
					}
				}
				else
				{
					h.Patch(target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Patches).GetMethod(prefix, BindingFlags.Static | BindingFlags.NonPublic)), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Patches).GetMethod(postfix, BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not hook " + target?.Name + " (" + text + "): " + ex.Message);
				if (required)
				{
					Healthy = false;
				}
			}
		}

		private static void CartCostPost(DeliveryShop __instance, ref float __result)
		{
			try
			{
				Courier.Shop shop = Courier.ByPanel(__instance);
				if (shop != null)
				{
					__result = (Courier.CartHasItems(shop) ? 1E-20f : 0f);
				}
			}
			catch
			{
			}
		}

		private static void DeliveryFeePost(DeliveryShop __instance, ref float __result)
		{
			try
			{
				if (Courier.ByPanel(__instance) != null)
				{
					__result = Config.DeliveryFee;
				}
			}
			catch
			{
			}
		}

		private static void OrderButtonPre(DeliveryShop __instance)
		{
			try
			{
				Courier.Shop shop = Courier.ByPanel(__instance);
				if (shop != null)
				{
					Courier.EnsureVan(shop);
				}
			}
			catch
			{
			}
		}

		private static void OrderButtonPost(DeliveryShop __instance)
		{
			try
			{
				Courier.Shop shop = Courier.ByPanel(__instance);
				if (shop == null)
				{
					return;
				}
				string text = Courier.BlockReason(shop);
				if (text != null)
				{
					if ((Object)(object)__instance.OrderButton != (Object)null)
					{
						((Selectable)__instance.OrderButton).interactable = false;
					}
					Text orderButtonNote = __instance.OrderButtonNote;
					if ((Object)(object)orderButtonNote != (Object)null)
					{
						orderButtonNote.text = text;
						((Behaviour)orderButtonNote).enabled = true;
					}
				}
			}
			catch
			{
			}
		}

		private static void DestinationsPost(DeliveryShop __instance, List<Property> __result)
		{
			try
			{
				Courier.Shop shop = Courier.ByPanel(__instance);
				if (shop == null || __result == null || (Object)(object)shop.Source == (Object)null)
				{
					return;
				}
				for (int num = __result.Count - 1; num >= 0; num--)
				{
					Property val = __result[num];
					if ((Object)(object)val != (Object)null && ((Il2CppObjectBase)val).Pointer == ((Il2CppObjectBase)shop.Source).Pointer)
					{
						__result.RemoveAt(num);
					}
				}
			}
			catch
			{
			}
		}

		private static void SendDeliveryPre(DeliveryInstance delivery)
		{
			try
			{
				if (Courier.Submitting != null)
				{
					Courier.OnDeliveryCreated(delivery);
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: SendDelivery hook failed: " + ex.Message);
			}
		}

		private static bool SkipWhileSubmitting()
		{
			return Courier.Submitting == null;
		}

		private static void TransactionPre(ref string _transaction_Name, ref float _unit_Amount, ref float _quantity)
		{
			try
			{
				Courier.Shop submitting = Courier.Submitting;
				if (submitting != null)
				{
					_transaction_Name = Config.ServiceName + " run from " + submitting.Title;
					_unit_Amount = -Config.DeliveryFee;
					_quantity = 1f;
				}
			}
			catch
			{
			}
		}

		private static bool AddItemsPre(DeliveryInstance __instance)
		{
			CourierRun run = null;
			try
			{
				State.Sync();
				if (__instance == null || !Courier.TryGetRun(__instance.DeliveryID, out run))
				{
					return true;
				}
				if (run.Loaded)
				{
					return false;
				}
				return !Courier.LoadVan(__instance, run);
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: van loading failed: " + ex);
				return run == null || !run.Loaded;
			}
		}

		private static void AssignDeliveryPost(DeliveryStatusDisplay __instance, DeliveryInstance instance)
		{
			try
			{
				State.Sync();
				if (instance != null && Courier.TryGetRun(instance.DeliveryID, out var run))
				{
					Courier.ApplyRunLabel(__instance, run, items: true);
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: could not label the delivery: " + ex.Message);
			}
		}

		private static void SetOpenPost(DeliveryApp __instance, bool open)
		{
			try
			{
				if (open)
				{
					Courier.OnAppOpened(__instance);
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: app open hook failed: " + ex.Message);
			}
		}
	}
	internal static class FixerUnlock
	{
		private static DialogueController controller;

		private static DialogueChoice choice;

		private static DialogueChoice exitChoice;

		private static int exitChoicePriority;

		private static float nextLook;

		private static string pendingLine;

		private static float pendingLineAt;

		internal static bool Installed
		{
			get
			{
				if ((Object)(object)controller != (Object)null)
				{
					return choice != null;
				}
				return false;
			}
		}

		internal static string ChoiceText => "I need a courier to move product between my properties (" + MoneyManager.FormatAmount((float)Config.UnlockPrice, false, false) + ")";

		private static bool ShouldShow()
		{
			try
			{
				return Game.IsHost && Patches.Healthy && Config.RequireUnlock && !State.Data.Unlocked;
			}
			catch
			{
				return false;
			}
		}

		internal static void Tick()
		{
			if (pendingLine != null && Time.unscaledTime >= pendingLineAt)
			{
				string text = pendingLine;
				pendingLine = null;
				try
				{
					if ((Object)(object)controller != (Object)null && (Object)(object)controller.handler != (Object)null)
					{
						controller.handler.ShowWorldspaceDialogue(text, 9f);
					}
				}
				catch (Exception ex)
				{
					Core.Log.Warning("Courier: Fixer line failed: " + ex.Message);
				}
			}
			if (!Game.IsHost)
			{
				return;
			}
			if (Installed)
			{
				try
				{
					string choiceText = ChoiceText;
					if (choice.ChoiceText != choiceText)
					{
						choice.ChoiceText = choiceText;
					}
					return;
				}
				catch
				{
					return;
				}
			}
			if (!(Time.unscaledTime < nextLook))
			{
				nextLook = Time.unscaledTime + 3f;
				DialogueController_Fixer val = Object.FindObjectOfType<DialogueController_Fixer>();
				if ((Object)(object)val != (Object)null)
				{
					Install((DialogueController)(object)val);
				}
			}
		}

		private static void Install(DialogueController c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			DialogueChoice val = new DialogueChoice();
			val.ChoiceText = ChoiceText;
			val.Enabled = true;
			val.Conversation = null;
			if (val.onChoosen == null)
			{
				val.onChoosen = new UnityEvent();
			}
			val.onChoosen.AddListener(UnityAction.op_Implicit((Action)OnChosen));
			val.shouldShowCheck = ShouldShowCheck.op_Implicit((Func<bool, bool>)((bool enabled) => ShouldShow()));
			exitChoice = null;
			try
			{
				int num = 0;
				DialogueChoice val2 = null;
				for (int num2 = 0; num2 < c.Choices.Count; num2++)
				{
					DialogueChoice val3 = c.Choices[num2];
					if (val3 != null && !((Object)(object)val3.Conversation != (Object)null) && !((Delegate)(object)val3.shouldShowCheck != (Delegate)null) && !((Delegate)(object)val3.isValidCheck != (Delegate)null) && (val3.onChoosen == null || ((UnityEventBase)val3.onChoosen).GetPersistentEventCount() <= 0))
					{
						val2 = val3;
						num++;
					}
				}
				if (num == 1)
				{
					exitChoice = val2;
					exitChoicePriority = val2.Priority;
					val2.Priority = exitChoicePriority - 1;
				}
			}
			catch
			{
				exitChoice = null;
			}
			c.AddDialogueChoice(val, 0);
			controller = c;
			choice = val;
			Core.Log.Msg("Courier: Fixer conversation hooked.");
		}

		private static void Say(string line)
		{
			pendingLine = line;
			pendingLineAt = Time.unscaledTime + 0.4f;
		}

		internal static void OnChosen()
		{
			try
			{
				if (State.Data.Unlocked)
				{
					return;
				}
				MoneyManager money = Game.Money;
				float num = Config.UnlockPrice;
				string text = MoneyManager.FormatAmount(num, false, false);
				if ((Object)(object)money == (Object)null)
				{
					return;
				}
				if (money.cashBalance < num)
				{
					Say("Setting up a courier is " + text + ", cash. Come back when you have it.");
					return;
				}
				if (num > 0f)
				{
					money.ChangeCashBalance(0f - num, true, true);
				}
				State.Data.Unlocked = true;
				Say("Done. Name a storage rack \"" + Config.RackName + "\" at any of your properties, then book the run in your Deliveries app.");
				try
				{
					NotificationsManager val = Object.FindObjectOfType<NotificationsManager>();
					DeliveryApp app = Game.App;
					if ((Object)(object)val != (Object)null)
					{
						val.SendNotification(Config.ServiceName + " service unlocked", "See your Deliveries app", ((Object)(object)app != (Object)null) ? ((App<DeliveryApp>)(object)app).AppIcon : null, 6f, true);
					}
				}
				catch
				{
				}
				Core.Log.Msg("Courier: service bought from the Fixer for " + text + ".");
				Courier.SyncShops();
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Courier: unlock failed: " + ex);
			}
		}

		internal static void Forget()
		{
			controller = null;
			choice = null;
			exitChoice = null;
			pendingLine = null;
		}

		internal static void Teardown()
		{
			try
			{
				if ((Object)(object)controller != (Object)null && choice != null && controller.Choices != null)
				{
					controller.Choices.Remove(choice);
				}
				if ((Object)(object)controller != (Object)null && exitChoice != null)
				{
					exitChoice.Priority = exitChoicePriority;
				}
			}
			catch
			{
			}
			Forget();
		}
	}
}
namespace SupplyRun
{
	public class Mod : MelonMod
	{
		private float nextErrorLog;

		public override void OnInitializeMelon()
		{
			Core.Init(((MelonBase)this).LoggerInstance, "");
		}

		public override void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
			try
			{
				Core.OnScene(sceneName);
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("scene change: " + ex.Message);
			}
		}

		public override void OnUpdate()
		{
			try
			{
				Core.Tick();
			}
			catch (Exception ex)
			{
				if (!(Time.unscaledTime < nextErrorLog))
				{
					nextErrorLog = Time.unscaledTime + 10f;
					((MelonBase)this).LoggerInstance.Warning("update: " + ex);
				}
			}
		}

		public override void OnDeinitializeMelon()
		{
			Core.Shutdown();
		}
	}
}