Decompiled source of Cartel Logistics v1.0.0

Mods/CartelLogistics.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.Json;
using CartelLogistics;
using HarmonyLib;
using Il2Cpp;
using Il2CppFishNet;
using Il2CppFishNet.Connection;
using Il2CppFishNet.Object;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppPathfinding;
using Il2CppScheduleOne;
using Il2CppScheduleOne.AvatarFramework.Equipping;
using Il2CppScheduleOne.Cartel;
using Il2CppScheduleOne.Clothing;
using Il2CppScheduleOne.Combat;
using Il2CppScheduleOne.Core.Avatar;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.Delivery;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dialogue;
using Il2CppScheduleOne.Doors;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.Equipping;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Levelling;
using Il2CppScheduleOne.Management;
using Il2CppScheduleOne.Management.UI;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.Math;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.NPCs.CharacterClasses;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.PlayerScripts.Health;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Management;
using Il2CppScheduleOne.Variables;
using Il2CppScheduleOne.Vehicles;
using Il2CppScheduleOne.Vehicles.AI;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using S1API.Cartel;
using S1API.Console;
using S1API.Entities;
using S1API.Entities.Equippables;
using S1API.Messaging;
using S1API.PhoneApp;
using S1API.UI;
using S1API.Utils;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(CartelLogisticsMod), "Cartel Logistics", "1.0.0", "HylandWorks", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("CartelLogistics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0d20dede6c2c916f88ab50313b673b3d986a9522")]
[assembly: AssemblyProduct("CartelLogistics")]
[assembly: AssemblyTitle("CartelLogistics")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[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 CartelLogistics
{
	internal sealed class AutoLaundering(Action<string> log)
	{
		private MoreBusinessBridge? _moreBusiness;

		private bool _lookedUpMoreBusiness;

		private float _nextCheck;

		public void Tick(Settings settings, Action<string> notify)
		{
			if (!settings.AutoLaunder || Time.time < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.time + 3f;
			foreach (Business item in World.Businesses())
			{
				IEnumerable<Stash> shelves = DriverRoutes.LabeledStashes((Property)(object)item, settings.DropoffLabel);
				if (Cargo.TryLaunderFullRun(item, shelves))
				{
					notify("Laundering started at " + ((Property)item).PropertyName + ".");
				}
			}
			try
			{
				if (!_lookedUpMoreBusiness)
				{
					_lookedUpMoreBusiness = true;
					_moreBusiness = MoreBusinessBridge.TryBind();
				}
				_moreBusiness?.Run(settings.DropoffLabel, notify);
			}
			catch (Exception ex)
			{
				_moreBusiness = null;
				log("More Business integration paused for this session. " + ex.GetBaseException().Message);
			}
		}
	}
	internal sealed class MoreBusinessBridge
	{
		private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private readonly FieldInfo _enabled;

		private readonly FieldInfo _saveKey;

		private readonly FieldInfo _days;

		private readonly FieldInfo _shops;

		private readonly FieldInfo _operations;

		private readonly FieldInfo _shopId;

		private readonly FieldInfo _name;

		private readonly FieldInfo _capacity;

		private readonly MethodInfo _owns;

		private readonly MethodInfo _laundering;

		private readonly FieldInfo _opShop;

		private readonly FieldInfo _opAmount;

		private readonly FieldInfo _opDue;

		private readonly FieldInfo _opStart;

		private readonly Type _opType;

		private readonly MethodInfo _currentDay;

		private MoreBusinessBridge(Type mod)
		{
			Type type = mod.GetNestedType("Shop", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingMemberException(mod.Name, "Shop");
			_opType = mod.GetNestedType("Op", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingMemberException(mod.Name, "Op");
			_enabled = RequireField(mod, "_enabled");
			_saveKey = RequireField(mod, "_saveKey");
			_days = RequireField(mod, "_launderDays");
			_shops = RequireField(mod, "Shops");
			_operations = RequireField(mod, "Ops");
			_shopId = RequireField(type, "Id");
			_name = RequireField(type, "Name");
			_capacity = RequireField(type, "Capacity");
			_owns = RequireMethod(mod, "IsOwned", typeof(bool), type);
			_laundering = RequireMethod(mod, "Laundering", typeof(float), type);
			_currentDay = RequireMethod(mod, "Today", typeof(int));
			_opShop = RequireField(_opType, "ShopId");
			_opAmount = RequireField(_opType, "Amount");
			_opDue = RequireField(_opType, "DueDay");
			_opStart = RequireField(_opType, "StartMin");
		}

		internal static MoreBusinessBridge? TryBind()
		{
			Type type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
				select assembly.GetType("MoreBusiness.Mod", throwOnError: false)).FirstOrDefault((Type type2) => type2 != null);
			if (!(type == null))
			{
				return new MoreBusinessBridge(type);
			}
			return null;
		}

		public void Run(string dropoff, Action<string> notify)
		{
			string fileName = Path.GetFileName(Singleton<LoadManager>.Instance.LoadedGameFolderPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
			if (!IsReady(fileName) || !(_shops.GetValue(null) is IEnumerable enumerable))
			{
				return;
			}
			Property[] source = World.Properties().ToArray();
			foreach (object shop in enumerable)
			{
				if ((bool)_owns.Invoke(null, new object[1] { shop }) && (float)_laundering.Invoke(null, new object[1] { shop }) == 0f)
				{
					string name = (string)_name.GetValue(shop);
					int capacity = ((MelonPreferences_Entry<int>)_capacity.GetValue(shop)).Value;
					IEnumerable<Stash> shelves = source.SelectMany((Property property) => DriverRoutes.LabeledStashes(property, dropoff + " / " + name));
					if (capacity > 0 && Cargo.TrySpendCash(shelves, capacity, delegate
					{
						AddOperation(shop, capacity);
					}))
					{
						notify("Laundering started at " + name + ".");
					}
				}
			}
		}

		internal bool IsReady(string saveKey)
		{
			if (_enabled.GetValue(null) is MelonPreferences_Entry<bool> val && val.Value && _saveKey.GetValue(null) is string text)
			{
				return text == saveKey;
			}
			return false;
		}

		private void AddOperation(object shop, float amount)
		{
			object obj = Activator.CreateInstance(_opType, nonPublic: true);
			int num = Math.Max(1, ((MelonPreferences_Entry<int>)_days.GetValue(null)).Value);
			_opShop.SetValue(obj, _shopId.GetValue(shop));
			_opAmount.SetValue(obj, amount);
			_opDue.SetValue(obj, (int)_currentDay.Invoke(null, null) + num);
			_opStart.SetValue(obj, World.Minute);
			((IList)_operations.GetValue(null)).Add(obj);
		}

		private static FieldInfo RequireField(Type type, string name)
		{
			return type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingMemberException(type.FullName, name);
		}

		private static MethodInfo RequireMethod(Type type, string name, Type returns, params Type[] arguments)
		{
			MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, arguments, null);
			if (!(method?.ReturnType == returns))
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return method;
		}
	}
	internal static class Cargo
	{
		private sealed record CashDebit(ItemSlot Slot, CashInstance Original, float Balance, float Remaining);

		public static bool Any(List<ItemSlot> slots)
		{
			Enumerator<ItemSlot> enumerator = slots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				if (enumerator.Current.ItemInstance != null)
				{
					return true;
				}
			}
			return false;
		}

		public static bool CanTake(ItemSlot slot)
		{
			if (slot.ItemInstance != null && !slot.IsLocked)
			{
				return !slot.IsRemovalLocked;
			}
			return false;
		}

		public static bool HasTransferable(List<ItemSlot> slots, bool cashOnly)
		{
			Enumerator<ItemSlot> enumerator = slots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (CanTake(current) && (!cashOnly || ((Il2CppObjectBase)current.ItemInstance).TryCast<CashInstance>() != null))
				{
					return true;
				}
			}
			return false;
		}

		public static bool CanTransfer(List<ItemSlot> source, List<ItemSlot> destination, bool cashOnly = false, Predicate<ItemInstance>? filter = null)
		{
			Enumerator<ItemSlot> enumerator = source.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (!CanTake(current))
				{
					continue;
				}
				ItemInstance itemInstance = current.ItemInstance;
				bool flag = ((Il2CppObjectBase)itemInstance).TryCast<CashInstance>() != null;
				if ((cashOnly && !flag) || (filter != null && !filter(itemInstance)))
				{
					continue;
				}
				Enumerator<ItemSlot> enumerator2 = destination.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ItemSlot current2 = enumerator2.Current;
					if (TransferQuantity(current, current2, itemInstance, flag) > 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		public static int Transfer(List<ItemSlot> source, List<ItemSlot> destination, bool cashOnly = false, Predicate<ItemInstance>? filter = null)
		{
			int num = 0;
			Enumerator<ItemSlot> enumerator = source.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (!CanTake(current))
				{
					continue;
				}
				Enumerator<ItemSlot> enumerator2 = destination.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ItemSlot current2 = enumerator2.Current;
					ItemInstance itemInstance = current.ItemInstance;
					if (itemInstance == null)
					{
						break;
					}
					bool flag = ((Il2CppObjectBase)itemInstance).TryCast<CashInstance>() != null;
					if ((cashOnly && !flag) || (filter != null && !filter(itemInstance)))
					{
						break;
					}
					int num2 = TransferQuantity(current, current2, itemInstance, flag);
					if (num2 <= 0)
					{
						continue;
					}
					ItemInstance itemInstance2 = current2.ItemInstance;
					ItemInstance val = ((itemInstance2 != null) ? Copy(itemInstance2, ((BaseItemInstance)itemInstance2).Quantity) : null);
					int quantity = current2.Quantity;
					current2.AddItem(Copy(itemInstance, num2), false);
					int num3 = current2.Quantity - quantity;
					if (num3 != num2)
					{
						if (num3 > 0)
						{
							current2.SetStoredItem(val, false);
						}
						continue;
					}
					int num4 = current.Quantity - num2;
					try
					{
						current.SetQuantity(num4, false);
					}
					finally
					{
						if (current.Quantity != num4)
						{
							current2.SetStoredItem(val, false);
						}
					}
					if (current.Quantity == num4)
					{
						num += num2;
					}
				}
			}
			return num;
		}

		private static int TransferQuantity(ItemSlot from, ItemSlot to, ItemInstance item, bool isCash)
		{
			if (((Il2CppObjectBase)from).Pointer == ((Il2CppObjectBase)to).Pointer || to.IsLocked || to.IsRemovalLocked || to.IsAddLocked || (isCash && to.ItemInstance != null))
			{
				return 0;
			}
			return Math.Min(((BaseItemInstance)item).Quantity, to.GetCapacityForItem(item, true));
		}

		private static ItemInstance Copy(ItemInstance item, int quantity)
		{
			ItemInstance copy = item.GetCopy(quantity);
			CashInstance val = ((Il2CppObjectBase)item).TryCast<CashInstance>();
			if (val != null)
			{
				((Il2CppObjectBase)copy).Cast<CashInstance>().SetBalance(val.Balance, true);
			}
			return copy;
		}

		private static bool IsPackagedProduct(ItemInstance item)
		{
			ProductItemInstance obj = ((Il2CppObjectBase)item).TryCast<ProductItemInstance>();
			return (Object)(object)((obj != null) ? obj.AppliedPackaging : null) != (Object)null;
		}

		public static bool CanSupplyDealer(List<ItemSlot> trunk, Dealer dealer)
		{
			return CanTransfer(trunk, ((NPC)dealer).Inventory.ItemSlots, cashOnly: false, IsPackagedProduct);
		}

		public static int SupplyDealer(List<ItemSlot> trunk, Dealer dealer)
		{
			int num = Transfer(trunk, ((NPC)dealer).Inventory.ItemSlots, cashOnly: false, IsPackagedProduct);
			if (num > 0)
			{
				((NPC)dealer).HasChanged = true;
			}
			return num;
		}

		public static bool CanCollectDealerCash(List<ItemSlot> trunk, Dealer dealer)
		{
			CashInstance cash;
			return FindCashDestination(trunk, dealer.Cash, out cash) != null;
		}

		public static bool CollectDealerCash(List<ItemSlot> trunk, Dealer dealer)
		{
			float cash = dealer.Cash;
			CashInstance cash2;
			ItemSlot val = FindCashDestination(trunk, cash, out cash2);
			if (val == null)
			{
				return false;
			}
			bool flag = false;
			bool flag2 = false;
			try
			{
				val.SetStoredItem((ItemInstance)(object)cash2, false);
				ItemInstance itemInstance = val.ItemInstance;
				if (itemInstance != null)
				{
					CashInstance obj = ((Il2CppObjectBase)itemInstance).TryCast<CashInstance>();
					if (((obj != null) ? new float?(obj.Balance) : ((float?)null)) == cash && dealer.Cash == cash)
					{
						flag2 = true;
						dealer.RpcLogic___SetCash_431000436(0f);
						flag = dealer.Cash == 0f;
						return flag;
					}
				}
				return false;
			}
			finally
			{
				if (!flag && (!flag2 || dealer.Cash != 0f))
				{
					val.ClearStoredInstance(false);
				}
			}
		}

		private static ItemSlot? FindCashDestination(List<ItemSlot> trunk, float balance, out CashInstance? cash)
		{
			cash = null;
			if (!float.IsFinite(balance) || balance <= 0f)
			{
				return null;
			}
			Enumerator<ItemSlot> enumerator = trunk.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (current.ItemInstance == null && !current.IsLocked && !current.IsRemovalLocked && !current.IsAddLocked)
				{
					if (cash == null)
					{
						cash = World.Money.GetCashInstance(balance);
					}
					if (current.GetCapacityForItem((ItemInstance)(object)cash, true) >= ((BaseItemInstance)cash).Quantity)
					{
						return current;
					}
				}
			}
			return null;
		}

		private static IEnumerable<(ItemSlot Slot, CashInstance Cash)> CashSlots(IEnumerable<Stash> shelves)
		{
			HashSet<nint> seen = new HashSet<IntPtr>();
			foreach (Stash shelf in shelves)
			{
				Enumerator<ItemSlot> enumerator2 = shelf.Storage.ItemSlots.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ItemSlot current2 = enumerator2.Current;
					if (seen.Add(((Il2CppObjectBase)current2).Pointer) && CanTake(current2))
					{
						ItemInstance itemInstance = current2.ItemInstance;
						CashInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<CashInstance>() : null);
						if (val != null && float.IsFinite(val.Balance) && val.Balance > 0f)
						{
							yield return (Slot: current2, Cash: val);
						}
					}
				}
			}
		}

		public static float CountCash(IEnumerable<Stash> shelves)
		{
			return CashSlots(shelves).Sum<(ItemSlot, CashInstance)>(((ItemSlot Slot, CashInstance Cash) entry) => entry.Cash.Balance);
		}

		public static bool TrySpendCash(IEnumerable<Stash> shelves, float amount, Action start)
		{
			return TrySpendCash(shelves, amount, delegate
			{
				start();
				return true;
			});
		}

		public static bool TrySpendCash(IEnumerable<Stash> shelves, float amount, Func<bool> start)
		{
			if (!float.IsFinite(amount) || amount <= 0f)
			{
				return false;
			}
			List<CashDebit> list = new List<CashDebit>();
			double num = Math.Round((double)amount * 100.0, MidpointRounding.AwayFromZero);
			if (num <= 0.0)
			{
				return false;
			}
			foreach (var item3 in CashSlots(shelves))
			{
				ItemSlot item = item3.Slot;
				CashInstance item2 = item3.Cash;
				float balance = item2.Balance;
				double num2 = Math.Round((double)balance * 100.0, MidpointRounding.AwayFromZero);
				double num3 = Math.Min(num2, num);
				if (!(num3 <= 0.0))
				{
					float remaining = (float)((num2 - num3) / 100.0);
					list.Add(new CashDebit(item, item2, balance, remaining));
					num -= num3;
					if (num <= 0.0)
					{
						break;
					}
				}
			}
			if (num > 0.0)
			{
				return false;
			}
			List<CashDebit> list2 = new List<CashDebit>();
			bool flag = false;
			try
			{
				foreach (CashDebit item4 in list)
				{
					ItemInstance itemInstance = item4.Slot.ItemInstance;
					IntPtr? intPtr = ((itemInstance != null) ? new IntPtr?(((Il2CppObjectBase)itemInstance).Pointer) : ((IntPtr?)null));
					IntPtr pointer = ((Il2CppObjectBase)item4.Original).Pointer;
					if (!intPtr.HasValue || intPtr.GetValueOrDefault() != pointer || item4.Original.Balance != item4.Balance || !CanTake(item4.Slot))
					{
						return false;
					}
					list2.Add(item4);
					if (item4.Remaining == 0f)
					{
						item4.Slot.ClearStoredInstance(false);
					}
					else
					{
						CashInstance val = ((Il2CppObjectBase)Copy((ItemInstance)(object)item4.Original, ((BaseItemInstance)item4.Original).Quantity)).Cast<CashInstance>();
						val.SetBalance(item4.Remaining, true);
						item4.Slot.SetStoredItem((ItemInstance)(object)val, false);
					}
					ItemInstance itemInstance2 = item4.Slot.ItemInstance;
					bool num4;
					if (item4.Remaining != 0f)
					{
						float? obj;
						if (itemInstance2 == null)
						{
							obj = null;
						}
						else
						{
							CashInstance obj2 = ((Il2CppObjectBase)itemInstance2).TryCast<CashInstance>();
							obj = ((obj2 != null) ? new float?(obj2.Balance) : ((float?)null));
						}
						num4 = obj != item4.Remaining;
					}
					else
					{
						num4 = itemInstance2 != null;
					}
					if (num4)
					{
						return false;
					}
				}
				flag = start();
				return flag;
			}
			finally
			{
				if (!flag)
				{
					foreach (CashDebit item5 in list2.AsEnumerable().Reverse())
					{
						item5.Slot.SetStoredItem((ItemInstance)(object)item5.Original, false);
					}
				}
			}
		}

		public static bool TryLaunderFullRun(Business business, IEnumerable<Stash> shelves)
		{
			if ((Object)(object)business == (Object)null || business.LaunderingOperations.Count != 0)
			{
				return false;
			}
			float amount = business.LaunderCapacity;
			if (!TrySpendCash(shelves, amount, delegate
			{
				if (business.LaunderingOperations.Count != 0)
				{
					return false;
				}
				try
				{
					business.RpcLogic___ReceiveLaunderingOperation_1001022388((NetworkConnection)null, amount, 0);
				}
				catch (Exception ex2) when (business.LaunderingOperations.Count != 0)
				{
					MelonLogger.Warning("A laundering job started before its callback failed. " + ex2.Message);
				}
				return business.LaunderingOperations.Count > 0;
			}))
			{
				return false;
			}
			Enumerator<int, NetworkConnection> enumerator = InstanceFinder.ServerManager.Clients.Values.GetEnumerator();
			while (enumerator.MoveNext())
			{
				NetworkConnection current = enumerator.Current;
				if (!current.IsHost)
				{
					try
					{
						business.ReceiveLaunderingOperation(current, amount, 0);
					}
					catch (Exception ex)
					{
						MelonLogger.Warning("Could not update a client about the new laundering job. " + ex.Message);
					}
				}
			}
			return true;
		}

		public static bool StealOne(List<ItemSlot> slots)
		{
			Enumerator<ItemSlot> enumerator = slots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (CanTake(current))
				{
					current.ClearStoredInstance(false);
					if (current.ItemInstance == null)
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	public sealed class CartelLogisticsMod : MelonMod
	{
		private string? _savePath;

		private float _nextTick;

		private string? _failedSavePath;

		private bool _saveListener;

		internal static Settings CurrentSettings { get; private set; }

		internal static Operations? CurrentOperations { get; private set; }

		public override void OnInitializeMelon()
		{
			CurrentSettings = new Settings();
			((MelonBase)this).LoggerInstance.Msg("Cartel Logistics is ready. Global settings are in the CartelLogistics phone app.");
		}

		public override void OnUpdate()
		{
			if (Time.unscaledTime < _nextTick)
			{
				return;
			}
			_nextTick = Time.unscaledTime + 0.5f;
			try
			{
				LogisticsPhoneApp.Active?.UpdateAuthority();
				LoadManager val = (Singleton<LoadManager>.InstanceExists ? Singleton<LoadManager>.Instance : null);
				if (!InstanceFinder.IsHost && val != null && val.IsGameLoaded && !val.IsLoading && (Object)(object)Player.Local != (Object)null)
				{
					LogisticsEmployeeRates.RefreshGuestRates();
				}
				if (!InstanceFinder.IsHost || (Object)(object)val == (Object)null || !val.IsGameLoaded || val.IsLoading || (Object)(object)Player.Local == (Object)null)
				{
					if (CurrentOperations != null)
					{
						EndSession();
					}
					_failedSavePath = null;
					return;
				}
				string loadedGameFolderPath = val.LoadedGameFolderPath;
				if (string.IsNullOrEmpty(loadedGameFolderPath) || _failedSavePath == loadedGameFolderPath)
				{
					return;
				}
				if (_savePath != loadedGameFolderPath)
				{
					EndSession();
					BeginSession(loadedGameFolderPath);
				}
				if (Singleton<SaveManager>.Instance.IsSaving)
				{
					return;
				}
				Operations currentOperations = CurrentOperations;
				if (currentOperations != null)
				{
					if (World.ActivePlayers().Any())
					{
						currentOperations.Tick();
					}
					else
					{
						currentOperations.TickIncident();
					}
				}
			}
			catch (Exception value)
			{
				((MelonBase)this).LoggerInstance.Error($"Cartel Logistics stopped for this session. {value}");
				_failedSavePath = _savePath ?? (Singleton<LoadManager>.InstanceExists ? Singleton<LoadManager>.Instance.LoadedGameFolderPath : null);
				EndSession();
			}
		}

		private void BeginSession(string path)
		{
			DriverRoutes.ResetCache();
			OperationsData operationsData = OperationsData.Load(path);
			_savePath = path;
			CurrentOperations = new Operations(operationsData, CurrentSettings, Notify, SendIncidentText, delegate(string message)
			{
				((MelonBase)this).LoggerInstance.Warning(message);
			});
			EventHelper.AddListener((Action)OnGameSaved, Singleton<SaveManager>.Instance.onSaveComplete);
			_saveListener = true;
			((MelonBase)this).LoggerInstance.Msg($"Loaded logistics for {Path.GetFileName(path)} with {operationsData.Routes.Count} routes.");
		}

		private void OnGameSaved()
		{
			if (_savePath == null || CurrentOperations == null || SaveManager.SaveError)
			{
				return;
			}
			try
			{
				CurrentOperations.Data.Save(_savePath);
			}
			catch (Exception value)
			{
				((MelonBase)this).LoggerInstance.Error($"Could not save the logistics routes. {value}");
				Notify("Could not save logistics routes. Check the MelonLoader log.");
			}
		}

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

		public override void OnDeinitializeMelon()
		{
			EndSession();
		}

		private void EndSession()
		{
			if (_saveListener && Singleton<SaveManager>.InstanceExists)
			{
				EventHelper.RemoveListener((Action)OnGameSaved, Singleton<SaveManager>.Instance.onSaveComplete);
			}
			_saveListener = false;
			Operations currentOperations = CurrentOperations;
			CurrentOperations = null;
			_savePath = null;
			try
			{
				currentOperations?.Stop();
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not release all logistics objects. " + ex.Message);
			}
			DriverRoutes.ResetCache();
		}

		private void Notify(string text)
		{
			((MelonBase)this).LoggerInstance.Msg(text);
			if (Singleton<NotificationsManager>.InstanceExists)
			{
				Singleton<NotificationsManager>.Instance.SendNotification("Cartel Logistics", text, (Sprite)null, 8f, true);
			}
		}

		private void SendIncidentText(string text)
		{
			((MelonBase)this).LoggerInstance.Msg(text);
			try
			{
				NPC val = NPC.Get("manny_oakfield");
				if (val == null)
				{
					((MelonBase)this).LoggerInstance.Warning("Manny is unavailable to send the cartel alert.");
				}
				else
				{
					val.Messaging.SendTextMessage(text, (Response[])null, 1f, true);
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not send the cartel text. " + ex.GetBaseException().Message);
			}
		}
	}
	internal static class DriverClipboard
	{
		[HarmonyPatch(typeof(PackagerConfigPanel), "BindInternal")]
		private static class HandlerPanel
		{
			private static void Postfix(PackagerConfigPanel __instance, List<EntityConfiguration> __0)
			{
				Bind(((Component)__instance).transform, __instance.BedUI, __instance.StationsUI.Button, __0, ((Component)__instance.StationsUI).gameObject, ((Component)__instance.RoutesUI).gameObject);
			}
		}

		[HarmonyPatch(typeof(CleanerConfigPanel), "BindInternal")]
		private static class CleanerPanel
		{
			private static void Postfix(CleanerConfigPanel __instance, List<EntityConfiguration> __0)
			{
				Bind(((Component)__instance).transform, __instance.BedUI, __instance.BinsUI.Button, __0, ((Component)__instance.BinsUI).gameObject);
			}
		}

		[HarmonyPatch(typeof(SelectionInfoUI), "Set")]
		private static class SelectionTitle
		{
			private static void Postfix(SelectionInfoUI __instance, List<IConfigurable> __0)
			{
				if (__0.Count == 1)
				{
					Employee val = FindEmployee(__0[0].Configuration);
					Role? role = GetRole(val);
					if (role.HasValue && (Object)(object)val != (Object)null)
					{
						((TMP_Text)__instance.Title).text = $"{((NPC)val).FullName} ({role})";
					}
				}
			}
		}

		[HarmonyPatch(typeof(ManagementWorldspaceCanvas), "UpdateInputPrompt")]
		private static class HoverPrompt
		{
			private static void Postfix(ManagementWorldspaceCanvas __instance)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				IConfigurable hoveredConfigurable = __instance.HoveredConfigurable;
				if (hoveredConfigurable != null && !(__instance._currentPromptMessage != "Manage " + ConfigurableType.GetTypeName(hoveredConfigurable.ConfigurableType)))
				{
					Role? role = GetRole(FindEmployee(hoveredConfigurable.Configuration));
					if (role.HasValue)
					{
						__instance.SetCrosshairPromptMessage($"Manage {role.Value}");
					}
				}
			}
		}

		private sealed class Editor
		{
			private sealed record Choice(string Label, Action Select);

			private const int MaxVisibleStops = 4;

			private readonly RectTransform _root;

			private readonly TextMeshProUGUI _font;

			private readonly Button _template;

			private readonly float _spacing;

			private readonly float _row;

			private readonly int _pageSize;

			private string _employeeId = "";

			private Role _role;

			private Operations _operations;

			private string _status = "";

			private int _routePage;

			private readonly List<GameObject> _children = new List<GameObject>();

			internal Editor(Transform panel, ObjectFieldUI home, Button template)
			{
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_023c: Unknown result type (might be due to invalid IL or missing references)
				//IL_024c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0263: Unknown result type (might be due to invalid IL or missing references)
				//IL_0279: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				Canvas.ForceUpdateCanvases();
				RectTransform val = ((Il2CppObjectBase)panel).Cast<RectTransform>();
				RectTransform val2 = ((Il2CppObjectBase)((Component)home).transform).Cast<RectTransform>();
				Rect rect = val2.rect;
				float num = float.PositiveInfinity;
				float num2 = float.NegativeInfinity;
				float num3 = float.PositiveInfinity;
				for (int i = 0; i < 4; i++)
				{
					float num4 = (((i & 1) == 0) ? ((Rect)(ref rect)).xMin : ((Rect)(ref rect)).xMax);
					float num5 = (((i & 2) == 0) ? ((Rect)(ref rect)).yMin : ((Rect)(ref rect)).yMax);
					Vector3 val3 = ((Transform)val).InverseTransformPoint(((Transform)val2).TransformPoint(new Vector3(num4, num5, 0f)));
					num = Math.Min(num, val3.x);
					num2 = Math.Max(num2, val3.x);
					num3 = Math.Min(num3, val3.y);
				}
				Rect rect2 = val.rect;
				_font = home.FieldLabel;
				_template = template;
				_spacing = Mathf.Clamp(((TMP_Text)_font).fontSize * 0.35f, 4f, 10f);
				float num6 = Mathf.Clamp(((Rect)(ref rect2)).yMax - num3 + _spacing, 0f, ((Rect)(ref rect2)).height * 0.5f);
				float num7 = Mathf.Clamp(num - ((Rect)(ref rect2)).xMin, 0f, ((Rect)(ref rect2)).width * 0.15f);
				float num8 = Mathf.Clamp(((Rect)(ref rect2)).xMax - num2, 0f, ((Rect)(ref rect2)).width * 0.15f);
				_row = Mathf.Min(Mathf.Clamp(((TMP_Text)_font).fontSize * 1.65f, 22f, 44f), Mathf.Max(18f, (((Rect)(ref rect2)).height - num6) / 7f));
				_pageSize = Mathf.Clamp(Mathf.FloorToInt((((Rect)(ref rect2)).height - num6 - _row * 5f) / _row), 1, 4);
				_root = CreateRect(panel, "CartelLogistics.Clipboard");
				((Component)_root).gameObject.AddComponent<LayoutElement>().ignoreLayout = true;
				_root.anchorMin = Vector2.zero;
				_root.anchorMax = Vector2.one;
				_root.offsetMin = new Vector2(num7, 0f);
				_root.offsetMax = new Vector2(0f - num8, 0f - num6);
			}

			internal void Open(string employeeId, Role role, Operations operations)
			{
				_employeeId = employeeId;
				_role = role;
				_operations = operations;
				ShowAssignments();
			}

			internal void Message(string message)
			{
				Label(message, 0, 0f, 1f);
			}

			private void ShowAssignments()
			{
				if (_role == Role.Driver)
				{
					ShowRoute();
				}
				else
				{
					ShowSoldier();
				}
			}

			private void ShowRoute()
			{
				BeginPage();
				Route route = _operations.FindDriverRoute(_employeeId);
				LandVehicle val = ((route == null) ? null : World.FindVan(route.VanId));
				DriverStop[] array = route?.Stops.ToArray() ?? Array.Empty<DriverStop>();
				Label("Vehicle", 0, 0f, 0.24f);
				AddButton(((Object)(object)val == (Object)null) ? "Choose vehicle" : VehicleDisplayName(val), 0, 0.25f, 1f, delegate
				{
					ChooseVehicle(0);
				});
				Label("Route stops", 1, 0f, 0.53f);
				AddButton("Add stop", 1, 0.55f, 1f, delegate
				{
					ChooseStop(0);
				});
				_routePage = ClampPage(_routePage, array.Length);
				int num = _routePage * _pageSize;
				int num2 = Math.Min(_pageSize, array.Length - num);
				if (num2 == 0)
				{
					Label("Choose a property, business, or recruited dealer.", 2, 0f, 1f);
				}
				for (int num3 = 0; num3 < num2; num3++)
				{
					int index = num + num3;
					int row = num3 + 2;
					string value = DriverRoutes.Resolve(array[index])?.Label ?? "Unavailable stop";
					AddButton($"{index + 1}. {value}", row, 0f, 1f, delegate
					{
						ShowStopActions(index);
					}, enabled: true, leftAligned: true);
				}
				int row2 = 2 + Math.Max(1, num2);
				if (array.Length > _pageSize)
				{
					AddPagination(row2++, _routePage, array.Length, delegate(int page)
					{
						_routePage = page;
						ShowRoute();
					});
				}
				string text = ((_status.Length > 0) ? _status : ((route != null) ? _operations.Status(route) : ""));
				if (text.Length > 0)
				{
					Label(text, row2, 0f, 1f);
				}
			}

			private void ShowStopActions(int index)
			{
				List<DriverStop> list = CurrentStops();
				if ((uint)index >= (uint)list.Count)
				{
					ShowRoute();
					return;
				}
				BeginPage();
				Label($"Route stop {index + 1}", 0, 0f, 0.69f);
				AddButton("Back", 0, 0.71f, 1f, ShowRoute);
				Label(DriverRoutes.Resolve(list[index])?.Label ?? "Unavailable stop", 1, 0f, 1f);
				AddButton("Move up", 2, 0f, 0.48f, delegate
				{
					MoveStop(index, -1);
				}, index > 0);
				AddButton("Move down", 2, 0.52f, 1f, delegate
				{
					MoveStop(index, 1);
				}, index < list.Count - 1);
				AddButton("Remove stop", 3, 0f, 1f, delegate
				{
					RemoveStop(index);
				});
			}

			private void ShowSoldier()
			{
				BeginPage();
				SoldierAssignment assignment = _operations.FindSoldierAssignment(_employeeId);
				Employee? obj = World.FindStaff(_employeeId, Role.Soldier);
				Property val = ((obj != null) ? obj.AssignedProperty : null);
				Employee val2 = (((Object)(object)val == (Object)null) ? null : GuardTargets(val).FirstOrDefault((Func<Employee, bool>)((Employee employee) => ((NPC)employee).ID == assignment?.TargetId)));
				Stash stash = (((Object)(object)val == (Object)null) ? null : World.Stashes(val).FirstOrDefault((Stash stash2) => stash2.Id == assignment?.RackId));
				Label("Duty", 0, 0f, 0.35f);
				AddButton((!((Object)(object)val2 == (Object)null)) ? ("Guard " + ((NPC)val2).FullName) : ((assignment?.TargetId == null) ? "Patrol property" : "Employee unavailable"), 0, 0.36f, 1f, delegate
				{
					ChooseDuty(0);
				});
				Label("Equipment rack", 1, 0f, 0.35f);
				AddButton((!(stash == null)) ? RackName(stash) : ((assignment?.RackId == null) ? "Choose storage" : "Rack unavailable"), 1, 0.36f, 1f, delegate
				{
					ChooseRack(0);
				});
				Label((_status.Length > 0) ? _status : "Stock a melee weapon, firearm, and matching ammo.", 2, 0f, 1f);
			}

			private void ChooseDuty(int page)
			{
				Employee? obj = World.FindStaff(_employeeId, Role.Soldier);
				Property val = ((obj != null) ? obj.AssignedProperty : null);
				Choice[] choices = (from employee in (IEnumerable<Employee>)(((Object)(object)val == (Object)null) ? ((IEnumerable)Enumerable.Empty<Employee>()) : ((IEnumerable)GuardTargets(val)))
					orderby ((NPC)employee).FullName
					select new Choice("Guard " + ((NPC)employee).FullName, delegate
					{
						AssignDuty(((NPC)employee).ID);
					})).Prepend(new Choice("Patrol property", delegate
				{
					AssignDuty(null);
				})).ToArray();
				ShowChoices("Choose a duty", choices, page, ChooseDuty);
			}

			private void ChooseRack(int page)
			{
				Employee? obj = World.FindStaff(_employeeId, Role.Soldier);
				Property val = ((obj != null) ? obj.AssignedProperty : null);
				Choice[] choices = (from stash in (((Object)(object)val == (Object)null) ? Enumerable.Empty<Stash>() : World.Stashes(val)).OrderBy(RackName)
					select new Choice(RackName(stash), delegate
					{
						AssignRack(stash.Id);
					})).Prepend(new Choice("Unassign rack", delegate
				{
					AssignRack(null);
				})).ToArray();
				ShowChoices("Choose an equipment rack", choices, page, ChooseRack);
			}

			private IEnumerable<Employee> GuardTargets(Property property)
			{
				Enumerator<Employee> enumerator = property.Employees.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Employee current = enumerator.Current;
					if (World.Available(current) && (Object)(object)current.AssignedProperty == (Object)(object)property && ((NPC)current).ID != _employeeId)
					{
						yield return current;
					}
				}
			}

			private static string RackName(Stash stash)
			{
				return stash.Storage.StorageEntityName + " [" + stash.Id.Substring(0, Math.Min(stash.Id.Length, 6)) + "]";
			}

			private void AssignDuty(string? target)
			{
				Change(() => _operations.ConfigureSoldier(_employeeId, target, _operations.FindSoldierAssignment(_employeeId)?.RackId));
			}

			private void AssignRack(string? rack)
			{
				Change(() => _operations.ConfigureSoldier(_employeeId, _operations.FindSoldierAssignment(_employeeId)?.TargetId, rack));
			}

			private void ChooseVehicle(int page)
			{
				Choice[] choices = (from vehicle in (from vehicle in World.Vans()
						where (Object)(object)vehicle != (Object)null
						select vehicle).OrderBy(VehicleName)
					select new Choice(VehicleName(vehicle), delegate
					{
						//IL_000c: Unknown result type (might be due to invalid IL or missing references)
						//IL_0011: Unknown result type (might be due to invalid IL or missing references)
						Apply(((object)vehicle.GUID/*cast due to .constrained prefix*/).ToString());
					})).Prepend(new Choice("Unassign vehicle", delegate
				{
					Apply(null);
				})).ToArray();
				ShowChoices("Choose vehicle", choices, page, ChooseVehicle);
			}

			private void ChooseStop(int page)
			{
				Choice[] choices = (from option in DriverRoutes.AvailableStops()
					orderby option.Label
					select new Choice(option.Label, delegate
					{
						AddStop(option.Stop);
					})).ToArray();
				ShowChoices("Choose a parking stop", choices, page, ChooseStop);
			}

			private void ShowChoices(string title, Choice[] choices, int page, Action<int> turnPage)
			{
				BeginPage();
				Label(title, 0, 0f, 0.69f);
				AddButton("Back", 0, 0.71f, 1f, ShowAssignments);
				page = ClampPage(page, choices.Length);
				int num = page * _pageSize;
				int num2 = Math.Min(_pageSize, choices.Length - num);
				if (num2 == 0)
				{
					Label("No matching assignments available.", 1, 0f, 1f);
				}
				for (int i = 0; i < num2; i++)
				{
					Choice choice = choices[num + i];
					AddButton(choice.Label, i + 1, 0f, 1f, choice.Select);
				}
				if (choices.Length > _pageSize)
				{
					AddPagination(num2 + 1, page, choices.Length, turnPage);
				}
			}

			private void AddPagination(int row, int page, int count, Action<int> change)
			{
				int num = ClampPage(int.MaxValue, count);
				AddButton("Previous", row, 0f, 0.3f, delegate
				{
					change(page - 1);
				}, page > 0);
				Label($"{page + 1} / {num + 1}", row, 0.38f, 0.65f);
				AddButton("Next", row, 0.7f, 1f, delegate
				{
					change(page + 1);
				}, page < num);
			}

			private int ClampPage(int page, int count)
			{
				return Math.Clamp(page, 0, Math.Max(0, (count - 1) / _pageSize));
			}

			private void AddStop(DriverStop stop)
			{
				List<DriverStop> list = CurrentStops();
				list.Add(stop);
				_routePage = (list.Count - 1) / _pageSize;
				ApplyStops(list);
			}

			private void MoveStop(int index, int amount)
			{
				List<DriverStop> list = CurrentStops();
				int num = index + amount;
				if ((uint)index < (uint)list.Count && (uint)num < (uint)list.Count)
				{
					List<DriverStop> list2 = list;
					int index2 = num;
					DriverStop value = list[num];
					DriverStop value2 = list[index];
					list2[index] = value;
					list[index2] = value2;
					_routePage = num / _pageSize;
					ApplyStops(list);
				}
			}

			private void RemoveStop(int index)
			{
				List<DriverStop> list = CurrentStops();
				if ((uint)index < (uint)list.Count)
				{
					list.RemoveAt(index);
					ApplyStops(list);
				}
			}

			private List<DriverStop> CurrentStops()
			{
				return _operations.FindDriverRoute(_employeeId)?.Stops.ToList() ?? new List<DriverStop>();
			}

			private void Apply(string? vehicle)
			{
				Change(() => _operations.ConfigureRoute(_employeeId, vehicle, CurrentStops()));
			}

			private void ApplyStops(List<DriverStop> stops)
			{
				Change(() => _operations.ConfigureRoute(_employeeId, _operations.FindDriverRoute(_employeeId)?.VanId, stops));
			}

			private void Change(Func<string> apply)
			{
				if (CartelLogisticsMod.CurrentOperations == _operations)
				{
					_status = apply();
					ShowAssignments();
				}
			}

			private static string VehicleName(LandVehicle van)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				string text = ((object)van.GUID/*cast due to .constrained prefix*/).ToString();
				string text2 = VehicleDisplayName(van);
				Player local = Player.Local;
				if (!((Object)(object)local == (Object)null))
				{
					return $"{text2} [{text.Substring(0, Math.Min(text.Length, 6))}] ({Vector3.Distance(((Component)local).transform.position, ((Component)van).transform.position):0} m)";
				}
				return text2 + " [" + text.Substring(0, Math.Min(text.Length, 6)) + "]";
			}

			private static string VehicleDisplayName(LandVehicle van)
			{
				if (!string.IsNullOrWhiteSpace(van.VehicleName))
				{
					return van.VehicleName;
				}
				return van.VehicleCode;
			}

			private void BeginPage()
			{
				foreach (GameObject child in _children)
				{
					child.SetActive(false);
					Object.Destroy((Object)(object)child);
				}
				_children.Clear();
			}

			private void Label(string value, int row, float left, float right)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				RectTransform rect = RowRect("Label", row, left, right);
				StyleLabel(rect, value, ((Graphic)_font).color, (TextAlignmentOptions)4097);
			}

			private void AddButton(string value, int row, float left, float right, Action action, bool enabled = true, bool leftAligned = false)
			{
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0115: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0151: Unknown result type (might be due to invalid IL or missing references)
				RectTransform obj = RowRect("Button", row, left, right);
				Image val = ((Component)obj).gameObject.AddComponent<Image>();
				Graphic targetGraphic = ((Selectable)_template).targetGraphic;
				Image val2 = ((targetGraphic != null) ? ((Il2CppObjectBase)targetGraphic).TryCast<Image>() : null);
				if ((Object)(object)val2 != (Object)null && ((Graphic)val2).color.a >= 0.1f)
				{
					val.sprite = val2.sprite;
					val.type = val2.type;
					((Graphic)val).color = ((Graphic)val2).color;
				}
				else
				{
					Color color = ((Graphic)_font).color;
					color.a = 0.14f;
					((Graphic)val).color = color;
				}
				Button obj2 = ((Component)obj).gameObject.AddComponent<Button>();
				((Selectable)obj2).targetGraphic = (Graphic)(object)val;
				((Selectable)obj2).colors = ((Selectable)_template).colors;
				((Selectable)obj2).interactable = enabled;
				((UnityEvent)obj2.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
				{
					try
					{
						action();
					}
					catch (Exception value2)
					{
						MelonLogger.Error($"Could not update the logistics clipboard. {value2}");
					}
				}));
				RectTransform val3 = CreateRect((Transform)(object)obj, "Caption");
				val3.anchorMin = Vector2.zero;
				val3.anchorMax = Vector2.one;
				val3.offsetMin = new Vector2(8f, 2f);
				val3.offsetMax = new Vector2(-8f, -2f);
				TextMeshProUGUI componentInChildren = ((Component)_template).GetComponentInChildren<TextMeshProUGUI>(true);
				StyleLabel(val3, value, ((Object)(object)componentInChildren == (Object)null) ? ((Graphic)_font).color : ((Graphic)componentInChildren).color, (TextAlignmentOptions)(leftAligned ? 4097 : 514));
			}

			private void StyleLabel(RectTransform rect, string value, Color color, TextAlignmentOptions alignment)
			{
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				TextMeshProUGUI obj = ((Component)rect).gameObject.AddComponent<TextMeshProUGUI>();
				((TMP_Text)obj).font = ((TMP_Text)_font).font;
				((TMP_Text)obj).fontSharedMaterial = ((TMP_Text)_font).fontSharedMaterial;
				float num = (((TMP_Text)obj).fontSize = Mathf.Min(((TMP_Text)_font).fontSize, _row * 0.65f));
				((TMP_Text)obj).fontSizeMin = num * 0.6f;
				((TMP_Text)obj).fontSizeMax = num;
				((TMP_Text)obj).enableAutoSizing = true;
				((Graphic)obj).color = color;
				((TMP_Text)obj).alignment = alignment;
				((TMP_Text)obj).overflowMode = (TextOverflowModes)3;
				((TMP_Text)obj).richText = false;
				((Graphic)obj).raycastTarget = false;
				((TMP_Text)obj).text = value;
			}

			private RectTransform RowRect(string name, int row, float left, float right)
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				RectTransform val = CreateRect((Transform)(object)_root, name);
				_children.Add(((Component)val).gameObject);
				val.anchorMin = new Vector2(left, 1f);
				val.anchorMax = new Vector2(right, 1f);
				val.offsetMin = new Vector2(0f, (float)(-(row + 1)) * _row + _spacing);
				val.offsetMax = new Vector2(0f, (float)(-row) * _row);
				return val;
			}

			private static RectTransform CreateRect(Transform parent, string name)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				RectTransform obj = ((Il2CppObjectBase)new GameObject(name, (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() }).transform).Cast<RectTransform>();
				((Transform)obj).SetParent(parent, false);
				return obj;
			}
		}

		internal const string ContentName = "CartelLogistics.Clipboard";

		internal static string RunDiagnostic()
		{
			Employee val = World.Staff(Role.Driver).FirstOrDefault();
			Employee val2 = World.Staff(Role.Soldier).FirstOrDefault();
			if ((Object)(object)val == (Object)null && (Object)(object)val2 == (Object)null)
			{
				return "Clipboard check skipped. Hire a Driver or Soldier first.";
			}
			ManagementInterface val3 = (ManagementInterface)(Singleton<ManagementInterface>.InstanceExists ? ((object)Singleton<ManagementInterface>.Instance) : ((object)((IEnumerable<ManagementInterface>)Resources.FindObjectsOfTypeAll<ManagementInterface>()).FirstOrDefault((Func<ManagementInterface, bool>)delegate(ManagementInterface instance)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)instance != (Object)null)
				{
					Scene scene = ((Component)instance).gameObject.scene;
					return ((Scene)(ref scene)).IsValid();
				}
				return false;
			})));
			if ((Object)(object)val3 == (Object)null)
			{
				return "Clipboard check failed. The native management interface is unavailable.";
			}
			List<string> list = new List<string>();
			if ((Object)(object)val != (Object)null)
			{
				string text = CheckPanel(val3, val, Role.Driver);
				if (text != null)
				{
					return "Clipboard check failed. " + text;
				}
				list.Add("Driver vehicle and parking pickers");
			}
			if ((Object)(object)val2 != (Object)null)
			{
				string text2 = CheckPanel(val3, val2, Role.Soldier);
				if (text2 != null)
				{
					return "Clipboard check failed. " + text2;
				}
				list.Add("Soldier duty and equipment rack pickers");
			}
			return "Clipboard check passed. Native " + string.Join(" and ", list) + " responded.";
		}

		private static string? CheckPanel(ManagementInterface menu, Employee worker, Role role)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			IConfigurable val = ((Il2CppObjectBase)worker).TryCast<IConfigurable>();
			if (((val != null) ? val.Configuration : null) != null)
			{
				ConfigPanel configPanelPrefab = menu.GetConfigPanelPrefab(val.ConfigurableType);
				if (configPanelPrefab != null)
				{
					ConfigPanel val2 = Object.Instantiate<ConfigPanel>(configPanelPrefab, (Transform)(object)menu.PanelContainer);
					CanvasGroup obj = ((Component)val2).gameObject.GetComponent<CanvasGroup>() ?? ((Component)val2).gameObject.AddComponent<CanvasGroup>();
					obj.alpha = 0f;
					obj.blocksRaycasts = false;
					try
					{
						List<EntityConfiguration> val3 = new List<EntityConfiguration>();
						val3.Add(val.Configuration);
						val2.BindInternal(val3);
						Transform val4 = ((Component)val2).transform.Find("CartelLogistics.Clipboard");
						if ((Object)(object)val4 == (Object)null)
						{
							return $"{role} controls were not mounted.";
						}
						Il2CppArrayBase<Button> componentsInChildren = ((Component)val4).GetComponentsInChildren<Button>(true);
						if (componentsInChildren.Length < 2)
						{
							return $"{role} assignment controls were not built.";
						}
						(string, string) tuple = ((role == Role.Driver) ? ("Choose vehicle", "Choose a parking stop") : ("Choose a duty", "Choose an equipment rack"));
						((UnityEvent)componentsInChildren[0].onClick).Invoke();
						if (!HasVisibleLabel(val4, tuple.Item1))
						{
							return $"The {role}’s first picker did not open.";
						}
						if (!ClickCaption(val4, "Back"))
						{
							return $"The {role}’s picker did not return to the clipboard.";
						}
						Button[] array = ((IEnumerable<Button>)((Component)val4).GetComponentsInChildren<Button>(true)).Where((Button button) => ((Component)button).gameObject.activeSelf).ToArray();
						if (array.Length < 2)
						{
							return $"The {role}’s clipboard did not restore its controls.";
						}
						((UnityEvent)array[1].onClick).Invoke();
						return HasVisibleLabel(val4, tuple.Item2) ? null : $"The {role}’s second picker did not open.";
					}
					finally
					{
						((Component)val2).gameObject.SetActive(false);
						Object.Destroy((Object)(object)((Component)val2).gameObject);
					}
				}
			}
			return $"The {role} has no native configuration panel.";
		}

		private static bool HasVisibleLabel(Transform editor, string caption)
		{
			return ((IEnumerable<TextMeshProUGUI>)((Component)editor).GetComponentsInChildren<TextMeshProUGUI>(true)).Any((TextMeshProUGUI label) => ((Component)label).gameObject.activeSelf && ((Component)((TMP_Text)label).transform.parent).gameObject.activeSelf && ((TMP_Text)label).text == caption);
		}

		private static bool ClickCaption(Transform editor, string caption)
		{
			foreach (Button componentsInChild in ((Component)editor).GetComponentsInChildren<Button>(true))
			{
				if (((Component)componentsInChild).gameObject.activeSelf)
				{
					TextMeshProUGUI componentInChildren = ((Component)componentsInChild).GetComponentInChildren<TextMeshProUGUI>(true);
					if (!(((componentInChildren != null) ? ((TMP_Text)componentInChildren).text : null) != caption))
					{
						((UnityEvent)componentsInChild.onClick).Invoke();
						return true;
					}
				}
			}
			return false;
		}

		private static Employee? FindEmployee(EntityConfiguration? configuration)
		{
			object obj;
			if (configuration == null)
			{
				obj = null;
			}
			else
			{
				PackagerConfiguration obj2 = ((Il2CppObjectBase)configuration).TryCast<PackagerConfiguration>();
				obj = ((obj2 != null) ? obj2.packager : null);
			}
			if (obj == null)
			{
				if (configuration == null)
				{
					return null;
				}
				CleanerConfiguration obj3 = ((Il2CppObjectBase)configuration).TryCast<CleanerConfiguration>();
				if (obj3 == null)
				{
					return null;
				}
				obj = obj3.cleaner;
			}
			return (Employee?)obj;
		}

		private static Role? GetRole(Employee? employee)
		{
			if ((Object)(object)employee == (Object)null)
			{
				return null;
			}
			if (World.IsRole(((NPC)employee).ID, Role.Driver))
			{
				return Role.Driver;
			}
			if (!World.IsRole(((NPC)employee).ID, Role.Soldier))
			{
				return null;
			}
			return Role.Soldier;
		}

		private static void Bind(Transform panel, ObjectFieldUI home, Button template, List<EntityConfiguration> configs, params GameObject[] nativeTaskFields)
		{
			Transform val = panel.Find("CartelLogistics.Clipboard");
			if ((Object)(object)val != (Object)null)
			{
				((Component)val).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
			Employee val2 = ((configs.Count == 1) ? FindEmployee(configs[0]) : null);
			Role? role = GetRole(val2);
			bool flag = role.HasValue;
			if (configs.Count > 1)
			{
				Enumerator<EntityConfiguration> enumerator = configs.GetEnumerator();
				while (enumerator.MoveNext())
				{
					EntityConfiguration current = enumerator.Current;
					flag |= GetRole(FindEmployee(current)).HasValue;
				}
			}
			if (!flag && (Object)(object)val == (Object)null)
			{
				return;
			}
			foreach (GameObject val3 in nativeTaskFields)
			{
				CanvasGroup val4 = val3.GetComponent<CanvasGroup>();
				if (flag && (Object)(object)val4 == (Object)null)
				{
					val4 = val3.AddComponent<CanvasGroup>();
				}
				if ((Object)(object)val4 != (Object)null)
				{
					val4.alpha = ((!flag) ? 1 : 0);
					val4.interactable = !flag;
					val4.blocksRaycasts = !flag;
				}
			}
			if (!flag)
			{
				return;
			}
			try
			{
				Editor editor = new Editor(panel, home, template);
				if (role.HasValue && (Object)(object)val2 != (Object)null)
				{
					Operations currentOperations = CartelLogisticsMod.CurrentOperations;
					if (currentOperations != null)
					{
						editor.Open(((NPC)val2).ID, role.Value, currentOperations);
						return;
					}
				}
				if (role.HasValue)
				{
					editor.Message("The host manages this employee’s assignments.");
				}
				else
				{
					editor.Message("Select one employee to edit their assignments.");
				}
			}
			catch (Exception value)
			{
				MelonLogger.Error($"Could not open the logistics clipboard. {value}");
			}
		}
	}
	internal static class ConvoyRoadRecovery
	{
		private const float MaximumMove = 27f;

		public static bool TryFindClearPose(LandVehicle van, Vector3[] path, out Pose pose)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//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_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: 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_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			pose = default(Pose);
			BoxCollider boundingBox = van.boundingBox;
			if (path.Length < 2 || (Object)(object)boundingBox == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)van).transform.position;
			float num = float.MaxValue;
			int num2 = 0;
			Vector3 val = path[0];
			Vector3 val4;
			for (int i = 0; i < path.Length - 1; i++)
			{
				Vector3 val2 = path[i + 1] - path[i];
				if (!(((Vector3)(ref val2)).sqrMagnitude < 0.01f))
				{
					Vector3 val3 = path[i] + val2 * Mathf.Clamp01(Vector3.Dot(position - path[i], val2) / ((Vector3)(ref val2)).sqrMagnitude);
					val4 = position - val3;
					float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude;
					if (sqrMagnitude < num)
					{
						num = sqrMagnitude;
						val = val3;
						num2 = i;
					}
				}
			}
			if (num > 49f)
			{
				return false;
			}
			Vector3 half = Vector3.Scale(boundingBox.size * 0.5f, ((Component)boundingBox).transform.lossyScale);
			Vector3 center = Quaternion.Inverse(((Component)van).transform.rotation) * (((Component)boundingBox).transform.TransformPoint(boundingBox.center) - position);
			float num3 = 0f;
			float num4 = 7f;
			for (int j = num2; j < path.Length - 1; j++)
			{
				if (!(num4 <= 27f))
				{
					break;
				}
				Vector3 val5 = path[j + 1];
				Vector3 val6 = val5 - val;
				float magnitude = ((Vector3)(ref val6)).magnitude;
				val4 = new Vector3(val6.x, 0f, val6.z);
				Vector3 normalized = ((Vector3)(ref val4)).normalized;
				while (((Vector3)(ref normalized)).sqrMagnitude > 0.5f && num4 <= Mathf.Min(27f, num3 + magnitude))
				{
					Vector3 val7 = val + val6 * ((num4 - num3) / magnitude);
					num4 += 3f;
					val4 = val7 - position;
					float sqrMagnitude2 = ((Vector3)(ref val4)).sqrMagnitude;
					if (sqrMagnitude2 >= 36f && sqrMagnitude2 <= 729f && TryPlace(van, val7, normalized, center, half, out pose))
					{
						return true;
					}
				}
				num3 += magnitude;
				num4 = Mathf.Max(num4, num3);
				val = val5;
			}
			return false;
		}

		private static bool TryPlace(LandVehicle van, Vector3 sample, Vector3 forward, Vector3 center, Vector3 half, out Pose pose)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: 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)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			pose = default(Pose);
			Vector3 val = forward * Mathf.Max(0.5f, half.z * 0.65f);
			if (!TryGround(sample, out var hit) || !TryGround(sample + val, out var hit2) || !TryGround(sample - val, out var hit3) || Mathf.Abs(((RaycastHit)(ref hit2)).point.y - ((RaycastHit)(ref hit3)).point.y) > 0.85f)
			{
				return false;
			}
			Quaternion val2 = Quaternion.LookRotation(Vector3.ProjectOnPlane(forward, ((RaycastHit)(ref hit)).normal), ((RaycastHit)(ref hit)).normal);
			float num = Mathf.Clamp(half.y - center.y, 0.25f, 0.85f);
			Vector3 position = ((RaycastHit)(ref hit)).point + ((RaycastHit)(ref hit)).normal * num;
			Vector3 val3 = position + val2 * (center + Vector3.up * 0.2f);
			Vector3 val4 = default(Vector3);
			((Vector3)(ref val4))..ctor(half.x + 0.25f, half.y, half.z + 0.4f);
			foreach (Collider item in (Il2CppArrayBase<Collider>)(object)Physics.OverlapBox(val3, val4, val2, -5, (QueryTriggerInteraction)1))
			{
				if ((Object)(object)item != (Object)null && !((Component)item).transform.IsChildOf(((Component)van).transform))
				{
					return false;
				}
			}
			float playerClearance = Mathf.Max(half.x, half.z) + 1.5f;
			if (World.ActivePlayers().Any(delegate(Player player)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				Vector3 val5 = ((Component)player).transform.position - position;
				return ((Vector3)(ref val5)).sqrMagnitude < playerClearance * playerClearance;
			}))
			{
				return false;
			}
			pose = new Pose(position, val2);
			return true;
		}

		private static bool TryGround(Vector3 point, out RaycastHit hit)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: 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_0010: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			if (Physics.Raycast(point + Vector3.up * 1.15f, Vector3.down, ref hit, 2.3f, -5, (QueryTriggerInteraction)1))
			{
				return ((RaycastHit)(ref hit)).normal.y >= 0.88f;
			}
			return false;
		}
	}
	internal sealed class Convoy
	{
		private const float StalledSeconds = 14f;

		private const float CalculationTimeout = 18f;

		private const int MaxRelocations = 3;

		internal static readonly HashSet<nint> CrewInTransit = new HashSet<IntPtr>();

		private int _navigationVersion;

		private readonly EAccessSettings _trunkAccess;

		private readonly nint _vanPointer;

		private readonly nint _driverPointer;

		private readonly nint _escortPointer;

		private readonly bool _originalRoadPreference;

		private readonly bool _originalTrafficPreference;

		private Vector3 _lastProgressPosition;

		private float _lastProgressAt;

		private Vector3 _recoveryPosition;

		private Vector3 _roadTarget;

		private float _reverseStartedAt;

		private float _navigationStartedAt;

		private bool _pathInterrupted;

		private int _recoveryStep;

		private int _relocations;

		private Vector3[] _lastPath = Array.Empty<Vector3>();

		private float _lastServiceAction;

		private float _nextShelfScan;

		private DriverShelf? _shelf;

		private Vector3 _shelfApproach;

		private float _closestToShelf;

		private bool _pickupPhase;

		private bool _holdingRoadStop;

		private bool _approachingDealer;

		public Route Route { get; }

		public LandVehicle Van { get; }

		public Employee Driver { get; }

		public Employee? Escort { get; }

		public DriverStopOption Destination { get; }

		public Vector3 Stop { get; }

		public float Started { get; } = Time.time;

		public float Departed { get; private set; }

		public bool Driving { get; private set; }

		public bool Interrupted { get; private set; }

		public bool Servicing { get; private set; }

		public bool Arrived
		{
			get
			{
				//IL_003b: 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)
				if (!((Object)(object)Destination.Parking != (Object)null) || !((Object)(object)Van.CurrentParkingLot == (Object)(object)Destination.Parking))
				{
					if (Vector3.Distance(((Component)Van).transform.position, Stop) <= 14f)
					{
						return Mathf.Abs(Van.Speed_Kmh) < 12f;
					}
					return false;
				}
				return true;
			}
		}

		public bool DriverAtVan
		{
			get
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)((NPC)Driver).CurrentVehicle == (Object)(object)Van))
				{
					return Vector3.Distance(((Component)Driver).transform.position, ((Component)Van).transform.position) <= 5.5f;
				}
				return true;
			}
		}

		public bool NavigationFailed { get; private set; }

		public bool Recovering
		{
			get
			{
				if (_recoveryStep > 0)
				{
					return !NavigationFailed;
				}
				return false;
			}
		}

		public Convoy(Route route, LandVehicle van, Employee driver, Employee? escort, DriverStopOption destination)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			Route = route;
			Van = van;
			Driver = driver;
			Escort = escort;
			Destination = destination;
			Stop = destination.Target;
			_trunkAccess = van.Storage.AccessSettings;
			_vanPointer = ((Il2CppObjectBase)van).Pointer;
			_driverPointer = ((Il2CppObjectBase)driver).Pointer;
			_escortPointer = ((escort != null) ? ((Il2CppObjectBase)escort).Pointer : IntPtr.Zero);
			_originalRoadPreference = van.Agent.Flags.UseRoads;
			_originalTrafficPreference = van.Agent.Flags.IgnoreTrafficLights;
			WalkToVan(driver);
			if ((Object)(object)escort != (Object)null)
			{
				WalkToVan(escort);
			}
			CrewInTransit.Add(_driverPointer);
			if (_escortPointer != 0)
			{
				CrewInTransit.Add(_escortPointer);
			}
		}

		private void WalkToVan(Employee employee)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			employee.SetIdle(false);
			Transform val = (((Object)(object)employee == (Object)(object)Driver) ? Van.driverEntryPoint : Van.GetClosestExitPoint(((Component)employee).transform.position));
			Vector3 val2 = (((Object)(object)val == (Object)null) ? (((Component)Van).transform.position - ((Component)Van).transform.right * 2f) : val.position);
			employee.SetDestination(val2, false);
		}

		public bool BoardAndDrive()
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			if (World.PlayerControls(Van) || !Board(Driver))
			{
				return false;
			}
			if ((Object)(object)Escort != (Object)null && World.CanWork(Escort) && !Board(Escort))
			{
				return false;
			}
			bool flag = (Object)(object)Van.CurrentParkingLot != (Object)null;
			if (flag)
			{
				Van.ExitPark_Networked((NetworkConnection)null, true);
			}
			Van.Storage.AccessSettings = (EAccessSettings)0;
			Driving = true;
			ConvoyPhysics.ActiveVans.Add(_vanPointer);
			Departed = Time.time;
			_roadTarget = (((Object)(object)Destination.Parking != (Object)null && DriverRoutes.TrySnapToVehicleGraph(Stop, 12f, out var road)) ? road : Stop);
			StartNavigation(useRoads: true, flag);
			return true;
		}

		private void StartNavigation(bool useRoads, bool checkProximity = false)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			int version = ++_navigationVersion;
			VehicleAgent agent = Van.Agent;
			agent.StopNavigating();
			agent.Flags.UseRoads = useRoads;
			agent.Flags.IgnoreTrafficLights = _originalTrafficPreference;
			_pathInterrupted = false;
			_navigationStartedAt = (_lastProgressAt = Time.time);
			_lastProgressPosition = ((Component)Van).transform.position;
			Vector3 road;
			NavigationSettings val = new NavigationSettings
			{
				ensureProximityToGraph = (checkProximity && DriverRoutes.TrySnapToVehicleGraph(((Component)Van).transform.position, 14f, out road)),
				teleportToGraphIfCalculationFails = false
			};
			agent.Navigate(_roadTarget, val, NavigationCallback.op_Implicit((Action<ENavigationResult>)delegate(ENavigationResult result)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Invalid comparison between Unknown and I4
				if (version == _navigationVersion)
				{
					_pathInterrupted = (int)result != 1 || (Object)(object)Van == (Object)null || !Arrived;
				}
			}));
		}

		public void CheckProgress()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: 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)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			VehicleAgent agent = Van.Agent;
			float time = Time.time;
			Vector3 position = ((Component)Van).transform.position;
			if (_reverseStartedAt > 0f)
			{
				float num = time - _reverseStartedAt;
				if (!(num < 1.5f) && (!agent.IsReversing || !(num < 8f)))
				{
					_reverseStartedAt = 0f;
					StartNavigation(useRoads: false);
				}
			}
			else
			{
				if (agent.NavigationCalculationInProgress && time - _navigationStartedAt < 18f)
				{
					return;
				}
				if (agent.AutoDriving && !_pathInterrupted && !agent.NavigationCalculationInProgress)
				{
					Vector3 val = position - _lastProgressPosition;
					if (((Vector3)(ref val)).sqrMagnitude >= 9f)
					{
						_lastProgressAt = time;
						_lastProgressPosition = position;
						if (_recoveryStep > 0)
						{
							val = position - _recoveryPosition;
							if (((Vector3)(ref val)).sqrMagnitude >= 225f)
							{
								_recoveryStep = 0;
								agent.Flags.IgnoreTrafficLights = _originalTrafficPreference;
							}
						}
					}
					float num2 = ((agent.targetSpeed > 3f) ? 9f : 14f);
					if (time - _lastProgressAt < num2)
					{
						return;
					}
				}
				else if (!_pathInterrupted && time - _navigationStartedAt < 2f)
				{
					return;
				}
				if (!agent.NavigationCalculationInProgress)
				{
					SmoothedPath path = agent.path;
					List<Vector3> val2 = ((path != null) ? path.vectorPath : null);
					if (val2 != null && val2.Count >= 2)
					{
						_lastPath = Il2CppArrayBase<Vector3>.op_Implicit(val2.ToArray());
					}
				}
				Pose pose;
				if (_recoveryStep == 0)
				{
					_recoveryPosition = position;
					_recoveryStep = 1;
					if (agent.AutoDriving && !_pathInterrupted && !agent.IsReversing)
					{
						_reverseStartedAt = time;
						agent.StartReverse();
					}
					else
					{
						StartNavigation(useRoads: false);
					}
				}
				else if (_recoveryStep == 1 && agent.AutoDriving && !_pathInterrupted && !_originalTrafficPreference && agent.targetSpeed < 1f)
				{
					_recoveryStep = 2;
					_lastProgressAt = time;
					agent.Flags.IgnoreTrafficLights = true;
				}
				else if (_relocations < 3 && ConvoyRoadRecovery.TryFindClearPose(Van, _lastPath, out pose))
				{
					bool useRoads = agent.Flags.UseRoads;
					_navigationVersion++;
					agent.StopNavigating();
					Van.Rb.velocity = Vector3.zero;
					Van.Rb.angularVelocity = Vector3.zero;
					Van.SetTransform(pose.position, pose.rotation);
					_relocations++;
					_recoveryPosition = pose.position;
					_recoveryStep = 1;
					_lastPath = Array.Empty<Vector3>();
					StartNavigation(useRoads);
				}
				else
				{
					NavigationFailed = true;
				}
			}
		}

		private bool Board(Employee employee)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)((NPC)employee).CurrentVehicle == (Object)(object)Van)
			{
				return true;
			}
			if (((NPC)employee).IsInVehicle || Vector3.Distance(((Component)employee).transform.position, ((Component)Van).transform.position) > 5.5f || ((IEnumerable<NPC>)Van.OccupantNPCs).Count((NPC occupant) => (Object)(object)occupant != (Object)null) >= Van.Capacity)
			{
				return false;
			}
			((NPC)employee).EnterVehicle((NetworkConnection)null, Van);
			return (Object)(object)((NPC)employee).CurrentVehicle == (Object)(object)Van;
		}

		public void StopDriving()
		{
			_navigationVersion++;
			if ((Object)(object)Van != (Object)null && Driving)
			{
				Van.Agent.StopNavigating();
				Van.Agent.Flags.IgnoreTrafficLights = _originalTrafficPreference;
			}
			_reverseStartedAt = 0f;
			Driving = false;
		}

		public bool BeginService()
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			if (Servicing)
			{
				return true;
			}
			StopDriving();
			ParkingLot parking = Destination.Parking;
			if ((Object)(object)parking == (Object)null)
			{
				if (!Destination.RoadStop.HasValue)
				{
					return false;
				}
				Van.overrideControls = true;
				Van.handbrakeOverride = true;
				_holdingRoadStop = true;
				if (Mathf.Abs(Van.Speed_Kmh) > 2f)
				{
					return false;
				}
			}
			else if ((Object)(object)Van.CurrentParkingLot != (Object)(object)parking || (Object)(object)Van.CurrentParkingSpot == (Object)null)
			{
				if (!Destination.TryGetSpot(Van, out int index, out ParkingSpot available) || (Object)(object)available == (Object)null)
				{
					return false;
				}
				Van.Park((NetworkConnection)null, new ParkData(parking.GUID, index, available.Alignment), true);
				if ((Object)(object)Van.CurrentParkingLot != (Object)(object)parking || (Object)(object)Van.CurrentParkingSpot != (Object)(object)available)
				{
					return false;
				}
			}
			ConvoyPhysics.ActiveVans.Remove(_vanPointer);
			Disembark();
			if ((Object)(object)Escort != (Object)null && (Object)(object)Destination.Property == (Object)(object)Escort.AssignedProperty)
			{
				CrewInTransit.Remove(_escortPointer);
			}
			Van.Storage.AccessSettings = _trunkAccess;
			_lastServiceAction = Time.time;
			Servicing = true;
			return true;
		}

		public bool Service(string dropoff, string pickup, float idleSeconds)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			if (!Servicing)
			{
				return false;
			}
			if ((Object)(object)Destination.Dealer != (Object)null)
			{
				return ServiceDealer(idleSeconds);
			}
			float time = Time.time;
			if (_shelf != null)
			{
				float num = Vector3.Distance(((Component)Driver).transform.position, _shelfApproach);
				if (num < _closestToShelf - 0.2f)
				{
					_closestToShelf = num;
					_lastServiceAction = time;
				}
			}
			if (time - _lastServiceAction >= idleSeconds)
			{
				return true;
			}
			if (time < _nextShelfScan)
			{
				return false;
			}
			_nextShelfScan = time + 0.5f;
			if (_shelf != null && ((Object)(object)_shelf.Item == (Object)null || !CanTransfer(_shelf) || !DriverRoutes.MatchesLabel(_shelf.Item.GetManagementName(), _pickupPhase ? pickup : dropoff, !_pickupPhase)))
			{
				_shelf = null;
			}
			if (_shelf == null)
			{
				_shelf = FindShelf(_pickupPhase ? pickup : dropoff);
				if (_shelf == null && !_pickupPhase)
				{
					_pickupPhase = true;
					_shelf = FindShelf(pickup);
				}
				if (_shelf == null)
				{
					return true;
				}
				_shelfApproach = _shelf.Approach(((Component)Driver).transform.position);
				_closestToShelf = Vector3.Distance(((Component)Driver).transform.position, _shelfApproach);
				if (_closestToShelf > 2.5f)
				{
					Driver.SetDestination(_shelfApproach, false);
				}
			}
			if (Vector3.Distance(((Component)Driver).transform.position, _shelfApproach) > 2.5f)
			{
				return false;
			}
			List<ItemSlot> itemSlots = _shelf.Stash.Storage.ItemSlots;
			List<ItemSlot> itemSlots2 = Van.Storage.ItemSlots;
			if ((_pickupPhase ? Cargo.Transfer(itemSlots, itemSlots2) : Cargo.Transfer(itemSlots2, itemSlots)) > 0)
			{
				_lastServiceAction = time;
			}
			_shelf = null;
			return false;
		}

		private DriverShelf? FindShelf(string label)
		{
			Property property = Destination.Property;
			if (!((Object)(object)property == (Object)null))
			{
				return DriverRoutes.Shelves(property, label, !_pickupPhase).Where(CanTransfer).OrderBy(delegate(DriverShelf shelf)
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_0021: Unknown result type (might be due to invalid IL or missing references)
					//IL_0026: Unknown result type (might be due to invalid IL or missing references)
					//IL_002b: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val = shelf.Approach(((Component)Driver).transform.position) - ((Component)Driver).transform.position;
					return ((Vector3)(ref val)).sqrMagnitude;
				})
					.FirstOrDefault();
			}
			return null;
		}

		private bool ServiceDealer(float idleSeconds)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			Dealer dealer = Destination.Dealer;
			if (!((Object)(object)dealer == (Object)null) && dealer.IsRecruited && ((NPC)dealer).IsConscious && !((Object)(object)((NPC)dealer).Inventory == (Object)null))
			{
				Vector3? dealerApproach = Destination.DealerApproach;
				if (dealerApproach.HasValue)
				{
					Vector3 valueOrDefault = dealerApproach.GetValueOrDefault();
					List<ItemSlot> itemSlots = Van.Storage.ItemSlots;
					if (!Cargo.CanSupplyDealer(itemSlots, dealer) && !Cargo.CanCollectDealerCash(itemSlots, dealer))
					{
						return true;
					}
					float num = Vector3.Distance(((Component)Driver).transform.position, valueOrDefault);
					if (num <= 3f)
					{
						Cargo.SupplyDealer(itemSlots, dealer);
						Cargo.CollectDealerCash(itemSlots, dealer);
						return true;
					}
					if (!_approachingDealer)
					{
						_approachingDealer = true;
						_closestToShelf = num;
						Driver.SetDestination(valueOrDefault, false);
					}
					if (num < _closestToShelf - 0.2f)
					{
						_closestToShelf = num;
						_lastServiceAction = Time.time;
					}
					return Time.time - _lastServiceAction >= idleSeconds;
				}
			}
			return true;
		}

		private bool CanTransfer(DriverShelf shelf)
		{
			StorageEntity storage = shelf.Stash.Storage;
			if ((Object)(object)storage == (Object)null)
			{
				return false;
			}
			List<ItemSlot> itemSlots = Van.Storage.ItemSlots;
			if (!_pickupPhase)
			{
				return Cargo.CanTransfer(itemSlots, storage.ItemSlots);
			}
			return Cargo.CanTransfer(storage.ItemSlots, itemSlots);
		}

		public void HoldForAmbush()
		{
			StopDriving();
			Van.overrideControls = true;
			Van.handbrakeOverride = true;
			Interrupted = true;
		}

		public void Disembark()
		{
			Leave(Driver);
			Leave(Escort);
		}

		private void Leave(Employee? employee)
		{
			if ((Object)(object)employee != (Object)null && ((NPC)employee).IsInVehicle && (Object)(object)((NPC)employee).CurrentVehicle == (Object)(object)Van)
			{
				((NPC)employee).ExitVehicle();
			}
		}

		public void Release()
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			ConvoyPhysics.ActiveVans.Remove(_vanPointer);
			CrewInTransit.Remove(_driverPointer);
			if (_escortPointer != 0)
			{
				CrewInTransit.Remove(_escortPointer);
			}
			try
			{
				StopDriving();
				Disembark();
			}
			finally
			{
				if ((Object)(object)Van != (Object)null && (Object)(object)Van.Storage != (Object)null)
				{
					if (Interrupted || _holdingRoadStop)
					{
						Van.handbrakeOverride = false;
						Van.overrideControls = false;
					}
					if ((Object)(object)Van.Agent != (Object)null)
					{
						Van.Agent.Flags.UseRoads = _originalRoadPreference;
					}
					Van.Storage.AccessSettings = _trunkAccess;
				}
			}
		}
	}
	[HarmonyPatch(typeof(IdleBehaviour), "OnActiveTick")]
	internal static class ConvoyMovement
	{
		private static bool Prefix(IdleBehaviour __instance)
		{
			if (!((Object)(object)((Behaviour)__instance).Npc == (Object)null))
			{
				return !Convoy.CrewInTransit.Contains(((Il2CppObjectBase)((Behaviour)__instance).Npc).Pointer);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(LandVehicle), "ShouldBePhysicallySimulated")]
	internal static class ConvoyPhysics
	{
		public static readonly HashSet<nint> ActiveVans = new HashSet<IntPtr>();

		private static void Postfix(LandVehicle __instance, ref bool __result)
		{
			if (!__result && ActiveVans.Contains(((Il2CppObjectBase)__instance).Pointer) && __instance.IsVisible && !World.PlayerControls(__instance))
			{
				__result = true;
			}
		}
	}
	[HarmonyPatch(typeof(Dealer), "TradeItems")]
	internal static class DealerInventoryFilters
	{
		private static void Prefix(Dealer __instance)
		{
			if (__instance.IsRecruited && !((Object)(object)((NPC)__instance).Inventory == (Object)null))
			{
				Enumerator<ItemSlot> enumerator = ((NPC)__instance).Inventory.ItemSlots.GetEnumerator();
				while (enumerator.MoveNext())
				{
					enumerator.Current.CanPlayerSetFilter = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(NPCInventory), "RpcLogic___SetSlotFilter_Internal_527532783")]
	internal static class SaveDealerInventoryFilters
	{
		private static void Postfix(NPCInventory __instance)
		{
			Dealer componentInParent = ((Component)__instance).GetComponentInParent<Dealer>();
			if ((Object)(object)componentInParent != (Object)null && componentInParent.IsRecruited)
			{
				((NPC)componentInParent).HasChanged = true;
			}
		}
	}
	internal sealed record DiagnosticsResult(int Passed, int Failed, int Skipped)
	{
		public string Summary
		{
			get
			{
				if (Failed == 0)
				{
					return $"{Passed} checks passed, {Skipped} skipped. Details in MelonLoader.";
				}
				return $"{Failed} checks failed. Details in MelonLoader.";
			}
		}
	}
	internal static class Diagnostics
	{
		public static DiagnosticsResult Run()
		{
			int passed = 0;
			int failed = 0;
			int num = 0;
			Check("Shelf labels match without case or surrounding whitespace", () => DriverRoutes.MatchesLabel(" driver pickup ", "DRIVER PICKUP"));
			Check("Named More Business bins are only included by the dropoff selector", () => DriverRoutes.MatchesLabel("DRIVER DROPOFF / Casino", "DRIVER DROPOFF", allowBusinessSuffix: true) && !DriverRoutes.MatchesLabel("DRIVER DROPOFF / Casino", "DRIVER DROPOFF"));
			Check("Itinerary order and the next stop survive serialization", CheckRouteRoundTrip);
			Check("Ambush rank and chance boundaries", () => !IncidentRules.CanAmbush(5, 6, enabled: true, 100, 0) && IncidentRules.CanAmbush(6, 6, enabled: true, 20, 19) && !IncidentRules.CanAmbush(6, 6, enabled: true, 20, 20));
			Check("Raider loadout odds respect the configured boundaries", delegate
			{
				string[] source = (from roll in Enumerable.Range(0, 100)
					select RaiderLoadout.Choose(100, 8, 0, roll)).ToArray();
				return RaiderLoadout.Choose(0, 100, 0, 0) == null && RaiderLoadout.Choose(100, 100, 99, 99) == ((object)Unsafe.As<EquippablePath, EquippablePath>(ref EquippablePath.PumpShotgun)/*cast due to .constrained prefix*/).ToString() && source.Count((string path) => path == ((object)Unsafe.As<EquippablePath, EquippablePath>(ref EquippablePath.PumpShotgun)/*cast due to .constrained prefix*/).ToString()) == 8 && source.Count((string path) => path == ((object)Unsafe.As<EquippablePath, EquippablePath>(ref EquippablePath.Revolver)/*cast due to .constrained prefix*/).ToString()) == 19 && source.Count((string path) => path == ((object)Unsafe.As<EquippablePath, EquippablePath>(ref EquippablePath.M1911)/*cast due to .constrained prefix*/).ToString()) == 73;
			});
			if (CartelLogisticsMod.CurrentOperations == null)
			{
				num += 3;
				Log("SKIP Native warehouse, parking and phone fields. Load a host save.");
			}
			else
			{
				Check("Native Fixer dialogue adds Driver and Soldier", CheckWarehouseChoices);
				Check("Native parking stops resolve without duplicate identifiers", delegate
				{
					List<DriverStop> list = (from option in DriverRoutes.AvailableStops()
						select option.Stop).ToList();
					return list.Distinct().Count() == list.Count && list.All((DriverStop stop) => DriverRoutes.Resolve(stop) != null);
				});
				Check("Phone uses working native text fields", () => LogisticsPhoneApp.Active?.VerifyTextFields() ?? false);
			}
			if (AppDomain.CurrentDomain.GetAssemblies().Any((Assembly assembly) => assembly.GetType("MoreBusiness.Mod") != null))
			{
				Check("Installed More Business operation interface is compatible", () => MoreBusinessBridge.TryBind() != null);
			}
			else
			{
				num++;
				Log("SKIP More Business is not enabled.");
			}
			return new DiagnosticsResult(passed, failed, num);
			void Check(string name, Func<bool> test)
			{
				try
				{
					if (test())
					{
						passed++;
						Log("PASS " + name);
					}
					else
					{
						failed++;
						Log("FAIL " + name);
					}
				}
				catch (Exception ex)
				{
					failed++;
					Log("FAIL " + name + ". " + ex.GetBaseException().Message);
				}
			}
		}

		public static string CheckClipboard()
		{
			try
			{
				string text = DriverClipboard.RunDiagnostic();
				Log(text);
				return text;
			}
			catch (Exception ex)
			{
				string text2 = "Clipboard check failed. " + ex.GetBaseException().Message;
				Log(text2);
				return text2;
			}
		}

		private static bool CheckRouteRoundTrip()
		{
			List<DriverStop> list = new List<DriverStop>
			{
				new DriverStop("first", "lot-a"),
				new DriverStop("second", "lot-b"),
				new DriverStop("first", "lot-c")
			};
			Route route = OperationsData.ReadCurrent(new OperationsData
			{
				Routes = new List<Route>
				{
					new Route
					{
						DriverId = "test",
						VanId = "vehicle",
						Stops = list,
						NextStop = 1
					}
				}
			}.Serialize()).Routes.Single();
			if (route.NextStop == 1 && route.Stops.SequenceEqual(list))
			{
				return route.VanId == "vehicle";
			}
			return false;
		}

		private static bool CheckWarehouseChoices()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			DialogueController_Fixer val = Object.FindObjectOfType<DialogueController_Fixer>();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			List<DialogueChoiceData> val2 = new List<DialogueChoiceData>();
			val2.Add(new DialogueChoiceData
			{
				ChoiceLabel = "Packager",
				ChoiceText = "Handler"
			});
			((DialogueController)val).ModifyChoiceList("SELECT_EMPLOYEE", ref val2);
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			Enumerator<DialogueChoiceData> enumerator = val2.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DialogueChoiceData current = enumerator.Current;
				flag |= current.ChoiceLabel == "CartelLogistics.Driver";
				flag2 |= current.ChoiceLabel == "CartelLogistics.Soldier";
				flag3 |= current.ChoiceLabel == "Packager";
			}
			return flag && flag2 && flag3;
		}

		private static void Log(string text)
		{
			MelonLogger.Msg("[Logistics check]