Decompiled source of Autonomous Dealers v1.0.1

Mods/AutonomousDealers.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using AutonomousDealers;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Cartel;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI.Phone.Messages;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "Autonomous Dealers", "1.0.1", "MightyMods", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("AutonomousDealers")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AutonomousDealers")]
[assembly: AssemblyTitle("AutonomousDealers")]
[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 AutonomousDealers
{
	public class Core : MelonMod
	{
		internal const int VanillaLimit = 10;

		internal static MelonPreferences_Entry<int> MaxCustomers;

		internal static MelonPreferences_Entry<int> DealerSlots;

		internal static Instance Log;

		internal static int SlotTarget => Math.Clamp(DealerSlots?.Value ?? 10, 1, 20);

		internal static int Limit => Math.Clamp(MaxCustomers?.Value ?? 20, 1, 50);

		public override void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
			if (sceneName == "Main")
			{
				MelonCoroutines.Start(DealerTrips.DescribeBases());
			}
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			if (sceneName == "Main")
			{
				DealerTrips.Reset();
			}
		}

		public override void OnUpdate()
		{
			DealerTrips.Update();
		}

		public override void OnInitializeMelon()
		{
			Log = ((MelonBase)this).LoggerInstance;
			MelonPreferences_Category obj = MelonPreferences.CreateCategory("AutonomousDealers", "Autonomous Dealers");
			MaxCustomers = obj.CreateEntry<int>("MaxCustomers", 20, "Max customers per dealer", "How many customers each dealer can be assigned. The game's normal limit is 10. Allowed: 1 to 50.", false, false, (ValueValidator)null, (string)null);
			DealerSlots = obj.CreateEntry<int>("DealerInventorySlots", 10, "Dealer inventory slots", "How many inventory slots each of your dealers has (game default is 5). Allowed: up to 20. Takes effect after reloading your save; lowering it does not remove slots a dealer already has until you reload.", false, false, (ValueValidator)null, (string)null);
			DealerTrips.Init();
			Log.Msg($"Loaded. Dealers can take up to {Limit} customers (game normally allows {10}) and have {SlotTarget} inventory slots.");
		}
	}
	[HarmonyPatch(typeof(DealerManagementApp), "Start")]
	internal static class DealerAppStartPatch
	{
		private static void Postfix(DealerManagementApp __instance)
		{
			try
			{
				Il2CppReferenceArray<RectTransform> customerEntries = __instance.CustomerEntries;
				if (customerEntries == null || ((Il2CppArrayBase<RectTransform>)(object)customerEntries).Length == 0)
				{
					Core.Log.Warning("Dealers app has no customer rows to copy.");
					return;
				}
				int length = ((Il2CppArrayBase<RectTransform>)(object)customerEntries).Length;
				int limit = Core.Limit;
				if (limit <= length)
				{
					Core.Log.Msg($"Dealers app already has {length} customer rows.");
					return;
				}
				RectTransform val = ((Il2CppArrayBase<RectTransform>)(object)customerEntries)[length - 1];
				Transform parent = ((Transform)val).parent;
				Il2CppReferenceArray<RectTransform> val2 = new Il2CppReferenceArray<RectTransform>((long)limit);
				for (int i = 0; i < length; i++)
				{
					((Il2CppArrayBase<RectTransform>)(object)val2)[i] = ((Il2CppArrayBase<RectTransform>)(object)customerEntries)[i];
				}
				for (int j = length; j < limit; j++)
				{
					GameObject obj = Object.Instantiate<GameObject>(((Component)val).gameObject, parent);
					((Object)obj).name = $"AssignedCustomerEntry ({j})";
					RectTransform component = obj.GetComponent<RectTransform>();
					((Transform)component).SetSiblingIndex(((Transform)val).GetSiblingIndex() + (j - length) + 1);
					obj.SetActive(false);
					((Il2CppArrayBase<RectTransform>)(object)val2)[j] = component;
				}
				__instance.CustomerEntries = val2;
				Core.Log.Msg($"Dealers app customer rows: {length} -> {limit}.");
			}
			catch (Exception ex)
			{
				Core.Log.Error("Could not add customer rows to the Dealers app: " + ex);
			}
		}
	}
	[HarmonyPatch(typeof(DealerManagementApp), "SetDisplayedDealer")]
	internal static class DealerAppShowDealerPatch
	{
		private static readonly Regex OutOfTen = new Regex("/\\s*" + 10 + "\\b");

		private static void Postfix(DealerManagementApp __instance, Dealer dealer)
		{
			try
			{
				if (!((Object)(object)dealer == (Object)null))
				{
					bool active = (dealer.AssignedCustomers?.Count ?? 0) < Core.Limit;
					Button assignCustomerButton = __instance.AssignCustomerButton;
					if ((Object)(object)assignCustomerButton != (Object)null)
					{
						((Component)assignCustomerButton).gameObject.SetActive(active);
					}
					Text customerTitleLabel = __instance.CustomerTitleLabel;
					if ((Object)(object)customerTitleLabel != (Object)null && customerTitleLabel.text != null)
					{
						customerTitleLabel.text = OutOfTen.Replace(customerTitleLabel.text, "/" + Core.Limit);
					}
				}
			}
			catch (Exception ex)
			{
				Core.Log.Error("Error while updating the Dealers app: " + ex);
			}
		}
	}
	internal static class DealerSlots
	{
		internal static Dealer DealerOf(NPCInventory inv)
		{
			if ((Object)(object)inv == (Object)null)
			{
				return null;
			}
			NPC obj = inv._npc ?? ((Component)inv).GetComponentInParent<NPC>();
			Dealer val = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<Dealer>() : null);
			if ((Object)(object)val == (Object)null || (Object)(object)((Il2CppObjectBase)val).TryCast<CartelDealer>() != (Object)null)
			{
				return null;
			}
			return val;
		}

		internal static void TopUp(NPCInventory inv, Dealer dealer, string when)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)inv == (Object)null || (Object)(object)dealer == (Object)null || (Object)(object)((Il2CppObjectBase)dealer).TryCast<CartelDealer>() != (Object)null)
				{
					return;
				}
				List<ItemSlot> itemSlots = inv.ItemSlots;
				if (itemSlots == null)
				{
					return;
				}
				int count = itemSlots.Count;
				if (count == 0 || count >= Core.SlotTarget)
				{
					return;
				}
				IItemSlotOwner slotOwner = new IItemSlotOwner(((Il2CppObjectBase)inv).Pointer);
				while (itemSlots.Count < Core.SlotTarget)
				{
					new ItemSlot().SetSlotOwner(slotOwner);
					if (itemSlots.Count > Core.SlotTarget + 5)
					{
						break;
					}
				}
			}
			catch (Exception value)
			{
				Core.Log.Error($"[slots] Could not add inventory slots ({when}): {value}");
			}
		}
	}
	[HarmonyPatch(typeof(NPCInventory), "Awake")]
	internal static class InventoryAwakePatch
	{
		private static void Postfix(NPCInventory __instance)
		{
			DealerSlots.TopUp(__instance, DealerSlots.DealerOf(__instance), "inventory awake");
		}
	}
	[HarmonyPatch(typeof(NPCInventory), "Start")]
	internal static class InventoryStartPatch
	{
		private static void Postfix(NPCInventory __instance)
		{
			DealerSlots.TopUp(__instance, DealerSlots.DealerOf(__instance), "inventory start");
		}
	}
	[HarmonyPatch(typeof(Dealer), "Start")]
	internal static class DealerStartSlotsPatch
	{
		private static void Postfix(Dealer __instance)
		{
			DealerSlots.TopUp(((NPC)__instance).Inventory, __instance, "dealer start");
		}
	}
	[HarmonyPatch(typeof(Dealer), "Load", new Type[]
	{
		typeof(NPCData),
		typeof(string)
	})]
	internal static class DealerLoadPatchA
	{
		private static void Prefix(Dealer __instance)
		{
			DealerSlots.TopUp(((NPC)__instance).Inventory, __instance, "before load");
		}
	}
	[HarmonyPatch(typeof(Dealer), "Load", new Type[]
	{
		typeof(DynamicSaveData),
		typeof(NPCData)
	})]
	internal static class DealerLoadPatchB
	{
		private static void Prefix(Dealer __instance)
		{
			DealerSlots.TopUp(((NPC)__instance).Inventory, __instance, "before load");
		}
	}
	internal static class DealerTrips
	{
		private enum StopKind
		{
			Entrance,
			Safe,
			Restock
		}

		private class Stop
		{
			public StopKind Kind;

			public Vector3 Target;

			public StorageEntity Storage;
		}

		private class Trip
		{
			public Dealer Dealer;

			public Property Base;

			public List<Stop> Stops = new List<Stop>();

			public int StopIndex;

			public string LastResult = "";

			public int OrigMask = int.MinValue;

			public float StartedAt;

			public int Retries;

			public bool LeftBuilding;
		}

		internal const string RestockName = "dealer restock";

		internal static MelonPreferences_Category BaseCat;

		internal static MelonPreferences_Entry<bool> TripsEnabled;

		internal static MelonPreferences_Entry<int> TripStartTime;

		internal static MelonPreferences_Entry<bool> TestKeyEnabled;

		private static readonly Dictionary<string, MelonPreferences_Entry<string>> BaseEntries = new Dictionary<string, MelonPreferences_Entry<string>>();

		private const float ArriveDistance = 2.5f;

		private const float NearStorageDistance = 3.5f;

		private const float TripTimeoutSeconds = 300f;

		private const int MaxRetries = 6;

		private static readonly Dictionary<string, Trip> Active = new Dictionary<string, Trip>();

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

		private static float _nextTick;

		internal static void Init()
		{
			MelonPreferences_Category obj = MelonPreferences.CreateCategory("AutonomousDealers_Trips", "Autonomous Dealers - Base trips");
			TripsEnabled = obj.CreateEntry<bool>("Enabled", true, "Dealers visit their base", "After their last deal of the night, dealers walk to their base: they drop cash in a Safe there, and restock product from storage named 'Dealer Restock'.", false, false, (ValueValidator)null, (string)null);
			TripStartTime = obj.CreateEntry<int>("EarliestTripTime", 2200, "Earliest trip time", "Dealers only start their trip after this time (24-hour clock, e.g. 2200 = 10 PM), once no deal is coming up within an hour. Trips can happen until 6 AM.", false, false, (ValueValidator)null, (string)null);
			TestKeyEnabled = obj.CreateEntry<bool>("TestKeyF9", false, "F9 test key", "When on, pressing F9 in game sends every dealer to their base right now. Handy for checking your setup.", false, false, (ValueValidator)null, (string)null);
			BaseCat = MelonPreferences.CreateCategory("AutonomousDealers_Bases", "Autonomous Dealers - Dealer bases");
		}

		private static string BaseSettingFor(Dealer d)
		{
			string name = ((Object)d).name;
			if (!BaseEntries.TryGetValue(name, out var value))
			{
				value = BaseCat.CreateEntry<string>("Base_" + name, "nearest", name + "'s base", "Property name for " + name + "'s base (e.g. Bungalow, Storage Unit, Sweatshop), 'nearest', or 'none'.", false, false, (ValueValidator)null, (string)null);
				BaseEntries[name] = value;
				BaseCat.SaveToFile(false);
			}
			return (value.Value ?? "").Trim();
		}

		private static bool IsServer()
		{
			try
			{
				return InstanceFinder.IsServer;
			}
			catch
			{
				return true;
			}
		}

		internal static StorageEntity FindSafe(Property prop)
		{
			List<BuildableItem> val = ((prop != null) ? prop.BuildableItems : null);
			if (val == null)
			{
				return null;
			}
			for (int i = 0; i < val.Count; i++)
			{
				BuildableItem val2 = val[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					StorageEntity componentInChildren = ((Component)val2).GetComponentInChildren<StorageEntity>();
					if (!((Object)(object)componentInChildren == (Object)null) && (componentInChildren.StorageEntityName + " " + ((Object)((Component)val2).gameObject).name).ToLowerInvariant().Contains("safe"))
					{
						return componentInChildren;
					}
				}
			}
			return null;
		}

		internal static StorageEntity FindRestock(Property prop)
		{
			List<BuildableItem> val = ((prop != null) ? prop.BuildableItems : null);
			if (val == null)
			{
				return null;
			}
			for (int i = 0; i < val.Count; i++)
			{
				BuildableItem val2 = val[i];
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				string text = "";
				try
				{
					PlaceableStorageEntity obj = ((Il2CppObjectBase)val2).TryCast<PlaceableStorageEntity>();
					text = ((obj != null) ? obj.Name : null) ?? "";
				}
				catch
				{
				}
				if (text.ToLowerInvariant().Contains("dealer restock"))
				{
					StorageEntity componentInChildren = ((Component)val2).GetComponentInChildren<StorageEntity>();
					if ((Object)(object)componentInChildren != (Object)null)
					{
						return componentInChildren;
					}
				}
			}
			return null;
		}

		private static Property ResolveBase(Dealer d, out string why)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			why = "";
			string text = BaseSettingFor(d);
			List<Property> ownedProperties = Property.OwnedProperties;
			if (text.Equals("none", StringComparison.OrdinalIgnoreCase) || text == "")
			{
				why = "base set to none";
				return null;
			}
			if (ownedProperties == null || ownedProperties.Count == 0)
			{
				why = "you don't own any properties";
				return null;
			}
			if (text.Equals("nearest", StringComparison.OrdinalIgnoreCase))
			{
				Property val = null;
				float num = float.MaxValue;
				for (int i = 0; i < ownedProperties.Count; i++)
				{
					Property val2 = ownedProperties[i];
					if (!((Object)(object)val2 == (Object)null) && (!((Object)(object)FindSafe(val2) == (Object)null) || !((Object)(object)FindRestock(val2) == (Object)null)))
					{
						float num2 = Vector3.Distance(PosOf(d), ((Component)val2).transform.position);
						if (num2 < num)
						{
							num = num2;
							val = val2;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					why = "none of your properties has a Safe or a 'Dealer Restock' storage";
				}
				return val;
			}
			for (int j = 0; j < ownedProperties.Count; j++)
			{
				Property val3 = ownedProperties[j];
				if ((Object)(object)val3 != (Object)null && (val3.PropertyName ?? "").IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return val3;
				}
			}
			why = "you don't own a property called '" + text + "'";
			return null;
		}

		private static Vector3 PosOf(Dealer d)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return ((NPC)d).Movement.FootPosition;
			}
			catch
			{
				return ((Component)d).transform.position;
			}
		}

		private static Vector3 Snap(Vector3 pos)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(pos, ref val, 3f, -1))
			{
				pos = ((NavMeshHit)(ref val)).position;
			}
			return pos;
		}

		internal static Vector3 WalkTargetFor(StorageEntity se)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)se).transform.position;
			try
			{
				PlaceableStorageEntity componentInParent = ((Component)se).GetComponentInParent<PlaceableStorageEntity>();
				Il2CppReferenceArray<Transform> val = ((componentInParent != null) ? componentInParent.AccessPoints : null);
				if (val != null && ((Il2CppArrayBase<Transform>)(object)val).Length > 0 && (Object)(object)((Il2CppArrayBase<Transform>)(object)val)[0] != (Object)null)
				{
					position = ((Il2CppArrayBase<Transform>)(object)val)[0].position;
				}
			}
			catch
			{
			}
			return Snap(position);
		}

		internal static bool HasDealSoon(Dealer d, int now, out string reason)
		{
			reason = "";
			if ((Object)(object)d.currentContract != (Object)null)
			{
				reason = "on a deal right now";
				return true;
			}
			List<Contract> activeContracts = d.ActiveContracts;
			if (activeContracts == null)
			{
				return false;
			}
			for (int i = 0; i < activeContracts.Count; i++)
			{
				Contract obj = activeContracts[i];
				QuestWindowConfig val = ((obj != null) ? obj.DeliveryWindow : null);
				if (val != null)
				{
					int windowStartTime = val.WindowStartTime;
					int windowEndTime = val.WindowEndTime;
					bool num = ((windowStartTime > windowEndTime) ? (now >= windowStartTime || now < windowEndTime) : (now >= windowStartTime && now < windowEndTime));
					int num2 = (ToMins(windowStartTime) - ToMins(now) + 1440) % 1440;
					if (num)
					{
						reason = $"a deal window is open ({windowStartTime:0000}-{windowEndTime:0000})";
						return true;
					}
					if (num2 <= 60)
					{
						reason = $"a deal starts at {windowStartTime:0000}";
						return true;
					}
				}
			}
			return false;
		}

		private static int ToMins(int hhmm)
		{
			return hhmm / 100 * 60 + hhmm % 100;
		}

		private static bool IsProduct(ItemInstance item)
		{
			if (item != null)
			{
				return ((Il2CppObjectBase)item).TryCast<ProductItemInstance>() != null;
			}
			return false;
		}

		private static bool Usable(ItemSlot s)
		{
			if (s != null)
			{
				return !s.IsLocked;
			}
			return false;
		}

		private static bool WantsRestock(Dealer d, StorageEntity storage)
		{
			NPCInventory inventory = ((NPC)d).Inventory;
			List<ItemSlot> val = ((inventory != null) ? inventory.ItemSlots : null);
			List<ItemSlot> val2 = ((storage != null) ? storage.ItemSlots : null);
			if (val == null || val2 == null)
			{
				return false;
			}
			bool flag = false;
			for (int i = 0; i < val2.Count; i++)
			{
				if (Usable(val2[i]) && IsProduct(val2[i].ItemInstance) && val2[i].Quantity > 0)
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return false;
			}
			for (int j = 0; j < val.Count; j++)
			{
				ItemSlot val3 = val[j];
				if (!Usable(val3))
				{
					continue;
				}
				if (val3.ItemInstance == null)
				{
					return true;
				}
				if (!IsProduct(val3.ItemInstance) || val3.Quantity >= ((BaseItemInstance)val3.ItemInstance).StackLimit)
				{
					continue;
				}
				for (int k = 0; k < val2.Count; k++)
				{
					ItemSlot val4 = val2[k];
					if (Usable(val4) && IsProduct(val4.ItemInstance) && val4.Quantity > 0 && val4.ItemInstance.CanStackWith(val3.ItemInstance, false))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static void Restock(Trip t, StorageEntity storage)
		{
			Dealer dealer = t.Dealer;
			NPCInventory inventory = ((NPC)dealer).Inventory;
			List<ItemSlot> val = ((inventory != null) ? inventory.ItemSlots : null);
			List<ItemSlot> val2 = ((storage != null) ? storage.ItemSlots : null);
			if (val == null || val2 == null)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < val.Count; i++)
			{
				ItemSlot val3 = val[i];
				if (!Usable(val3) || !IsProduct(val3.ItemInstance))
				{
					continue;
				}
				for (int j = 0; j < val2.Count; j++)
				{
					if (val3.Quantity >= ((BaseItemInstance)val3.ItemInstance).StackLimit)
					{
						break;
					}
					ItemSlot val4 = val2[j];
					if (Usable(val4) && IsProduct(val4.ItemInstance) && val4.Quantity > 0 && val4.ItemInstance.CanStackWith(val3.ItemInstance, false))
					{
						int num3 = Math.Min(((BaseItemInstance)val3.ItemInstance).StackLimit - val3.Quantity, val4.Quantity);
						if (num3 > 0)
						{
							val3.ChangeQuantity(num3, false);
							val4.ChangeQuantity(-num3, false);
							num += num3;
						}
					}
				}
			}
			for (int k = 0; k < val.Count; k++)
			{
				ItemSlot val5 = val[k];
				if (!Usable(val5) || val5.ItemInstance != null)
				{
					continue;
				}
				ItemSlot val6 = null;
				ItemSlot val7 = null;
				for (int l = 0; l < val2.Count; l++)
				{
					ItemSlot val8 = val2[l];
					if (!Usable(val8) || !IsProduct(val8.ItemInstance) || val8.Quantity <= 0)
					{
						continue;
					}
					if (val7 == null)
					{
						val7 = val8;
					}
					bool flag = false;
					for (int m = 0; m < val.Count; m++)
					{
						ItemSlot obj = val[m];
						ItemInstance val9 = ((obj != null) ? obj.ItemInstance : null);
						if (val9 != null && val8.ItemInstance.CanStackWith(val9, false))
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						val6 = val8;
						break;
					}
				}
				if (val6 == null)
				{
					val6 = val7;
				}
				if (val6 == null)
				{
					break;
				}
				int num4 = Math.Min(((BaseItemInstance)val6.ItemInstance).StackLimit, val6.Quantity);
				ItemInstance copy = val6.ItemInstance.GetCopy(num4);
				val5.SetStoredItem(copy, false);
				val6.ChangeQuantity(-num4, false);
				num2++;
			}
			if (num == 0 && num2 == 0)
			{
				Core.Log.Msg($"[trips] {((Object)dealer).name}: nothing to restock at {t.Base.PropertyName}.");
			}
			else
			{
				Core.Log.Msg($"[trips] {((Object)dealer).name}: restocked at {t.Base.PropertyName} (topped up {num} items, filled {num2} empty slot(s)).");
			}
		}

		private static void DropOffCash(Trip t, StorageEntity safe)
		{
			Dealer dealer = t.Dealer;
			float cash = dealer.Cash;
			if (cash < 1f)
			{
				return;
			}
			if ((Object)(object)safe == (Object)null)
			{
				Core.Log.Msg("[trips] " + ((Object)dealer).name + ": the Safe is gone, keeping cash.");
				return;
			}
			ItemDefinition item = Registry.GetItem("cash");
			object obj;
			if (item == null)
			{
				obj = null;
			}
			else
			{
				ItemInstance defaultInstance = item.GetDefaultInstance(1);
				obj = ((defaultInstance != null) ? ((Il2CppObjectBase)defaultInstance).TryCast<CashInstance>() : null);
			}
			CashInstance val = (CashInstance)obj;
			if (val == null)
			{
				Core.Log.Warning("[trips] " + ((Object)dealer).name + ": couldn't create cash item, keeping cash.");
				return;
			}
			val.SetBalance(cash, false);
			if (!safe.CanItemFit((ItemInstance)(object)val, 1))
			{
				Core.Log.Msg($"[trips] {((Object)dealer).name}: the Safe at {t.Base.PropertyName} is full, keeping cash.");
			}
			else
			{
				safe.InsertItem((ItemInstance)(object)val, true);
				dealer.ChangeCash(0f - cash);
				Core.Log.Msg($"[trips] {((Object)dealer).name}: dropped ${cash:N0} in the Safe at {t.Base.PropertyName}.");
			}
		}

		internal static void Update()
		{
			try
			{
				if (TestKeyEnabled.Value && F9Pressed())
				{
					Core.Log.Msg("[trips] F9 pressed: sending dealers to their bases now.");
					TryStartAll(force: true);
				}
				if (!(Time.unscaledTime < _nextTick))
				{
					_nextTick = Time.unscaledTime + 2f;
					if (TripsEnabled.Value && IsServer())
					{
						ProgressTrips();
						TryStartAll(force: false);
					}
				}
			}
			catch (Exception ex)
			{
				Core.Log.Error("[trips] " + ex);
			}
		}

		private static bool F9Pressed()
		{
			try
			{
				Keyboard current = Keyboard.current;
				return current != null && ((ButtonControl)current.f9Key).wasPressedThisFrame;
			}
			catch
			{
				return false;
			}
		}

		private static int TripDay(TimeManager tm)
		{
			if (tm.CurrentTime >= 600)
			{
				return tm.ElapsedDays;
			}
			return tm.ElapsedDays - 1;
		}

		private static bool InTripHours(TimeManager tm)
		{
			int currentTime = tm.CurrentTime;
			if (currentTime < TripStartTime.Value)
			{
				return currentTime < 600;
			}
			return true;
		}

		private static void TryStartAll(bool force)
		{
			if (!NetworkSingleton<TimeManager>.InstanceExists)
			{
				return;
			}
			TimeManager instance = NetworkSingleton<TimeManager>.Instance;
			List<Dealer> allPlayerDealers = Dealer.AllPlayerDealers;
			if (allPlayerDealers == null || (!force && !InTripHours(instance)))
			{
				return;
			}
			int num = TripDay(instance);
			for (int i = 0; i < allPlayerDealers.Count; i++)
			{
				Dealer val = allPlayerDealers[i];
				if ((Object)(object)val == (Object)null || !val.IsRecruited || Active.ContainsKey(((Object)val).name) || (!force && LastTripDay.TryGetValue(((Object)val).name, out var value) && value == num) || !((NPC)val).IsConscious || ((NPC)val).IsInVehicle)
				{
					continue;
				}
				if (force ? ((Object)(object)val.currentContract != (Object)null) : HasDealSoon(val, instance.CurrentTime, out var _))
				{
					if (force)
					{
						Core.Log.Msg("[trips] " + ((Object)val).name + ": on a deal right now, so no trip.");
					}
				}
				else
				{
					LastTripDay[((Object)val).name] = num;
					StartTrip(val);
				}
			}
		}

		private static void StartTrip(Dealer d)
		{
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			string why;
			Property val = ResolveBase(d, out why);
			if ((Object)(object)val == (Object)null)
			{
				Core.Log.Msg($"[trips] {((Object)d).name}: no trip ({why}). Working as normal.");
				return;
			}
			StorageEntity val2 = FindSafe(val);
			StorageEntity val3 = FindRestock(val);
			bool flag = (Object)(object)val2 != (Object)null && d.Cash >= 1f;
			bool flag2 = (Object)(object)val3 != (Object)null && WantsRestock(d, val3);
			if (!flag && !flag2)
			{
				string value = (((Object)(object)val2 == (Object)null) ? "no Safe" : "no cash to drop off");
				string value2 = (((Object)(object)val3 == (Object)null) ? "no 'Dealer Restock' storage" : "nothing to restock");
				Core.Log.Msg($"[trips] {((Object)d).name}: no trip to {val.PropertyName} ({value}, {value2}). Working as normal.");
				return;
			}
			Trip trip = new Trip
			{
				Dealer = d,
				Base = val,
				StartedAt = Time.unscaledTime
			};
			try
			{
				if ((Object)(object)val.NPCSpawnPoint != (Object)null)
				{
					trip.Stops.Add(new Stop
					{
						Kind = StopKind.Entrance,
						Target = Snap(val.NPCSpawnPoint.position)
					});
				}
			}
			catch
			{
			}
			if (flag)
			{
				trip.Stops.Add(new Stop
				{
					Kind = StopKind.Safe,
					Storage = val2,
					Target = WalkTargetFor(val2)
				});
			}
			if (flag2)
			{
				trip.Stops.Add(new Stop
				{
					Kind = StopKind.Restock,
					Storage = val3,
					Target = WalkTargetFor(val3)
				});
			}
			Active[((Object)d).name] = trip;
			try
			{
				NavMeshAgent agent = ((NPC)d).Movement._agent;
				if ((Object)(object)agent != (Object)null)
				{
					trip.OrigMask = agent.areaMask;
					agent.areaMask = -1;
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("[trips] " + ((Object)d).name + ": couldn't change walkable areas: " + ex.Message);
			}
			NPCBehaviour behaviour = ((NPC)d).Behaviour;
			if (behaviour != null)
			{
				NPCScheduleManager scheduleManager = behaviour.ScheduleManager;
				if (scheduleManager != null)
				{
					scheduleManager.DisableSchedule();
				}
			}
			if (((NPC)d).isInBuilding && (Object)(object)((NPC)d).CurrentBuilding != (Object)null)
			{
				((NPC)d).ExitBuilding(((NPC)d).CurrentBuilding);
			}
			else
			{
				trip.LeftBuilding = true;
				WalkTo(trip, trip.Stops[0].Target);
			}
			List<string> list = new List<string>();
			if (flag)
			{
				list.Add($"drop off ${d.Cash:N0}");
			}
			if (flag2)
			{
				list.Add("restock");
			}
			Core.Log.Msg($"[trips] {((Object)d).name}: heading to {val.PropertyName} to {string.Join(" and ", list)}.");
		}

		private unsafe static void WalkTo(Trip t, Vector3 pos)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			Action<WalkResult> val = DelegateSupport.ConvertDelegate<Action<WalkResult>>((Delegate)(Action<WalkResult>)delegate(WalkResult r)
			{
				t.LastResult = ((object)(*(WalkResult*)(&r))/*cast due to .constrained prefix*/).ToString();
			});
			t.LastResult = "";
			((NPC)t.Dealer).Movement.SetDestination(pos, val, true, 1.5f, 1f);
		}

		private static void ProgressTrips()
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			if (Active.Count == 0)
			{
				return;
			}
			foreach (string item in new List<string>(Active.Keys))
			{
				Trip trip = Active[item];
				Dealer dealer = trip.Dealer;
				try
				{
					if ((Object)(object)dealer == (Object)null)
					{
						Active.Remove(item);
						continue;
					}
					if (!((NPC)dealer).IsConscious)
					{
						EndTrip(trip, "knocked out");
						continue;
					}
					if ((Object)(object)dealer.currentContract != (Object)null)
					{
						EndTrip(trip, "started a deal");
						continue;
					}
					if (Time.unscaledTime - trip.StartedAt > 300f)
					{
						EndTrip(trip, "took too long");
						continue;
					}
					Stop stop = trip.Stops[trip.StopIndex];
					if (!trip.LeftBuilding)
					{
						if (!((NPC)dealer).isInBuilding)
						{
							trip.LeftBuilding = true;
							WalkTo(trip, stop.Target);
						}
						continue;
					}
					Vector3 val = PosOf(dealer);
					float num = Vector3.Distance(val, stop.Target);
					float num2 = (((Object)(object)stop.Storage != (Object)null) ? Vector3.Distance(val, ((Component)stop.Storage).transform.position) : 999f);
					if (num <= 2.5f || num2 <= 3.5f)
					{
						if (stop.Kind == StopKind.Safe)
						{
							DropOffCash(trip, stop.Storage);
						}
						else if (stop.Kind == StopKind.Restock)
						{
							Restock(trip, stop.Storage);
						}
						if (++trip.StopIndex >= trip.Stops.Count)
						{
							EndTrip(trip, null);
							continue;
						}
						trip.Retries = 0;
						WalkTo(trip, trip.Stops[trip.StopIndex].Target);
					}
					else if (!((NPC)dealer).Movement.IsMoving)
					{
						if (++trip.Retries > 6)
						{
							EndTrip(trip, $"got stuck {num:0}m from the {stop.Kind}, walk result '{trip.LastResult}'");
						}
						else
						{
							WalkTo(trip, stop.Target);
						}
					}
				}
				catch (Exception ex)
				{
					Core.Log.Error("[trips] " + item + ": " + ex.Message);
					EndTrip(trip, "error");
				}
			}
		}

		private static void RestoreMask(Trip t)
		{
			try
			{
				if (t.OrigMask != int.MinValue)
				{
					Dealer dealer = t.Dealer;
					object obj;
					if (dealer == null)
					{
						obj = null;
					}
					else
					{
						NPCMovement movement = ((NPC)dealer).Movement;
						obj = ((movement != null) ? movement._agent : null);
					}
					if ((Object)obj != (Object)null)
					{
						((NPC)t.Dealer).Movement._agent.areaMask = t.OrigMask;
					}
				}
			}
			catch
			{
			}
		}

		private static void EndTrip(Trip t, string problem)
		{
			Active.Remove(((Object)(object)t.Dealer != (Object)null) ? ((Object)t.Dealer).name : "");
			RestoreMask(t);
			try
			{
				Dealer dealer = t.Dealer;
				if (dealer != null)
				{
					NPCBehaviour behaviour = ((NPC)dealer).Behaviour;
					if (behaviour != null)
					{
						NPCScheduleManager scheduleManager = behaviour.ScheduleManager;
						if (scheduleManager != null)
						{
							scheduleManager.EnableSchedule();
						}
					}
				}
			}
			catch
			{
			}
			if (problem != null)
			{
				Instance log = Core.Log;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(44, 2);
				defaultInterpolatedStringHandler.AppendLiteral("[trips] ");
				Dealer dealer2 = t.Dealer;
				defaultInterpolatedStringHandler.AppendFormatted((dealer2 != null) ? ((Object)dealer2).name : null);
				defaultInterpolatedStringHandler.AppendLiteral(": trip cancelled (");
				defaultInterpolatedStringHandler.AppendFormatted(problem);
				defaultInterpolatedStringHandler.AppendLiteral("). Back to normal.");
				log.Msg(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			else
			{
				Instance log2 = Core.Log;
				Dealer dealer3 = t.Dealer;
				log2.Msg("[trips] " + ((dealer3 != null) ? ((Object)dealer3).name : null) + ": trip done, back to normal.");
			}
		}

		internal static void Reset()
		{
			foreach (Trip item in new List<Trip>(Active.Values))
			{
				RestoreMask(item);
				try
				{
					Dealer dealer = item.Dealer;
					if (dealer == null)
					{
						continue;
					}
					NPCBehaviour behaviour = ((NPC)dealer).Behaviour;
					if (behaviour != null)
					{
						NPCScheduleManager scheduleManager = behaviour.ScheduleManager;
						if (scheduleManager != null)
						{
							scheduleManager.EnableSchedule();
						}
					}
				}
				catch
				{
				}
			}
			Active.Clear();
		}

		internal static IEnumerator DescribeBases()
		{
			yield return (object)new WaitForSeconds(20f);
			try
			{
				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)
						{
							continue;
						}
						List<string> list = new List<string>();
						List<BuildableItem> buildableItems = val.BuildableItems;
						if (buildableItems != null)
						{
							for (int j = 0; j < buildableItems.Count; j++)
							{
								BuildableItem val2 = buildableItems[j];
								StorageEntity val3 = ((val2 != null) ? ((Component)val2).GetComponentInChildren<StorageEntity>() : null);
								if (!((Object)(object)val3 == (Object)null))
								{
									string text = "";
									try
									{
										PlaceableStorageEntity obj = ((Il2CppObjectBase)val2).TryCast<PlaceableStorageEntity>();
										text = ((obj != null) ? obj.Name : null) ?? "";
									}
									catch
									{
									}
									list.Add((string.IsNullOrEmpty(text) || text == val3.StorageEntityName) ? val3.StorageEntityName : (val3.StorageEntityName + " named '" + text + "'"));
								}
							}
						}
						string value = (((Object)(object)FindSafe(val) != (Object)null) ? "  << Safe" : "") + (((Object)(object)FindRestock(val) != (Object)null) ? "  << Dealer Restock" : "");
						Core.Log.Msg($"[bases] You own '{val.PropertyName}': storage = {((list.Count > 0) ? string.Join(", ", list) : "none")}{value}");
					}
				}
				List<Dealer> allPlayerDealers = Dealer.AllPlayerDealers;
				if (allPlayerDealers == null)
				{
					yield break;
				}
				for (int k = 0; k < allPlayerDealers.Count; k++)
				{
					Dealer val4 = allPlayerDealers[k];
					if (!((Object)(object)val4 == (Object)null) && val4.IsRecruited)
					{
						string why;
						Property val5 = ResolveBase(val4, out why);
						Core.Log.Msg($"[bases] {((Object)val4).name}: setting '{BaseSettingFor(val4)}' -> {(((Object)(object)val5 != (Object)null) ? val5.PropertyName : ("no base (" + why + ")"))}, carrying ${val4.Cash:N0}.");
					}
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("[bases] " + ex.Message);
			}
		}
	}
}