Decompiled source of EmpireControl v2.0.1

Mods/ScheduleTweaks.dll

Decompiled 6 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppFishNet.Object;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Casino.UI;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.Delivery;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Effects;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Levelling;
using Il2CppScheduleOne.Management;
using Il2CppScheduleOne.Management.UI;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.Messaging;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Product.Packaging;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.StationFramework;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.Tools;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Management;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.UI.Phone.Delivery;
using Il2CppScheduleOne.UI.Phone.Map;
using Il2CppScheduleOne.UI.Phone.Messages;
using Il2CppScheduleOne.UI.Shop;
using Il2CppScheduleOne.UI.Stations;
using Il2CppScheduleOne.Vehicles;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using ScheduleTweaks;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Mod), "ScheduleTweaks", "2.0.1", "prixedox", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ScheduleTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a7ccd453b0e23b0b8e56a43be1a80828b2f65ed1")]
[assembly: AssemblyProduct("ScheduleTweaks")]
[assembly: AssemblyTitle("ScheduleTweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ScheduleTweaks
{
	internal static class AutoAccept
	{
		private static readonly Queue<(Customer c, float at)> Pending = new Queue<(Customer, float)>();

		private const float Delay = 1.5f;

		private static DealWindowSelector _selector;

		private static readonly EDealWindow[] Order;

		internal static void Enqueue(Customer c)
		{
			if (Mod.AutoAcceptDeals.Value && (Object)(object)c != (Object)null && Net.IsHost)
			{
				Pending.Enqueue((c, Time.realtimeSinceStartup + 1.5f));
			}
		}

		internal static void Tick()
		{
			while (Pending.Count > 0 && Pending.Peek().at <= Time.realtimeSinceStartup)
			{
				Customer item = Pending.Dequeue().c;
				try
				{
					Accept(item);
				}
				catch (Exception ex)
				{
					Mod.Warn("Auto-accept failed: " + ex.Message);
				}
			}
		}

		private static void Accept(Customer c)
		{
			//IL_006b: 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)
			if ((Object)(object)c == (Object)null || c.OfferedContractInfo == null || (Object)(object)c.CurrentContract != (Object)null)
			{
				return;
			}
			ContractInfo offeredContractInfo = c.OfferedContractInfo;
			if (!TryPickWindow(out var window))
			{
				Mod.Log("Auto-accept: no deal window open for " + c.NPC.FullName + ", left for you to answer.");
				Ui.Toast(c.NPC.FirstName + " wants a deal: answer it in Messages");
				return;
			}
			c.PlayerAcceptedContract(window);
			if (!Mod.MuteAcceptToast.Value)
			{
				Ui.Toast($"Deal accepted: {c.NPC.FirstName}, {MoneyManager.FormatAmount(offeredContractInfo.Payment, false, false)}, {Pretty(window)}");
			}
		}

		private static bool TryPickWindow(out EDealWindow window)
		{
			//IL_0042: 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_004d: Expected I4, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_00df: 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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Expected I4, but got Unknown
			window = (EDealWindow)0;
			if ((Object)(object)_selector == (Object)null)
			{
				_selector = Object.FindObjectOfType<DealWindowSelector>(true);
			}
			if ((Object)(object)_selector == (Object)null)
			{
				return false;
			}
			if (Enum.TryParse<EDealWindow>(Mod.AutoAcceptWindow.Value, out EDealWindow result) && _selector.IsWindowValid(result))
			{
				window = (EDealWindow)(int)result;
				return true;
			}
			bool flag = false;
			int num = int.MaxValue;
			StringBuilder stringBuilder = new StringBuilder();
			int minSumFrom24HourTime = TimeManager.GetMinSumFrom24HourTime(NetworkSingleton<TimeManager>.Instance.CurrentTime);
			EDealWindow[] order = Order;
			foreach (EDealWindow val in order)
			{
				DealWindowInfo windowInfo = DealWindowInfo.GetWindowInfo(val);
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(4, 4, stringBuilder2);
				handler.AppendLiteral(" ");
				handler.AppendFormatted<EDealWindow>(val);
				handler.AppendLiteral("[");
				handler.AppendFormatted(windowInfo.StartTime, "0000");
				handler.AppendLiteral("-");
				handler.AppendFormatted(windowInfo.EndTime, "0000");
				handler.AppendFormatted(_selector.IsWindowValid(val) ? "" : " closed");
				handler.AppendLiteral("]");
				stringBuilder2.Append(ref handler);
				if (!_selector.IsWindowValid(val))
				{
					continue;
				}
				int minSumFrom24HourTime2 = TimeManager.GetMinSumFrom24HourTime(windowInfo.StartTime);
				int minSumFrom24HourTime3 = TimeManager.GetMinSumFrom24HourTime(windowInfo.EndTime);
				bool num2;
				if (minSumFrom24HourTime2 > minSumFrom24HourTime3)
				{
					if (minSumFrom24HourTime >= minSumFrom24HourTime2)
					{
						goto IL_018a;
					}
					num2 = minSumFrom24HourTime < minSumFrom24HourTime3;
				}
				else
				{
					if (minSumFrom24HourTime < minSumFrom24HourTime2)
					{
						goto IL_0177;
					}
					num2 = minSumFrom24HourTime < minSumFrom24HourTime3;
				}
				if (!num2)
				{
					goto IL_0177;
				}
				goto IL_018a;
				IL_018b:
				int num4;
				int num3 = num4;
				if (num3 < num)
				{
					num = num3;
					window = (EDealWindow)(int)val;
					flag = true;
				}
				continue;
				IL_0177:
				num4 = (minSumFrom24HourTime2 - minSumFrom24HourTime + 1440) % 1440;
				goto IL_018b;
				IL_018a:
				num4 = 0;
				goto IL_018b;
			}
			Mod.Log($"Auto-accept at {NetworkSingleton<TimeManager>.Instance.CurrentTime:0000}: picked {(flag ? ((object)Unsafe.As<EDealWindow, EDealWindow>(ref window)/*cast due to .constrained prefix*/).ToString() : "none")} from{stringBuilder}");
			return flag;
		}

		internal unsafe static string Pretty(EDealWindow w)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)w != 3)
			{
				return ((object)(*(EDealWindow*)(&w))/*cast due to .constrained prefix*/).ToString().ToLowerInvariant();
			}
			return "late night";
		}

		static AutoAccept()
		{
			EDealWindow[] array = new EDealWindow[4];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			Order = (EDealWindow[])(object)array;
		}
	}
	[HarmonyPatch(typeof(Customer), "NotifyPlayerOfContract")]
	internal static class NotifyContractPatch
	{
		private static void Postfix(Customer __instance, ContractInfo contract, MessageChain offerMessage, bool canAccept)
		{
			if (canAccept && contract != null && !contract.IsCounterOffer)
			{
				AutoAccept.Enqueue(__instance);
			}
		}
	}
	public class OrderItem
	{
		public string Id { get; set; }

		public int Qty { get; set; }
	}
	public class OrderRule
	{
		public bool Enabled { get; set; } = true;

		public string StoreName { get; set; }

		public string DestinationCode { get; set; }

		public int DockIndex { get; set; }

		public List<OrderItem> Items { get; set; } = new List<OrderItem>();

		public string Mode { get; set; } = "Daily";

		public int Hour { get; set; } = 7;

		public string WatchItemId { get; set; }

		public int Threshold { get; set; } = 20;

		public int LastFiredDay { get; set; } = -1;

		public string LastResult { get; set; } = "";
	}
	internal static class AutoOrders
	{
		internal static List<OrderRule> Rules = new List<OrderRule>();

		internal static void Load()
		{
			try
			{
				Rules = new List<OrderRule>();
				string text = SaveFiles.Read("AutoOrders");
				if (text != null)
				{
					Rules = JsonSerializer.Deserialize<List<OrderRule>>(text) ?? new List<OrderRule>();
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not read auto orders: " + ex.Message);
			}
		}

		internal static void Save()
		{
			try
			{
				SaveFiles.Write("AutoOrders", JsonSerializer.Serialize(Rules, new JsonSerializerOptions
				{
					WriteIndented = true
				}));
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not save auto orders: " + ex.Message);
			}
		}

		internal static List<DeliveryReceipt> PastOrders()
		{
			List<DeliveryReceipt> list = new List<DeliveryReceipt>();
			if (!NetworkSingleton<DeliveryManager>.InstanceExists)
			{
				return list;
			}
			List<DeliveryReceipt> displayedDeliveryHistory = NetworkSingleton<DeliveryManager>.Instance.DisplayedDeliveryHistory;
			if (displayedDeliveryHistory == null)
			{
				return list;
			}
			Enumerator<DeliveryReceipt> enumerator = displayedDeliveryHistory.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeliveryReceipt current = enumerator.Current;
				if (current != null)
				{
					list.Add(current);
				}
			}
			list.Reverse();
			return list;
		}

		internal static OrderRule FromReceipt(DeliveryReceipt r, string mode)
		{
			OrderRule orderRule = new OrderRule
			{
				StoreName = r.StoreName,
				DestinationCode = r.DestinationCode,
				DockIndex = r.LoadingDockIndex,
				Mode = mode
			};
			foreach (StringIntPair item in (Il2CppArrayBase<StringIntPair>)(object)r.Items)
			{
				orderRule.Items.Add(new OrderItem
				{
					Id = item.String,
					Qty = item.Int
				});
			}
			if (orderRule.Items.Count > 0)
			{
				orderRule.WatchItemId = orderRule.Items[0].Id;
			}
			return orderRule;
		}

		internal static void OnHour(int hour)
		{
			if (Rules.Count == 0 || !Mod.EnableAutoOrders.Value)
			{
				return;
			}
			int elapsedDays = NetworkSingleton<TimeManager>.Instance.ElapsedDays;
			bool flag = false;
			foreach (OrderRule rule in Rules)
			{
				if (!rule.Enabled)
				{
					continue;
				}
				try
				{
					bool num;
					if (!(rule.Mode == "Daily"))
					{
						num = IsLow(rule);
						goto IL_007c;
					}
					if (hour >= rule.Hour)
					{
						num = rule.LastFiredDay != elapsedDays;
						goto IL_007c;
					}
					goto end_IL_004a;
					IL_007c:
					if (num)
					{
						if (TryFire(rule, out var msg))
						{
							rule.LastFiredDay = elapsedDays;
						}
						rule.LastResult = msg;
						flag = true;
					}
					end_IL_004a:;
				}
				catch (Exception ex)
				{
					Mod.Warn($"Auto order {rule.StoreName} -> {rule.DestinationCode} failed: {ex.Message}");
				}
			}
			if (flag)
			{
				Save();
			}
		}

		internal static bool IsLow(OrderRule rule)
		{
			if (string.IsNullOrEmpty(rule.WatchItemId))
			{
				return false;
			}
			Property val = Stock.FindProperty(rule.DestinationCode);
			if ((Object)(object)val == (Object)null || !NetworkSingleton<DeliveryManager>.InstanceExists)
			{
				return false;
			}
			if (NetworkSingleton<DeliveryManager>.Instance.GetDelivery(val) != null)
			{
				return false;
			}
			return Stock.CountItem(val, rule.WatchItemId) < rule.Threshold;
		}

		internal static bool TryFire(OrderRule rule, out string msg)
		{
			if (!Net.IsHost)
			{
				msg = "only the host can send auto orders";
				return false;
			}
			DeliveryApp instance = PlayerSingleton<DeliveryApp>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				msg = "delivery app not ready";
				return false;
			}
			if (rule.Items.Count == 0)
			{
				msg = "skipped: the order has no items";
				return false;
			}
			DeliveryReceipt val = Receipt(rule);
			string text = default(string);
			if (!instance.CanReorder(val, ref text))
			{
				msg = "skipped: " + text;
				Mod.Log($"Auto order {rule.StoreName} -> {rule.DestinationCode} {msg}");
				return false;
			}
			float deliveryCost = instance.GetDeliveryCost(val);
			instance.Reorder(val);
			msg = $"sent day {NetworkSingleton<TimeManager>.Instance.ElapsedDays + 1}, ${deliveryCost:0}";
			Ui.Toast($"Auto order sent: {rule.StoreName} -> {PropertyName(rule.DestinationCode)} (${deliveryCost:0})");
			Mod.Log($"Auto order {rule.StoreName} -> {rule.DestinationCode} {msg}");
			return true;
		}

		private static DeliveryReceipt Receipt(OrderRule rule)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			Il2CppReferenceArray<StringIntPair> val = new Il2CppReferenceArray<StringIntPair>((long)rule.Items.Count);
			for (int i = 0; i < rule.Items.Count; i++)
			{
				((Il2CppArrayBase<StringIntPair>)(object)val)[i] = new StringIntPair(rule.Items[i].Id, rule.Items[i].Qty);
			}
			return new DeliveryReceipt(Guid.NewGuid().ToString(), rule.StoreName, rule.DestinationCode, rule.DockIndex, val);
		}

		internal static bool CanOrderNow(OrderRule rule, out string reason, out float cost)
		{
			reason = null;
			cost = 0f;
			DeliveryApp instance = PlayerSingleton<DeliveryApp>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				reason = "delivery app not ready";
				return false;
			}
			if (rule.Items.Count == 0)
			{
				reason = "no items";
				return false;
			}
			DeliveryReceipt val = Receipt(rule);
			cost = instance.GetDeliveryCost(val);
			return instance.CanReorder(val, ref reason);
		}

		internal static DeliveryInstance ActiveDelivery(OrderRule rule)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if (!NetworkSingleton<DeliveryManager>.InstanceExists)
			{
				return null;
			}
			Enumerator<DeliveryInstance> enumerator = NetworkSingleton<DeliveryManager>.Instance.Deliveries.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeliveryInstance current = enumerator.Current;
				if (current != null && (int)current.Status != 3 && current.StoreName == rule.StoreName && current.DestinationCode == rule.DestinationCode)
				{
					return current;
				}
			}
			return null;
		}

		internal static List<(string id, string name, float price)> Catalog(string storeName)
		{
			List<(string, string, float)> list = new List<(string, string, float)>();
			DeliveryApp instance = PlayerSingleton<DeliveryApp>.Instance;
			if ((Object)(object)instance == (Object)null || instance.deliveryShops == null)
			{
				return list;
			}
			Enumerator<DeliveryShop> enumerator = instance.deliveryShops.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeliveryShop current = enumerator.Current;
				ShopInterface val = ((current != null) ? current.MatchingShop : null);
				if ((Object)(object)val == (Object)null || val.ShopName != storeName || val.Listings == null)
				{
					continue;
				}
				Enumerator<ShopListing> enumerator2 = val.Listings.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					ShopListing current2 = enumerator2.Current;
					if (current2 != null && (Object)(object)current2.Item != (Object)null && current2.CanBeDelivered)
					{
						list.Add((((BaseItemDefinition)current2.Item).ID, ((BaseItemDefinition)current2.Item).Name, current2.Price));
					}
				}
			}
			return list;
		}

		internal static List<string> Stores()
		{
			List<string> list = new List<string>();
			DeliveryApp instance = PlayerSingleton<DeliveryApp>.Instance;
			if ((Object)(object)instance == (Object)null || instance.deliveryShops == null)
			{
				return list;
			}
			Enumerator<DeliveryShop> enumerator = instance.deliveryShops.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeliveryShop current = enumerator.Current;
				object obj;
				if (current == null)
				{
					obj = null;
				}
				else
				{
					ShopInterface matchingShop = current.MatchingShop;
					obj = ((matchingShop != null) ? matchingShop.ShopName : null);
				}
				string text = (string)obj;
				if (!string.IsNullOrEmpty(text) && !list.Contains(text))
				{
					list.Add(text);
				}
			}
			return list;
		}

		internal static string StoreFor(string itemId)
		{
			foreach (string item in Stores())
			{
				if (Catalog(item).Any(((string id, string name, float price) c) => c.id == itemId))
				{
					return item;
				}
			}
			return null;
		}

		internal static List<Property> Destinations()
		{
			List<Property> list = new List<Property>();
			foreach (Property item in Stock.OwnedProperties())
			{
				try
				{
					if (item.LoadingDockCount > 0)
					{
						list.Add(item);
					}
				}
				catch
				{
				}
			}
			return list;
		}

		internal static int Docks(string code)
		{
			try
			{
				Property obj = Stock.FindProperty(code);
				return Math.Max(1, (obj == null) ? 1 : obj.LoadingDockCount);
			}
			catch
			{
				return 1;
			}
		}

		internal static int StepUp(int v)
		{
			if (v >= 10)
			{
				return (v / 10 + 1) * 10;
			}
			return v + 1;
		}

		internal static int StepDown(int v)
		{
			if (v > 10)
			{
				return (v - 1) / 10 * 10;
			}
			return Math.Max(1, v - 1);
		}

		internal static string PropertyName(string code)
		{
			Property obj = Stock.FindProperty(code);
			return ((obj != null) ? obj.PropertyName : null) ?? code;
		}

		internal static string ItemName(string id)
		{
			ItemDefinition item = Registry.GetItem(id);
			if (!((Object)(object)item != (Object)null))
			{
				return id;
			}
			return ((BaseItemDefinition)item).Name;
		}
	}
	internal static class BrickUnpack
	{
		private const float Seconds = 1.5f;

		private static HashSet<string> _guids = new HashSet<string>();

		private static readonly Dictionary<IntPtr, List<ItemFilter>> RemovedFilters = new Dictionary<IntPtr, List<ItemFilter>>();

		private static readonly HashSet<IntPtr> OpenByPlayer = new HashSet<IntPtr>();

		private static float _next;

		internal static float BrickTime => 1.5f;

		internal static void Load()
		{
			RemovedFilters.Clear();
			OpenByPlayer.Clear();
			try
			{
				_guids = new HashSet<string>();
				string text = SaveFiles.Read("UnpackPresses");
				if (text != null)
				{
					_guids = JsonSerializer.Deserialize<HashSet<string>>(text) ?? new HashSet<string>();
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not read unpack stations: " + ex.Message);
			}
		}

		private static void Save()
		{
			try
			{
				SaveFiles.Write("UnpackPresses", JsonSerializer.Serialize(_guids));
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not save unpack stations: " + ex.Message);
			}
		}

		private static string Id(BuildableItem b)
		{
			//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)
			return ((object)b.GUID/*cast due to .constrained prefix*/).ToString();
		}

		internal static bool IsUnpack(BuildableItem b)
		{
			if ((Object)(object)b != (Object)null && _guids.Count > 0)
			{
				return _guids.Contains(Id(b));
			}
			return false;
		}

		internal static void Set(BuildableItem b, bool unpack)
		{
			if (unpack)
			{
				_guids.Add(Id(b));
			}
			else
			{
				_guids.Remove(Id(b));
			}
			Save();
			ApplyFilters(b);
			ExtraOutputs.Ensure(b);
		}

		internal static int UnpackAll(BuildableItem b)
		{
			int i;
			for (i = 0; i < 500; i++)
			{
				if (!UnpackOne(b))
				{
					break;
				}
			}
			return i;
		}

		internal static List<BuildableItem> Stations(Property prop)
		{
			List<BuildableItem> list = new List<BuildableItem>();
			if (((prop != null) ? prop.BuildableItems : null) == null)
			{
				return list;
			}
			Enumerator<BuildableItem> enumerator = prop.BuildableItems.GetEnumerator();
			while (enumerator.MoveNext())
			{
				BuildableItem current = enumerator.Current;
				if ((Object)(object)current != (Object)null && ((Object)(object)((Il2CppObjectBase)current).TryCast<BrickPress>() != (Object)null || (Object)(object)((Il2CppObjectBase)current).TryCast<PackagingStation>() != (Object)null))
				{
					list.Add(current);
				}
			}
			return list;
		}

		private static IEnumerable<ItemSlot> Inputs(BuildableItem b)
		{
			BrickPress val = ((Il2CppObjectBase)b).TryCast<BrickPress>();
			if ((Object)(object)val != (Object)null)
			{
				if (val.ProductSlots == null)
				{
					yield break;
				}
				foreach (ItemSlot item in (Il2CppArrayBase<ItemSlot>)(object)val.ProductSlots)
				{
					if (item != null)
					{
						yield return item;
					}
				}
			}
			else
			{
				PackagingStation val2 = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
				if (((val2 != null) ? val2.ProductSlot : null) != null)
				{
					yield return val2.ProductSlot;
				}
			}
		}

		private static ItemSlot Output(BuildableItem b)
		{
			BrickPress obj = ((Il2CppObjectBase)b).TryCast<BrickPress>();
			object obj2 = ((obj != null) ? obj.OutputSlot : null);
			if (obj2 == null)
			{
				PackagingStation obj3 = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
				if (obj3 == null)
				{
					return null;
				}
				obj2 = obj3.OutputSlot;
			}
			return (ItemSlot)obj2;
		}

		internal static void SetPlayerOpen(BuildableItem b, bool open)
		{
			if (Net.IsHost && !((Object)(object)((b != null) ? ((Il2CppObjectBase)b).TryCast<BrickPress>() : null) == (Object)null))
			{
				if (open)
				{
					OpenByPlayer.Add(((Il2CppObjectBase)b).Pointer);
				}
				else
				{
					OpenByPlayer.Remove(((Il2CppObjectBase)b).Pointer);
				}
				ApplyFilters(b);
			}
		}

		internal static bool OutputEmpty(BuildableItem b)
		{
			ItemSlot val = Output(b);
			if (val != null && val.Quantity > 0)
			{
				return false;
			}
			return ExtraOutputs.Get(b)?.All((ItemSlot s) => s.Quantity <= 0) ?? true;
		}

		internal static bool TrySet(BuildableItem b, bool unpack)
		{
			if (IsUnpack(b) == unpack)
			{
				return true;
			}
			if (!OutputEmpty(b))
			{
				Ui.Toast("Empty the output first, then switch Pack / Unpack");
				return false;
			}
			Set(b, unpack);
			return true;
		}

		internal static bool AutoSwitch(BuildableItem b)
		{
			if (!Net.IsHost || (Object)(object)((b != null) ? ((Il2CppObjectBase)b).TryCast<BrickPress>() : null) == (Object)null || IsUnpack(b) || PackageSlot(b, out var _) == null || !OutputEmpty(b))
			{
				return false;
			}
			Set(b, unpack: true);
			Ui.Toast("Brick press switched to Unpack");
			return true;
		}

		internal static void ApplyFilters(BuildableItem b)
		{
			bool flag = IsUnpack(b) || OpenByPlayer.Contains(((Il2CppObjectBase)b).Pointer);
			List<ItemSlot> list = Inputs(b).ToList();
			ItemSlot val = Output(b);
			if (val != null)
			{
				list.Add(val);
			}
			foreach (ItemSlot item in list)
			{
				if (((item != null) ? item.HardFilters : null) == null)
				{
					continue;
				}
				if (flag)
				{
					for (int num = item.HardFilters.Count - 1; num >= 0; num--)
					{
						ItemFilter val2 = item.HardFilters[num];
						if (val2 != null && (((Il2CppObjectBase)val2).TryCast<ItemFilter_UnpackagedProduct>() != null || ((Il2CppObjectBase)val2).TryCast<ItemFilter_PackagedProduct>() != null))
						{
							if (!RemovedFilters.TryGetValue(((Il2CppObjectBase)item).Pointer, out var value))
							{
								value = (RemovedFilters[((Il2CppObjectBase)item).Pointer] = new List<ItemFilter>());
							}
							value.Add(val2);
							item.HardFilters.RemoveAt(num);
						}
					}
				}
				else
				{
					if (!RemovedFilters.TryGetValue(((Il2CppObjectBase)item).Pointer, out var value2))
					{
						continue;
					}
					foreach (ItemFilter item2 in value2)
					{
						item.HardFilters.Add(item2);
					}
					RemovedFilters.Remove(((Il2CppObjectBase)item).Pointer);
				}
			}
		}

		internal static void Tick()
		{
			if (Time.realtimeSinceStartup < _next)
			{
				return;
			}
			_next = Time.realtimeSinceStartup + 3f;
			foreach (Property item in Stock.OwnedProperties())
			{
				foreach (BuildableItem item2 in Stations(item))
				{
					if (IsUnpack(item2))
					{
						ApplyFilters(item2);
					}
					ExtraOutputs.Ensure(item2);
				}
			}
		}

		private static ItemSlot PackageSlot(BuildableItem b, out ProductItemInstance pack)
		{
			pack = null;
			bool flag = (Object)(object)((Il2CppObjectBase)b).TryCast<BrickPress>() != (Object)null;
			foreach (ItemSlot item in Inputs(b))
			{
				if (item.Quantity > 0)
				{
					ItemInstance itemInstance = item.ItemInstance;
					ProductItemInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
					if (val != null && !string.IsNullOrEmpty(val.PackagingID) && (!flag || !(val.PackagingID != "brick")))
					{
						pack = val;
						return item;
					}
				}
			}
			return null;
		}

		private static ProductItemInstance Loose(ProductItemInstance pack)
		{
			int num = Math.Max(1, pack.Amount);
			ProductItemInstance obj = ((Il2CppObjectBase)((ItemInstance)pack).GetCopy(num)).Cast<ProductItemInstance>();
			obj.SetPackaging((PackagingDefinition)null);
			return obj;
		}

		internal static EState State(BuildableItem b)
		{
			if (PackageSlot(b, out var pack) != null)
			{
				ProductItemInstance val = Loose(pack);
				if (Room(b, (ItemInstance)(object)val) >= ((BaseItemInstance)val).Quantity)
				{
					return (EState)0;
				}
				return (EState)3;
			}
			return (EState)1;
		}

		private static List<ItemSlot> Targets(BuildableItem b)
		{
			List<ItemSlot> list = new List<ItemSlot>();
			ItemSlot val = Output(b);
			if (val != null)
			{
				list.Add(val);
			}
			List<ItemSlot> list2 = ExtraOutputs.Get(b);
			if (list2 != null)
			{
				list.AddRange(list2);
			}
			return list;
		}

		private static int Room(BuildableItem b, ItemInstance item)
		{
			int num = 0;
			foreach (ItemSlot item2 in Targets(b))
			{
				num += Math.Max(0, item2.GetCapacityForItem(item, false));
			}
			return num;
		}

		private static void Put(BuildableItem b, ProductItemInstance loose)
		{
			int num = ((BaseItemInstance)loose).Quantity;
			foreach (ItemSlot item in Targets(b))
			{
				if (num <= 0)
				{
					break;
				}
				int num2 = Math.Min(num, item.GetCapacityForItem((ItemInstance)(object)loose, false));
				if (num2 > 0)
				{
					item.InsertItem(((ItemInstance)loose).GetCopy(num2));
					num -= num2;
				}
			}
		}

		internal static bool UnpackOne(BuildableItem b)
		{
			ProductItemInstance pack;
			ItemSlot val = PackageSlot(b, out pack);
			if (val == null)
			{
				return false;
			}
			ProductItemInstance val2 = Loose(pack);
			if (Room(b, (ItemInstance)(object)val2) < ((BaseItemInstance)val2).Quantity)
			{
				return false;
			}
			PackagingDefinition appliedPackaging = pack.AppliedPackaging;
			val.ChangeQuantity(-1, false);
			Put(b, val2);
			PackagingStation val3 = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
			if (((val3 != null) ? val3.PackagingSlot : null) != null && (Object)(object)appliedPackaging != (Object)null && pack.PackagingID != "brick")
			{
				try
				{
					ItemInstance defaultInstance = ((ItemDefinition)appliedPackaging).GetDefaultInstance(1);
					if (val3.PackagingSlot.GetCapacityForItem(defaultInstance, false) >= 1)
					{
						val3.PackagingSlot.InsertItem(defaultInstance);
					}
				}
				catch
				{
				}
			}
			return true;
		}

		internal static IEnumerator Work(Behaviour beh, BuildableItem b, float seconds, Action<bool> setBusy)
		{
			setBusy(obj: true);
			float num = 1f;
			try
			{
				num = Math.Max(0.1f, ((Il2CppObjectBase)beh.Npc).Cast<Employee>().CurrentWorkSpeed);
			}
			catch
			{
			}
			yield return (object)new WaitForSeconds(seconds / num);
			try
			{
				if ((Object)(object)beh != (Object)null && beh.Active && IsUnpack(b))
				{
					int num2 = UnpackAll(b);
					if (num2 > 0)
					{
						Mod.Log($"Handler unpacked {num2} package(s)");
					}
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Unpack failed: " + ex.Message);
			}
			Release(b);
			setBusy(obj: false);
		}

		internal static void SetNpcUser(BuildableItem b, NetworkObject npc)
		{
			try
			{
				BrickPress val = ((Il2CppObjectBase)b).TryCast<BrickPress>();
				if ((Object)(object)val != (Object)null)
				{
					val.SetNPCUser(npc);
					return;
				}
				PackagingStation obj = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
				if (obj != null)
				{
					obj.SetNPCUser(npc);
				}
			}
			catch
			{
			}
		}

		internal static void Release(BuildableItem b)
		{
			SetNpcUser(b, null);
		}

		internal static bool PlayerUsing(BuildableItem b)
		{
			BrickPress obj = ((Il2CppObjectBase)b).TryCast<BrickPress>();
			object obj2 = ((obj != null) ? obj.PlayerUserObject : null);
			if (obj2 == null)
			{
				PackagingStation obj3 = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
				obj2 = ((obj3 != null) ? obj3.PlayerUserObject : null);
			}
			return (Object)obj2 != (Object)null;
		}

		internal static float PackTime()
		{
			return 1.5f;
		}
	}
	[HarmonyPatch(typeof(BrickPress), "GetState")]
	internal static class BrickPressStatePatch
	{
		private static bool Prefix(BrickPress __instance, ref EState __result)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected I4, but got Unknown
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)__instance))
			{
				return true;
			}
			try
			{
				__result = (EState)(int)BrickUnpack.State((BuildableItem)(object)__instance);
			}
			catch
			{
				__result = (EState)1;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PackagingStation), "GetState")]
	internal static class PackagingStationStatePatch
	{
		private static bool Prefix(PackagingStation __instance, ref EState __result)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected I4, but got Unknown
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)__instance))
			{
				return true;
			}
			try
			{
				__result = (EState)(int)BrickUnpack.State((BuildableItem)(object)__instance);
			}
			catch
			{
				__result = (EState)1;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(BrickPressBehaviour), "RpcLogic___BeginPackaging_2166136261")]
	internal static class BrickPressBeginPatch
	{
		private static bool Prefix(BrickPressBehaviour __instance)
		{
			BrickPress press = __instance.Press;
			if ((Object)(object)press == (Object)null)
			{
				return true;
			}
			if (BrickUnpack.PlayerUsing((BuildableItem)(object)press))
			{
				return false;
			}
			NPC npc = ((Behaviour)__instance).Npc;
			BrickUnpack.SetNpcUser((BuildableItem)(object)press, (npc != null) ? ((NetworkBehaviour)npc).NetworkObject : null);
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)press))
			{
				return true;
			}
			if (__instance.PackagingInProgress)
			{
				return false;
			}
			try
			{
				press.PlayPressAnim();
			}
			catch
			{
			}
			BrickPressBehaviour beh = __instance;
			MelonCoroutines.Start(BrickUnpack.Work((Behaviour)(object)beh, (BuildableItem)(object)press, BrickUnpack.BrickTime, delegate(bool busy)
			{
				if ((Object)(object)beh != (Object)null)
				{
					beh.PackagingInProgress = busy;
				}
			}));
			return false;
		}
	}
	[HarmonyPatch(typeof(PackagingStationBehaviour), "RpcLogic___BeginPackaging_2166136261")]
	internal static class PackagingStationBeginPatch
	{
		private static bool Prefix(PackagingStationBehaviour __instance)
		{
			PackagingStation station = __instance.Station;
			if ((Object)(object)station == (Object)null)
			{
				return true;
			}
			if (BrickUnpack.PlayerUsing((BuildableItem)(object)station))
			{
				return false;
			}
			NPC npc = ((Behaviour)__instance).Npc;
			BrickUnpack.SetNpcUser((BuildableItem)(object)station, (npc != null) ? ((NetworkBehaviour)npc).NetworkObject : null);
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)station))
			{
				return true;
			}
			if (__instance.PackagingInProgress)
			{
				return false;
			}
			PackagingStationBehaviour beh = __instance;
			MelonCoroutines.Start(BrickUnpack.Work((Behaviour)(object)beh, (BuildableItem)(object)station, BrickUnpack.PackTime(), delegate(bool busy)
			{
				if ((Object)(object)beh != (Object)null)
				{
					beh.PackagingInProgress = busy;
				}
			}));
			return false;
		}
	}
	[HarmonyPatch(typeof(BrickPressBehaviour), "StartPackaging")]
	internal static class BrickPressStartPatch
	{
		private static void Postfix(BrickPressBehaviour __instance)
		{
			BrickPress press = __instance.Press;
			if ((Object)(object)press != (Object)null && !__instance.PackagingInProgress)
			{
				BrickUnpack.Release((BuildableItem)(object)press);
			}
		}
	}
	[HarmonyPatch(typeof(PackagingStationBehaviour), "StartPackaging")]
	internal static class PackagingStationStartPatch
	{
		private static void Postfix(PackagingStationBehaviour __instance)
		{
			PackagingStation station = __instance.Station;
			if ((Object)(object)station != (Object)null && !__instance.PackagingInProgress)
			{
				BrickUnpack.Release((BuildableItem)(object)station);
			}
		}
	}
	[HarmonyPatch(typeof(BrickPress), "CompletePress")]
	internal static class BrickPressCompletePatch
	{
		private static bool Prefix(BrickPress __instance)
		{
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)__instance) || (Object)(object)__instance.PlayerUserObject != (Object)null)
			{
				return true;
			}
			try
			{
				BrickUnpack.UnpackAll((BuildableItem)(object)__instance);
			}
			catch (Exception ex)
			{
				Mod.Warn("Unpack (press step) failed: " + ex.Message);
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PackagingStation), "PackSingleInstance")]
	internal static class PackagingStationPackPatch
	{
		private static bool Prefix(PackagingStation __instance)
		{
			if (!BrickUnpack.IsUnpack((BuildableItem)(object)__instance) || (Object)(object)__instance.PlayerUserObject != (Object)null)
			{
				return true;
			}
			try
			{
				BrickUnpack.UnpackAll((BuildableItem)(object)__instance);
			}
			catch (Exception ex)
			{
				Mod.Warn("Unpack (pack step) failed: " + ex.Message);
			}
			return false;
		}
	}
	internal static class Casino
	{
		private static readonly Dictionary<IntPtr, InputField> Fields = new Dictionary<IntPtr, InputField>();

		internal static float Cash()
		{
			if (!NetworkSingleton<MoneyManager>.InstanceExists)
			{
				return 0f;
			}
			return NetworkSingleton<MoneyManager>.Instance.cashBalance;
		}

		internal static void OnPanelOpen(CasinoGameBetPanel panel)
		{
			//IL_00de: 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_00ff: 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_011f: 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_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: 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)
			if (Mod.UnlimitedCasino.Value && (Object)(object)panel._betSlider != (Object)null)
			{
				panel._betSlider.maxValue = Math.Max(panel._betSlider.maxValue, Mathf.Floor(Cash()));
			}
			Fields.TryGetValue(((Il2CppObjectBase)panel).Pointer, out var value);
			if ((Object)(object)value == (Object)null)
			{
				Slider betSlider = panel._betSlider;
				if ((Object)(object)betSlider == (Object)null)
				{
					return;
				}
				value = Ui.NumberField(((Component)betSlider).transform.parent, (int)panel._gameController.LocalPlayerBet, delegate(int v)
				{
					SetBet(panel, v);
				}, 160f, 40f, 9);
				RectTransform component = ((Component)betSlider).GetComponent<RectTransform>();
				RectTransform component2 = ((Component)value).GetComponent<RectTransform>();
				component2.anchorMin = component.anchorMin;
				component2.anchorMax = component.anchorMin;
				component2.pivot = new Vector2(0f, 1f);
				component2.sizeDelta = new Vector2(160f, 40f);
				Vector2 anchoredPosition = component.anchoredPosition;
				Rect rect = component.rect;
				float num = (0f - ((Rect)(ref rect)).width) * component.pivot.x;
				rect = component.rect;
				component2.anchoredPosition = anchoredPosition + new Vector2(num, (0f - ((Rect)(ref rect)).height) * (1f - component.pivot.y) - 10f);
				value.textComponent.fontSize = 20;
				((Text)value.placeholder).text = "type bet";
				Fields[((Il2CppObjectBase)panel).Pointer] = value;
				Mod.Log("Casino bet box added under the slider (slider max " + MoneyManager.FormatAmount(betSlider.maxValue, false, false) + ").");
			}
			value.text = ((int)panel._gameController.LocalPlayerBet).ToString();
		}

		private static void SetBet(CasinoGameBetPanel panel, int bet)
		{
			Slider betSlider = panel._betSlider;
			if (!((Object)(object)betSlider == (Object)null))
			{
				float num = (betSlider.value = Mathf.Clamp((float)bet, betSlider.minValue, betSlider.maxValue));
				panel._gameController.SetLocalPlayerBet(num);
				panel.RefreshDisplayedBet();
				panel.RefreshReadyButton();
				if (Fields.TryGetValue(((Il2CppObjectBase)panel).Pointer, out var value) && (Object)(object)value != (Object)null)
				{
					value.text = ((int)num).ToString();
				}
				if ((float)bet > num)
				{
					Ui.Toast(((float)bet > Cash()) ? "You don't have that much cash on you" : ("Max bet here is " + MoneyManager.FormatAmount(num, false, false)));
				}
			}
		}

		internal static void SyncFromSlider(CasinoGameBetPanel panel)
		{
			if (Fields.TryGetValue(((Il2CppObjectBase)panel).Pointer, out var value) && (Object)(object)value != (Object)null && !value.isFocused)
			{
				value.text = ((int)panel._gameController.LocalPlayerBet).ToString();
			}
		}
	}
	[HarmonyPatch(typeof(CasinoGameBetPanel), "Open")]
	internal static class BetPanelOpenPatch
	{
		private static void Postfix(CasinoGameBetPanel __instance)
		{
			try
			{
				Casino.OnPanelOpen(__instance);
			}
			catch (Exception ex)
			{
				Mod.Warn("Casino bet box failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(CasinoGameBetPanel), "BetSliderChanged")]
	internal static class BetSliderPatch
	{
		private static void Postfix(CasinoGameBetPanel __instance)
		{
			try
			{
				Casino.SyncFromSlider(__instance);
			}
			catch
			{
			}
		}
	}
	internal static class ClipboardScroll
	{
		private static RectTransform _panel;

		private static RectTransform _viewport;

		private static ScrollRect _scroll;

		private static float _next;

		internal static void Wrap(ManagementInterface ui)
		{
			//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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			ConfigPanel val = ((ui != null) ? ui.loadedPanel : null);
			RectTransform val2 = ((ui != null) ? ui.PanelContainer : null);
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
			{
				RectTransform component = ((Component)val).GetComponent<RectTransform>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)((Transform)component).parent == (Object)null))
				{
					GameObject val3 = new GameObject("TweaksScrollViewport");
					val3.transform.SetParent(((Transform)component).parent, false);
					RectTransform val4 = val3.AddComponent<RectTransform>();
					val4.anchorMin = component.anchorMin;
					val4.anchorMax = component.anchorMax;
					val4.pivot = component.pivot;
					val4.anchoredPosition = component.anchoredPosition;
					val4.sizeDelta = component.sizeDelta;
					((Transform)val4).SetSiblingIndex(((Transform)component).GetSiblingIndex());
					val3.AddComponent<RectMask2D>();
					((Graphic)val3.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
					Rect rect = component.rect;
					float height = ((Rect)(ref rect)).height;
					((Transform)component).SetParent((Transform)(object)val4, false);
					component.anchorMin = new Vector2(0f, 1f);
					component.anchorMax = new Vector2(1f, 1f);
					component.pivot = new Vector2(0.5f, 1f);
					component.anchoredPosition = Vector2.zero;
					component.sizeDelta = new Vector2(0f, height);
					_scroll = val3.AddComponent<ScrollRect>();
					_scroll.content = component;
					_scroll.viewport = val4;
					_scroll.horizontal = false;
					_scroll.vertical = true;
					_scroll.movementType = (MovementType)2;
					_scroll.scrollSensitivity = 30f;
					_panel = component;
					_viewport = val4;
				}
			}
		}

		internal static void Cleanup()
		{
			if ((Object)(object)_viewport != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_viewport).gameObject);
			}
			_viewport = null;
			_panel = null;
			_scroll = null;
		}

		internal static void Tick()
		{
			//IL_00ca: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_panel == (Object)null || (Object)(object)_viewport == (Object)null || Time.unscaledTime < _next)
			{
				return;
			}
			_next = Time.unscaledTime + 0.25f;
			float num = 0f;
			foreach (RectTransform componentsInChild in ((Component)_panel).GetComponentsInChildren<RectTransform>(false))
			{
				if (!((Object)(object)componentsInChild == (Object)null) && !((Object)(object)componentsInChild == (Object)(object)_panel))
				{
					Rect rect = componentsInChild.rect;
					float y = ((Transform)_panel).InverseTransformPoint(((Transform)componentsInChild).TransformPoint(new Vector3(((Rect)(ref rect)).xMin, ((Rect)(ref rect)).yMin, 0f))).y;
					if (y < num)
					{
						num = y;
					}
				}
			}
			Rect rect2 = _panel.rect;
			float yMax = ((Rect)(ref rect2)).yMax;
			rect2 = _viewport.rect;
			float num2 = Mathf.Max(((Rect)(ref rect2)).height, yMax - num + 20f);
			if (Mathf.Abs(_panel.sizeDelta.y - num2) > 1f)
			{
				_panel.sizeDelta = new Vector2(0f, num2);
			}
		}
	}
	[HarmonyPatch(typeof(ManagementInterface), "InitializeConfigPanel")]
	internal static class ConfigPanelScrollPatch
	{
		private static void Postfix(ManagementInterface __instance)
		{
			try
			{
				ClipboardScroll.Wrap(__instance);
			}
			catch (Exception ex)
			{
				Mod.Warn("Clipboard scroll failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(ManagementInterface), "DestroyConfigPanel")]
	internal static class ConfigPanelScrollCleanup
	{
		private static void Postfix()
		{
			ClipboardScroll.Cleanup();
		}
	}
	internal class DealerInfo
	{
		public Dealer Dealer;

		public string Name;

		public string Home;

		public string Region;

		public float Cash;

		public List<string> Customers = new List<string>();

		public int MaxCustomers;

		public List<(string id, string name, int units)> Product = new List<(string, string, int)>();

		public int OtherItems;
	}
	internal static class Dealers
	{
		private static readonly Dictionary<string, (IntPtr dealer, bool add, float until)> PendingCust = new Dictionary<string, (IntPtr, bool, float)>();

		private static readonly Dictionary<IntPtr, float> Collected = new Dictionary<IntPtr, float>();

		internal static List<DealerInfo> Recruited()
		{
			//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)
			List<DealerInfo> list = new List<DealerInfo>();
			if (Dealer.AllPlayerDealers == null)
			{
				return list;
			}
			int maxCustomers = MaxCustomers();
			Enumerator<Dealer> enumerator = Dealer.AllPlayerDealers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dealer current = enumerator.Current;
				if ((Object)(object)current == (Object)null || !current.IsRecruited)
				{
					continue;
				}
				DealerInfo dealerInfo = new DealerInfo
				{
					Dealer = current,
					Name = ((NPC)current).FullName,
					Cash = current.Cash,
					MaxCustomers = maxCustomers
				};
				try
				{
					dealerInfo.Home = (((Object)(object)current.Home != (Object)null) ? current.Home.BuildingName : null);
				}
				catch
				{
				}
				try
				{
					dealerInfo.Region = ((object)((NPC)current).Region/*cast due to .constrained prefix*/).ToString();
				}
				catch
				{
				}
				if (current.AssignedCustomers != null)
				{
					Enumerator<Customer> enumerator2 = current.AssignedCustomers.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						Customer current2 = enumerator2.Current;
						if ((Object)(object)current2 != (Object)null && (Object)(object)current2.NPC != (Object)null)
						{
							dealerInfo.Customers.Add(current2.NPC.FullName);
						}
					}
				}
				dealerInfo.Customers.Sort();
				Dictionary<string, (string, int)> dictionary = new Dictionary<string, (string, int)>();
				try
				{
					Enumerator<ItemSlot> enumerator3 = current.GetAllSlots().GetEnumerator();
					while (enumerator3.MoveNext())
					{
						ItemSlot current3 = enumerator3.Current;
						ItemInstance val = ((current3 != null) ? current3.ItemInstance : null);
						if (val != null && current3.Quantity > 0)
						{
							ProductItemInstance val2 = ((Il2CppObjectBase)val).TryCast<ProductItemInstance>();
							if (val2 == null)
							{
								dealerInfo.OtherItems += current3.Quantity;
								continue;
							}
							int num = Math.Max(1, val2.Amount);
							(string, int) value;
							int num2 = (dictionary.TryGetValue(((BaseItemInstance)val2).ID, out value) ? value.Item2 : 0);
							dictionary[((BaseItemInstance)val2).ID] = (((BaseItemInstance)val2).Name, num2 + current3.Quantity * num);
						}
					}
				}
				catch (Exception ex)
				{
					Mod.Warn("Could not read dealer inventory: " + ex.Message);
				}
				dealerInfo.Product = (from kv in dictionary
					orderby kv.Value.units descending
					select (Key: kv.Key, name: kv.Value.name, units: kv.Value.units)).ToList();
				list.Add(dealerInfo);
			}
			return list.OrderBy((DealerInfo x) => x.Name).ToList();
		}

		internal static int MaxCustomers()
		{
			int num = 10;
			try
			{
				num = Dealer.MAX_CUSTOMERS;
			}
			catch
			{
			}
			if (!Mod.EnableDealerLimit.Value)
			{
				return num;
			}
			return Math.Max(num, Mod.DealerLimit.Value);
		}

		internal unsafe static (int assigned, SortedDictionary<string, int> left) AssignByArea(bool dryRun)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();
			int num = 0;
			if (Dealer.AllPlayerDealers == null || Customer.UnlockedCustomers == null)
			{
				return (assigned: 0, left: sortedDictionary);
			}
			int num2 = MaxCustomers();
			List<Dealer> list = new List<Dealer>();
			Dictionary<IntPtr, int> dictionary = new Dictionary<IntPtr, int>();
			Enumerator<Dealer> enumerator = Dealer.AllPlayerDealers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dealer current = enumerator.Current;
				if ((Object)(object)current != (Object)null && current.IsRecruited)
				{
					list.Add(current);
					dictionary[((Il2CppObjectBase)current).Pointer] = (current.AssignedCustomers?.Count ?? 0) + PendingAdds(current);
				}
			}
			Enumerator<Customer> enumerator2 = Customer.UnlockedCustomers.GetEnumerator();
			while (enumerator2.MoveNext())
			{
				Customer current2 = enumerator2.Current;
				if ((Object)(object)current2 == (Object)null || (Object)(object)current2.NPC == (Object)null || (Object)(object)current2.AssignedDealer != (Object)null || IsPending(current2))
				{
					continue;
				}
				EMapRegion region = current2.NPC.Region;
				Dealer val = null;
				foreach (Dealer item in list)
				{
					if (((NPC)item).Region == region && dictionary[((Il2CppObjectBase)item).Pointer] < num2 && ((Object)(object)val == (Object)null || dictionary[((Il2CppObjectBase)item).Pointer] < dictionary[((Il2CppObjectBase)val).Pointer]))
					{
						val = item;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					string key = ((object)(*(EMapRegion*)(&region))/*cast due to .constrained prefix*/).ToString();
					sortedDictionary[key] = (sortedDictionary.TryGetValue(key, out var value) ? value : 0) + 1;
					continue;
				}
				if (!dryRun)
				{
					AddCustomer(val, current2);
				}
				dictionary[((Il2CppObjectBase)val).Pointer]++;
				num++;
			}
			return (assigned: num, left: sortedDictionary);
		}

		internal static List<Customer> Unassigned(Dealer d, bool allRegions)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			List<Customer> list = new List<Customer>();
			if (Customer.UnlockedCustomers == null)
			{
				return list;
			}
			Enumerator<Customer> enumerator = Customer.UnlockedCustomers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Customer current = enumerator.Current;
				if ((Object)(object)current != (Object)null && (Object)(object)current.NPC != (Object)null && (Object)(object)current.AssignedDealer == (Object)null && !IsPending(current) && (allRegions || current.NPC.Region == ((NPC)d).Region))
				{
					list.Add(current);
				}
			}
			return (from c in list
				orderby c.NPC.Region != ((NPC)d).Region, c.NPC.FullName
				select c).ToList();
		}

		internal static List<Customer> Assigned(Dealer d)
		{
			List<Customer> list = new List<Customer>();
			if (d.AssignedCustomers != null)
			{
				Enumerator<Customer> enumerator = d.AssignedCustomers.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Customer current = enumerator.Current;
					if ((Object)(object)current != (Object)null && (Object)(object)current.NPC != (Object)null)
					{
						list.Add(current);
					}
				}
			}
			return list.OrderBy((Customer c) => c.NPC.FullName).ToList();
		}

		internal static int PendingAdds(Dealer d)
		{
			int num = 0;
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			foreach (var value in PendingCust.Values)
			{
				if (value.dealer == ((Il2CppObjectBase)d).Pointer && value.add && realtimeSinceStartup < value.until)
				{
					num++;
				}
			}
			return num;
		}

		internal static bool IsPending(Customer c)
		{
			if (PendingCust.TryGetValue(c.NPC.ID, out (IntPtr, bool, float) value))
			{
				return Time.realtimeSinceStartup < value.Item3;
			}
			return false;
		}

		internal static void AddCustomer(Dealer d, Customer c)
		{
			if (!IsPending(c) && !((Object)(object)c.AssignedDealer != (Object)null))
			{
				PendingCust[c.NPC.ID] = (((Il2CppObjectBase)d).Pointer, true, Time.realtimeSinceStartup + 5f);
				d.AddCustomer_Server(c.NPC.ID);
			}
		}

		internal static void RemoveCustomer(Dealer d, Customer c)
		{
			if (!IsPending(c))
			{
				PendingCust[c.NPC.ID] = (((Il2CppObjectBase)d).Pointer, false, Time.realtimeSinceStartup + 5f);
				d.SendRemoveCustomer(c.NPC.ID);
			}
		}

		internal static float Collect(Dealer d)
		{
			if ((Object)(object)d == (Object)null || d.Cash <= 0f)
			{
				return 0f;
			}
			if (Collected.TryGetValue(((Il2CppObjectBase)d).Pointer, out var value) && Time.realtimeSinceStartup < value)
			{
				return 0f;
			}
			Collected[((Il2CppObjectBase)d).Pointer] = Time.realtimeSinceStartup + 5f;
			float cash = d.Cash;
			d.CollectCash();
			if (d.Cash > 0.01f)
			{
				d.SetCash(0f);
			}
			return cash;
		}

		private static int Room(Dealer d, ItemInstance item)
		{
			int num = 0;
			Enumerator<ItemSlot> enumerator = d.GetAllSlots().GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				if (current != null && !current.IsLocked)
				{
					num += Math.Max(0, current.GetCapacityForItem(item, false));
				}
			}
			return num;
		}

		internal static int Restock(Dealer d, Property from, Dictionary<string, int> missing, out string msg)
		{
			msg = null;
			int num = 0;
			foreach (KeyValuePair<string, int> item in missing)
			{
				int num2 = item.Value;
				foreach (ItemSlot item2 in Transfers.Slots(from).ToList())
				{
					if (num2 <= 0)
					{
						break;
					}
					ItemInstance itemInstance = item2.ItemInstance;
					ProductItemInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
					if (val != null && !(((BaseItemInstance)val).ID != item.Key) && !string.IsNullOrEmpty(val.PackagingID) && item2.Quantity > 0)
					{
						int num3 = Math.Max(1, val.Amount);
						int num4 = Room(d, item2.ItemInstance);
						if (num4 <= 0)
						{
							msg = "their inventory is full";
							break;
						}
						int num5 = Math.Min(Math.Min((num2 + num3 - 1) / num3, item2.Quantity), num4);
						d.AddItemToInventory(item2.ItemInstance.GetCopy(num5));
						item2.ChangeQuantity(-num5, false);
						num2 -= num5 * num3;
						num += num5 * num3;
					}
				}
				if (num2 > 0 && msg == null)
				{
					msg = "not enough packed product on the shelves";
				}
			}
			return num;
		}

		internal static int Give(Dealer d, Property from, string key, int qty, out string msg)
		{
			msg = null;
			int num = 0;
			foreach (ItemSlot item in Transfers.Slots(from).ToList())
			{
				if (num >= qty)
				{
					break;
				}
				if (!(Transfers.Key(item.ItemInstance) != key))
				{
					int num2 = Room(d, item.ItemInstance);
					if (num2 <= 0)
					{
						msg = "their inventory is full";
						break;
					}
					int num3 = Math.Min(Math.Min(qty - num, item.Quantity), num2);
					d.AddItemToInventory(item.ItemInstance.GetCopy(num3));
					item.ChangeQuantity(-num3, false);
					num += num3;
				}
			}
			if (num == 0 && msg == null)
			{
				msg = "none left on the shelves";
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(DealerManagementApp), "SetDisplayedDealer")]
	internal static class DealerAppLimitPatch
	{
		private static void Postfix(DealerManagementApp __instance, Dealer dealer)
		{
			try
			{
				if (Mod.EnableDealerLimit.Value && !((Object)(object)dealer == (Object)null))
				{
					int num = dealer.AssignedCustomers?.Count ?? 0;
					int num2 = Dealers.MaxCustomers();
					if ((Object)(object)__instance.AssignCustomerButton != (Object)null)
					{
						((Component)__instance.AssignCustomerButton).gameObject.SetActive(num < num2);
					}
					if ((Object)(object)__instance.CustomerTitleLabel != (Object)null)
					{
						__instance.CustomerTitleLabel.text = $"Assigned Customers ({num}/{num2})";
					}
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Dealer app limit failed: " + ex.Message);
			}
		}
	}
	internal static class DealNotifications
	{
		private static readonly Dictionary<IntPtr, float> Silent = new Dictionary<IntPtr, float>();

		internal static bool CompletingRemotely;

		internal static void SilenceOffer(Customer c)
		{
			if (Mod.AutoAcceptDeals.Value && Mod.MuteOfferTexts.Value && Net.IsHost)
			{
				object obj;
				if (c == null)
				{
					obj = null;
				}
				else
				{
					NPC nPC = c.NPC;
					obj = ((nPC != null) ? nPC.MSGConversation : null);
				}
				MSGConversation val = (MSGConversation)obj;
				if (val != null)
				{
					Silent[((Il2CppObjectBase)val).Pointer] = Time.realtimeSinceStartup + 6f;
				}
			}
		}

		internal static bool IsSilent(MSGConversation conv)
		{
			if (conv == null || !Silent.TryGetValue(((Il2CppObjectBase)conv).Pointer, out var value))
			{
				return false;
			}
			if (Time.realtimeSinceStartup <= value)
			{
				return true;
			}
			Silent.Remove(((Il2CppObjectBase)conv).Pointer);
			return false;
		}
	}
	[HarmonyPatch(typeof(Customer), "NotifyPlayerOfContract")]
	internal static class SilenceOfferPatch
	{
		private static void Prefix(Customer __instance, bool canAccept)
		{
			if (canAccept)
			{
				DealNotifications.SilenceOffer(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(MSGConversation), "SendMessage")]
	internal static class SilentMessagePatch
	{
		private static bool _inside;

		private static bool Prefix(MSGConversation __instance, Message message, bool notify, bool network)
		{
			if (_inside || !notify || !DealNotifications.IsSilent(__instance))
			{
				return true;
			}
			_inside = true;
			try
			{
				__instance.SendMessage(message, false, network);
			}
			finally
			{
				_inside = false;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(DealCompletionPopup), "PlayPopup")]
	internal static class RemoteCompletePopupPatch
	{
		private static bool Prefix()
		{
			if (DealNotifications.CompletingRemotely)
			{
				return !Mod.MuteRemoteCompletePopup.Value;
			}
			return true;
		}
	}
	internal class LinePlan
	{
		public List<(PackType type, int count)> Packs = new List<(PackType, int)>();

		public int Short;

		public int Lost;
	}
	internal class ProductPlan
	{
		public string Id;

		public string Name;

		public int Units;

		public int Short;

		public int Lost;

		public Dictionary<string, (PackType type, int count)> Bring = new Dictionary<string, (PackType, int)>();

		public Dictionary<string, (PackType type, int count)> Have = new Dictionary<string, (PackType, int)>();
	}
	internal static class DealPlanner
	{
		internal static (Dictionary<(DealInfo deal, int line), LinePlan> lines, List<ProductPlan> products) Plan(List<DealInfo> deals, Dictionary<(string, string), int> have)
		{
			Dictionary<(DealInfo, int), LinePlan> dictionary = new Dictionary<(DealInfo, int), LinePlan>();
			Dictionary<string, ProductPlan> dictionary2 = new Dictionary<string, ProductPlan>();
			Dictionary<(string, string), int> dictionary3 = ((have != null) ? new Dictionary<(string, string), int>(have) : null);
			List<PackType> types = Packing.Types().Where(Packing.IsEnabled).ToList();
			foreach (DealInfo deal in deals)
			{
				for (int i = 0; i < deal.Items.Count; i++)
				{
					(string, string, int, string) tuple = deal.Items[i];
					if (!dictionary2.TryGetValue(tuple.Item1, out var value))
					{
						string item = tuple.Item1;
						ProductPlan obj = new ProductPlan
						{
							Id = tuple.Item1,
							Name = tuple.Item2
						};
						ProductPlan productPlan = obj;
						dictionary2[item] = obj;
						value = productPlan;
						if (have != null)
						{
							foreach (PackType item2 in Packing.Types())
							{
								if (have.TryGetValue((tuple.Item1, item2.Id), out var value2) && value2 > 0)
								{
									value.Have[item2.Id] = (item2, value2);
								}
							}
						}
					}
					value.Units += tuple.Item3;
					LinePlan linePlan = Best(tuple.Item1, tuple.Item3, types, dictionary3);
					foreach (var (packType, num) in linePlan.Packs)
					{
						if (dictionary3 != null)
						{
							dictionary3[(tuple.Item1, packType.Id)] = (dictionary3.TryGetValue((tuple.Item1, packType.Id), out var value3) ? value3 : 0) - num;
						}
						value.Bring[packType.Id] = (packType, (value.Bring.TryGetValue(packType.Id, out (PackType, int) value4) ? value4.Item2 : 0) + num);
					}
					value.Short += linePlan.Short;
					value.Lost += linePlan.Lost;
					dictionary[(deal, i)] = linePlan;
				}
			}
			return (lines: dictionary, products: dictionary2.Values.ToList());
		}

		internal static LinePlan Best(string id, int qty, List<PackType> types, Dictionary<(string, string), int> left)
		{
			int allow = Math.Max(0, Mod.OverpackMax.Value);
			int[] counts = new int[types.Count];
			int[] best = null;
			(int shortU, int over, int packs, int lost) bestKey = (shortU: int.MaxValue, over: 0, packs: 0, lost: 0);
			Try(0, qty, 0);
			LinePlan linePlan = new LinePlan
			{
				Short = bestKey.shortU,
				Lost = bestKey.lost
			};
			for (int i = 0; i < types.Count; i++)
			{
				if (best[i] > 0)
				{
					linePlan.Packs.Add((types[i], best[i]));
				}
			}
			return linePlan;
			void Try(int num, int rem, int packs)
			{
				if (num == types.Count || rem <= 0)
				{
					int item = Math.Max(0, rem);
					int num2 = Math.Max(0, -rem);
					(int, int, int, int) tuple = (item, (num2 > allow) ? 1 : 0, packs, num2);
					if (best == null || tuple.CompareTo(bestKey) < 0)
					{
						best = (int[])counts.Clone();
						bestKey = tuple;
					}
				}
				else
				{
					PackType packType = types[num];
					int num3 = (rem + packType.Size - 1) / packType.Size;
					if (left != null)
					{
						num3 = Math.Min(num3, left.TryGetValue((id, packType.Id), out var value) ? Math.Max(0, value) : 0);
					}
					int num4 = ((num == types.Count - 1) ? num3 : 0);
					for (int num5 = num3; num5 >= num4; num5--)
					{
						counts[num] = num5;
						Try(num + 1, rem - num5 * packType.Size, packs + num5);
					}
					counts[num] = 0;
				}
			}
		}

		internal static Dictionary<(string, string), int> CountPacked()
		{
			Dictionary<(string, string), int> counts = new Dictionary<(string, string), int>();
			try
			{
				PlayerInventory instance = PlayerSingleton<PlayerInventory>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					Enumerator<HotbarSlot> enumerator = instance.hotbarSlots.GetEnumerator();
					while (enumerator.MoveNext())
					{
						HotbarSlot current = enumerator.Current;
						if (current != null)
						{
							Add(((ItemSlot)current).ItemInstance);
						}
					}
				}
				foreach (Property item in Stock.OwnedProperties())
				{
					foreach (ItemInstance item2 in Stock.Items(item))
					{
						Add(item2);
					}
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not count packed product: " + ex.Message);
			}
			return counts;
			void Add(ItemInstance item)
			{
				ProductItemInstance val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<ProductItemInstance>() : null);
				if (val != null && !string.IsNullOrEmpty(val.PackagingID))
				{
					(string, string) key = (((BaseItemInstance)val).ID, val.PackagingID);
					counts[key] = (counts.TryGetValue(key, out var value) ? value : 0) + ((BaseItemInstance)val).Quantity;
				}
			}
		}

		internal static string Describe(IEnumerable<(PackType type, int count)> packs, int shortUnits, bool shortIsStock)
		{
			List<string> list = (from p in packs
				where p.count > 0
				orderby p.type.Size descending
				select $"{p.count} {((p.count == 1) ? p.type.Name.ToLowerInvariant() : (p.type.Name.ToLowerInvariant() + "s"))}").ToList();
			if (shortUnits > 0)
			{
				list.Add(shortIsStock ? $"short {shortUnits} units" : $"{shortUnits} can't be packed");
			}
			if (list.Count != 0)
			{
				return string.Join(", ", list);
			}
			return "nothing";
		}
	}
	internal class DealInfo
	{
		public Contract Contract;

		public string Customer;

		public string Dealer;

		public float Payment;

		public string Location;

		public int WindowStart;

		public int WindowEnd;

		public string ExpiryText;

		public int MinsUntilExpiry;

		public bool Tracked;

		public List<(string id, string name, int qty, string quality)> Items = new List<(string, string, int, string)>();
	}
	internal static class Deals
	{
		internal static List<DealInfo> Active()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			//IL_01ad: 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)
			List<DealInfo> list = new List<DealInfo>();
			if (Contract.Contracts == null)
			{
				return list;
			}
			Enumerator<Contract> enumerator = Contract.Contracts.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Contract current = enumerator.Current;
				if ((Object)(object)current == (Object)null || (int)((Quest)current).State != 1)
				{
					continue;
				}
				DealInfo dealInfo = new DealInfo
				{
					Contract = current,
					Payment = current.Payment,
					Dealer = (((Object)(object)current.Dealer != (Object)null) ? ((NPC)current.Dealer).FullName : null),
					Tracked = ((Quest)current).IsTracked
				};
				try
				{
					Customer val = (((Object)(object)current.Customer != (Object)null) ? ((Component)current.Customer).GetComponent<Customer>() : null);
					dealInfo.Customer = (((Object)(object)val != (Object)null && (Object)(object)val.NPC != (Object)null) ? val.NPC.FullName : ((Quest)current).Title);
				}
				catch
				{
					dealInfo.Customer = ((Quest)current).Title;
				}
				if ((Object)(object)current.DeliveryLocation != (Object)null)
				{
					dealInfo.Location = current.DeliveryLocation.LocationName;
				}
				if (current.DeliveryWindow != null)
				{
					dealInfo.WindowStart = current.DeliveryWindow.WindowStartTime;
					dealInfo.WindowEnd = current.DeliveryWindow.WindowEndTime;
				}
				try
				{
					dealInfo.MinsUntilExpiry = ((Quest)current).GetMinsUntilExpiry();
					dealInfo.ExpiryText = ((Quest)current).GetExpiryText();
				}
				catch
				{
					dealInfo.MinsUntilExpiry = int.MaxValue;
				}
				if (current.ProductList != null && current.ProductList.entries != null)
				{
					Enumerator<Entry> enumerator2 = current.ProductList.entries.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						Entry current2 = enumerator2.Current;
						dealInfo.Items.Add((current2.ProductID, AutoOrders.ItemName(current2.ProductID), current2.Quantity, ((object)current2.Quality/*cast due to .constrained prefix*/).ToString()));
					}
				}
				list.Add(dealInfo);
			}
			return (from x in list
				orderby x.Dealer != null, x.WindowStart, x.MinsUntilExpiry
				select x).ToList();
		}

		internal static string Time(int hhmm)
		{
			return $"{hhmm / 100 % 24:00}:{hhmm % 100:00}";
		}
	}
	[HarmonyPatch(typeof(DeliveryShop), "GetDeliveryTime")]
	internal static class DeliveryTimePatch
	{
		internal const float InstantSpeed = 100f;

		internal static bool Instant => Mod.DeliverySpeed.Value >= 100f;

		private static void Postfix(ref int __result)
		{
			if (Guest.On(Mod.EnableDeliverySpeed))
			{
				if (Instant)
				{
					__result = 1;
					return;
				}
				float num = Math.Max(0.25f, Mod.DeliverySpeed.Value);
				__result = Math.Max(1, (int)Math.Round((float)__result / num));
			}
		}
	}
	internal class EconomySnapshot
	{
		public int Customers;

		public int CustomersWithDealer;

		public float WeeklySpendVanilla;

		public float WeeklySpendModded;

		public float LaunderPerDay;

		public float LaunderPerDayVanilla;

		public float LaunderInProgress;

		public List<(string name, float capacity)> Businesses = new List<(string, float)>();
	}
	internal static class Economy
	{
		private static readonly Dictionary<IntPtr, float> OriginalCapacity = new Dictionary<IntPtr, float>();

		internal static void ApplyLaunder()
		{
			if (Business.Businesses == null)
			{
				return;
			}
			float num = (Guest.On(Mod.EnableLaunder) ? Math.Max(0.1f, Mod.LaunderMultiplier.Value) : 1f);
			Enumerator<Business> enumerator = Business.Businesses.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Business current = enumerator.Current;
				if (!((Object)(object)current == (Object)null))
				{
					if (!OriginalCapacity.TryGetValue(((Il2CppObjectBase)current).Pointer, out var value))
					{
						float num2 = (OriginalCapacity[((Il2CppObjectBase)current).Pointer] = current.LaunderCapacity);
						value = num2;
					}
					current.LaunderCapacity = value * num;
				}
			}
		}

		internal static void Reset()
		{
			OriginalCapacity.Clear();
		}

		internal static EconomySnapshot Snapshot()
		{
			EconomySnapshot economySnapshot = new EconomySnapshot();
			float num = Prices.Factor();
			if (Customer.UnlockedCustomers != null)
			{
				Enumerator<Customer> enumerator = Customer.UnlockedCustomers.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Customer current = enumerator.Current;
					if (!((Object)(object)current == (Object)null) && !((Object)(object)current.customerData == (Object)null))
					{
						economySnapshot.Customers++;
						if ((Object)(object)current.AssignedDealer != (Object)null)
						{
							economySnapshot.CustomersWithDealer++;
						}
						float num2 = 0f;
						try
						{
							num2 = current.NPC.RelationData.NormalizedRelationDelta;
						}
						catch
						{
						}
						float adjustedWeeklySpend = current.customerData.GetAdjustedWeeklySpend(num2);
						economySnapshot.WeeklySpendModded += adjustedWeeklySpend;
						economySnapshot.WeeklySpendVanilla += ((num > 0f) ? (adjustedWeeklySpend / num) : adjustedWeeklySpend);
					}
				}
			}
			if (Business.OwnedBusinesses != null)
			{
				Enumerator<Business> enumerator2 = Business.OwnedBusinesses.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					Business current2 = enumerator2.Current;
					if ((Object)(object)current2 == (Object)null)
					{
						continue;
					}
					economySnapshot.LaunderPerDay += current2.LaunderCapacity;
					economySnapshot.LaunderPerDayVanilla += (OriginalCapacity.TryGetValue(((Il2CppObjectBase)current2).Pointer, out var value) ? value : current2.LaunderCapacity);
					economySnapshot.Businesses.Add((((Property)current2).PropertyName, current2.LaunderCapacity));
					if (current2.LaunderingOperations == null)
					{
						continue;
					}
					Enumerator<LaunderingOperation> enumerator3 = current2.LaunderingOperations.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						LaunderingOperation current3 = enumerator3.Current;
						if (current3 != null)
						{
							economySnapshot.LaunderInProgress += current3.amount;
						}
					}
				}
			}
			return economySnapshot;
		}
	}
	internal static class EmployeeTweaks
	{
		internal class TypeSettings
		{
			public string Key;

			public string Name;

			public string CapacityName;

			public MelonPreferences_Entry<float> Work;

			public MelonPreferences_Entry<float> Walk;

			public MelonPreferences_Entry<int> MaxItems;

			public MelonPreferences_Entry<int> MaxRoutes;

			public int GameItems = -1;

			public int GameRoutes = -1;
		}

		[HarmonyPatch(typeof(EmployeeManager), "CreateEmployee_Server")]
		internal static class CreateEmployeePatch
		{
			private static void Prefix(Property property)
			{
				ApplyCapacity(property, Guest.On(Mod.EnableEmployeeTweaks));
				try
				{
					LoadManager instance = Singleton<LoadManager>.Instance;
					if ((Object)(object)property != (Object)null && (Object)(object)instance != (Object)null && !instance.IsGameLoaded && property.Employees != null && property.EmployeeCapacity <= property.Employees.Count)
					{
						property.EmployeeCapacity = property.Employees.Count + 1;
					}
				}
				catch
				{
				}
			}
		}

		internal static readonly List<TypeSettings> Types = new List<TypeSettings>();

		private static MelonPreferences_Entry<string> _propertyStaffJson;

		private static Dictionary<string, int> _propertyStaff;

		private const string Label = "ScheduleTweaks";

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

		private static readonly Dictionary<IntPtr, float> WorkApplied = new Dictionary<IntPtr, float>();

		private static readonly Dictionary<IntPtr, float> WalkApplied = new Dictionary<IntPtr, float>();

		private static float _next;

		private static Dictionary<string, int> PropertyStaff
		{
			get
			{
				if (_propertyStaff != null)
				{
					return _propertyStaff;
				}
				try
				{
					_propertyStaff = JsonSerializer.Deserialize<Dictionary<string, int>>(_propertyStaffJson.Value);
				}
				catch
				{
				}
				return _propertyStaff ?? (_propertyStaff = new Dictionary<string, int>());
			}
		}

		internal static void CreatePrefs(MelonPreferences_Category c)
		{
			Add("Botanist", "Botanists", "Pots", routes: false);
			Add("Chemist", "Chemists", "Stations", routes: false);
			Add("Handler", "Handlers", "Stations", routes: true);
			Add("Cleaner", "Cleaners", "Bins", routes: false);
			_propertyStaffJson = c.CreateEntry<string>("PropertyStaffCounts", "{}", (string)null, "Workers per property, by property code (missing or 0 = game default).", false, false, (ValueValidator)null, (string)null);
			void Add(string key, string name, string capName, bool routes)
			{
				Types.Add(new TypeSettings
				{
					Key = key,
					Name = name,
					CapacityName = capName,
					Work = c.CreateEntry<float>(key + "WorkSpeed", 1f, (string)null, name + " work speed multiplier.", false, false, (ValueValidator)null, (string)null),
					Walk = c.CreateEntry<float>(key + "WalkSpeed", 1f, (string)null, name + " walk speed multiplier.", false, false, (ValueValidator)null, (string)null),
					MaxItems = c.CreateEntry<int>(key + "Max" + capName, 0, (string)null, name + ": max " + capName.ToLowerInvariant() + " per worker (0 = game default).", false, false, (ValueValidator)null, (string)null),
					MaxRoutes = (routes ? c.CreateEntry<int>(key + "MaxRoutes", 0, (string)null, name + ": max routes per worker (0 = game default).", false, false, (ValueValidator)null, (string)null) : null)
				});
			}
		}

		internal static int MaxPropertyStaff(string code)
		{
			return code switch
			{
				"sweatshop" => 5, 
				"storageunit" => 8, 
				"bungalow" => 10, 
				_ => 20, 
			};
		}

		internal static int GetPropertyStaff(string code)
		{
			if (!PropertyStaff.TryGetValue(code, out var value))
			{
				return 0;
			}
			return Math.Min(value, MaxPropertyStaff(code));
		}

		internal static void SetPropertyStaff(string code, int value)
		{
			if (value <= 0)
			{
				PropertyStaff.Remove(code);
			}
			else
			{
				PropertyStaff[code] = value;
			}
			_propertyStaffJson.Value = JsonSerializer.Serialize(PropertyStaff);
			Mod.Prefs.SaveToFile(false);
			Tick(force: true);
		}

		internal static int GamePropertyStaff(Property p)
		{
			if (!OrigI.TryGetValue((((Il2CppObjectBase)p).Pointer, "capacity"), out var value))
			{
				return p.EmployeeCapacity;
			}
			return value;
		}

		private static int Limit(IntPtr key, string name, int current, int wanted, bool on, Action<int> learn = null)
		{
			if (!OrigI.TryGetValue((key, name), out var value))
			{
				int num = (OrigI[(key, name)] = current);
				value = num;
				learn?.Invoke(value);
			}
			if (!on || wanted <= 0)
			{
				return value;
			}
			return wanted;
		}

		internal static void Tick(bool force = false)
		{
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			if (!force && Time.realtimeSinceStartup < _next)
			{
				return;
			}
			_next = Time.realtimeSinceStartup + 3f;
			if (!Net.IsHost)
			{
				return;
			}
			bool flag = Guest.On(Mod.EnableEmployeeTweaks);
			foreach (Employee item in Staff.All())
			{
				IntPtr pointer = ((Il2CppObjectBase)item).Pointer;
				TypeSettings t = TypeOf(item);
				if (t == null)
				{
					continue;
				}
				float num = (flag ? t.Work.Value : 1f);
				float num2 = (flag ? t.Walk.Value : 1f);
				int value = t.MaxItems.Value;
				int wanted = t.MaxRoutes?.Value ?? 0;
				Action<int> learn = delegate(int v)
				{
					if (t.GameItems < 0)
					{
						t.GameItems = v;
					}
				};
				if (item.WorkSpeedController != null && (!WorkApplied.TryGetValue(pointer, out var value2) || !Mathf.Approximately(value2, num)))
				{
					item.WorkSpeedController.Remove("ScheduleTweaks");
					if (!Mathf.Approximately(num, 1f))
					{
						item.WorkSpeedController.Add(new StackEntry("ScheduleTweaks", num, (EStackMode)2, 100));
					}
					WorkApplied[pointer] = num;
				}
				if (!WalkApplied.TryGetValue(((Il2CppObjectBase)item).Pointer, out var value3) || !Mathf.Approximately(value3, num2))
				{
					NPCMovement movement = ((NPC)item).Movement;
					if (movement != null)
					{
						NPCSpeedController speedController = movement.SpeedController;
						if (speedController != null)
						{
							speedController.SetSpeedMultiplier(num2);
						}
					}
					WalkApplied[((Il2CppObjectBase)item).Pointer] = num2;
				}
				switch (t.Key)
				{
				case "Botanist":
				{
					Botanist val2 = ((Il2CppObjectBase)item).TryCast<Botanist>();
					if (!((Object)(object)val2 == (Object)null))
					{
						val2.MaxAssignedPots = Limit(pointer, "pots", val2.MaxAssignedPots, value, flag, learn);
						BotanistConfiguration configuration2 = val2.configuration;
						if (((configuration2 != null) ? configuration2.Assigns : null) != null)
						{
							val2.configuration.Assigns.MaxItems = Limit(pointer, "assigns", val2.configuration.Assigns.MaxItems, value, flag);
						}
					}
					break;
				}
				case "Chemist":
				{
					Chemist val3 = ((Il2CppObjectBase)item).TryCast<Chemist>();
					object obj2;
					if (val3 == null)
					{
						obj2 = null;
					}
					else
					{
						ChemistConfiguration configuration3 = val3.configuration;
						obj2 = ((configuration3 != null) ? configuration3.Stations : null);
					}
					if (obj2 != null)
					{
						val3.configuration.Stations.MaxItems = Limit(pointer, "stations", val3.configuration.Stations.MaxItems, value, flag, learn);
					}
					break;
				}
				case "Handler":
				{
					Packager val4 = ((Il2CppObjectBase)item).TryCast<Packager>();
					if ((Object)(object)val4 == (Object)null)
					{
						break;
					}
					val4.MaxAssignedStations = Limit(pointer, "maxstations", val4.MaxAssignedStations, value, flag, learn);
					PackagerConfiguration configuration4 = val4.configuration;
					if (((configuration4 != null) ? configuration4.Stations : null) != null)
					{
						val4.configuration.Stations.MaxItems = Limit(pointer, "stations", val4.configuration.Stations.MaxItems, value, flag);
					}
					PackagerConfiguration configuration5 = val4.configuration;
					if (((configuration5 != null) ? configuration5.Routes : null) == null)
					{
						break;
					}
					val4.configuration.Routes.MaxRoutes = Limit(pointer, "routes", val4.configuration.Routes.MaxRoutes, wanted, flag, delegate(int v)
					{
						if (t.GameRoutes < 0)
						{
							t.GameRoutes = v;
						}
					});
					break;
				}
				case "Cleaner":
				{
					Cleaner val = ((Il2CppObjectBase)item).TryCast<Cleaner>();
					object obj;
					if (val == null)
					{
						obj = null;
					}
					else
					{
						CleanerConfiguration configuration = val.configuration;
						obj = ((configuration != null) ? configuration.Bins : null);
					}
					if (obj != null)
					{
						val.configuration.Bins.MaxItems = Limit(pointer, "bins", val.configuration.Bins.MaxItems, value, flag, learn);
					}
					break;
				}
				}
			}
			foreach (Property item2 in Stock.OwnedProperties())
			{
				ApplyCapacity(item2, flag);
			}
		}

		private static void ApplyCapacity(Property p, bool on)
		{
			if ((Object)(object)p != (Object)null)
			{
				p.EmployeeCapacity = Limit(((Il2CppObjectBase)p).Pointer, "capacity", p.EmployeeCapacity, GetPropertyStaff(p.PropertyCode), on);
			}
		}

		private static TypeSettings TypeOf(Employee e)
		{
			string key = (((Object)(object)((Il2CppObjectBase)e).TryCast<Botanist>() != (Object)null) ? "Botanist" : (((Object)(object)((Il2CppObjectBase)e).TryCast<Chemist>() != (Object)null) ? "Chemist" : (((Object)(object)((Il2CppObjectBase)e).TryCast<Packager>() != (Object)null) ? "Handler" : (((Object)(object)((Il2CppObjectBase)e).TryCast<Cleaner>() != (Object)null) ? "Cleaner" : null))));
			if (key != null)
			{
				return Types.Find((TypeSettings t) => t.Key == key);
			}
			return null;
		}

		internal static void Reset()
		{
			OrigI.Clear();
			WorkApplied.Clear();
			WalkApplied.Clear();
			foreach (TypeSettings type in Types)
			{
				type.GameItems = -1;
				type.GameRoutes = -1;
			}
			_next = 0f;
		}
	}
	[HarmonyPatch(typeof(Employee), "AssignProperty")]
	internal static class IdlePointsPatch
	{
		private const float MaxSpread = 8f;

		private const string SpotName = "ScheduleTweaks_IdlePoint";

		private static void Prefix(Property prop)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			Il2CppReferenceArray<Transform> val = ((prop != null) ? prop.EmployeeIdlePoints : null);
			if (val == null || ((Il2CppArrayBase<Transform>)(object)val).Length == 0)
			{
				return;
			}
			int num = Math.Max((prop.Employees?.Count ?? 0) + 1, Math.Max(prop.EmployeeCapacity, EmployeeTweaks.MaxPropertyStaff(prop.PropertyCode)));
			if (((Il2CppArrayBase<Transform>)(object)val).Length >= num)
			{
				return;
			}
			int length = ((Il2CppArrayBase<Transform>)(object)val).Length;
			List<Vector3> game = new List<Vector3>();
			foreach (Transform item in (Il2CppArrayBase<Transform>)(object)val)
			{
				if ((Object)(object)item != (Object)null && ((Object)item).name != "ScheduleTweaks_IdlePoint")
				{
					game.Add(item.position);
				}
			}
			if (game.Count == 0)
			{
				game.Add(((Il2CppArrayBase<Transform>)(object)val)[0].position);
			}
			Il2CppReferenceArray<Transform> val2 = new Il2CppReferenceArray<Transform>((long)num);
			List<Vector3> list = new List<Vector3>();
			for (int i = 0; i < length; i++)
			{
				((Il2CppArrayBase<Transform>)(object)val2)[i] = ((Il2CppArrayBase<Transform>)(object)val)[i];
				list.Add(((Il2CppArrayBase<Transform>)(object)val)[i].position);
			}
			int num2 = 0;
			for (int j = length; j < num; j++)
			{
				Transform val3 = null;
				for (int k = 0; k < j; k++)
				{
					if (!((Object)(object)val3 == (Object)null))
					{
						break;
					}
					Transform val4 = ((Il2CppArrayBase<Transform>)(object)val2)[k];
					Vector3? val5 = StaffIdle.FreeSpotNear(val4.position, val4.forward, list, (Vector3 p) => game.Exists((Vector3 g) => Vector3.Distance(g, p) <= 8f && Mathf.Abs(g.y - p.y) < 1f));
					if (val5.HasValue)
					{
						GameObject val6 = new GameObject("ScheduleTweaks_IdlePoint");
						val6.transform.SetParent(((Component)prop).transform, false);
						val6.transform.SetPositionAndRotation(val5.Value, val4.rotation);
						val3 = val6.transform;
					}
				}
				if ((Object)(object)val3 != (Object)null)
				{
					num2++;
				}
				((Il2CppArrayBase<Transform>)(object)val2)[j] = val3 ?? ((Il2CppArrayBase<Transform>)(object)val)[j % length];
				list.Add(((Il2CppArrayBase<Transform>)(object)val2)[j].position);
			}
			prop.EmployeeIdlePoints = val2;
			Mod.Log($"{prop.PropertyName}: {length} idle spots -> {num} ({num2} new" + ((num2 < num - length) ? $", {num - length - num2} share a spot: no more free space" : "") + ")");
		}
	}
	internal static class ExtraOutputs
	{
		internal const int Count = 19;

		private static readonly Dictionary<string, List<ItemSlot>> Slots = new Dictionary<string, List<ItemSlot>>();

		private static readonly Dictionary<string, BuildableItem> Owners = new Dictionary<string, BuildableItem>();

		private static Dictionary<string, List<string>> _saved = new Dictionary<string, List<string>>();

		private static float _nextRefill;

		private static float _nextOrphanToast;

		internal static void Load()
		{
			try
			{
				_saved = new Dictionary<string, List<string>>();
				string text = SaveFiles.Read("UnpackOutputs");
				if (text != null)
				{
					_saved = JsonSerializer.Deserialize<Dictionary<string, List<string>>>(text) ?? new Dictionary<string, List<string>>();
				}
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not read unpack outputs: " + ex.Message);
			}
		}

		private static string Id(BuildableItem b)
		{
			//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)
			return ((object)b.GUID/*cast due to .constrained prefix*/).ToString();
		}

		private static List<ItemSlot> StationOutputs(BuildableItem b)
		{
			BrickPress obj = ((Il2CppObjectBase)b).TryCast<BrickPress>();
			object obj2 = ((obj != null) ? obj.OutputSlots : null);
			if (obj2 == null)
			{
				PackagingStation obj3 = ((Il2CppObjectBase)b).TryCast<PackagingStation>();
				if (obj3 == null)
				{
					return null;
				}
				obj2 = obj3.OutputSlots;
			}
			return (List<ItemSlot>)obj2;
		}

		internal static List<ItemSlot> Get(BuildableItem b)
		{
			if (!((Object)(object)b != (Object)null) || !Slots.TryGetValue(Id(b), out var value))
			{
				return null;
			}
			return value;
		}

		internal static void Ensure(BuildableItem b)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			if (!Net.IsHost)
			{
				return;
			}
			string key = Id(b);
			bool flag = BrickUnpack.IsUnpack(b) || _saved.ContainsKey(key);
			if (Slots.TryGetValue(key, out var value))
			{
				if (flag || value.Any((ItemSlot s) => s.Quantity > 0))
				{
					return;
				}
				List<ItemSlot> val = StationOutputs(b);
				foreach (ItemSlot item2 in value)
				{
					val?.Remove(item2);
				}
				Slots.Remove(key);
				Owners.Remove(key);
			}
			else
			{
				if (!flag)
				{
					return;
				}
				List<ItemSlot> list = new List<ItemSlot>();
				List<ItemSlot> val2 = StationOutputs(b);
				for (int num = 0; num < 19; num++)
				{
					ItemSlot val3 = new ItemSlot();
					list.Add(val3);
					val2?.Add(val3);
				}
				if (_saved.TryGetValue(key, out var value2))
				{
					foreach (string item3 in value2)
					{
						try
						{
							ItemInstance item = ItemDeserializer.LoadItem(item3);
							if (item != null)
							{
								ItemSlot val4 = ((IEnumerable<ItemSlot>)list).FirstOrDefault((Func<ItemSlot, bool>)((ItemSlot s) => s.ItemInstance == null)) ?? ((IEnumerable<ItemSlot>)list).FirstOrDefault((Func<ItemSlot, bool>)((ItemSlot s) => s.GetCapacityForItem(item, false) >= ((BaseItemInstance)item).Quantity));
								if (val4 == null)
								{
									Mod.Warn("Unpack outputs: no room to restore " + ((BaseItemInstance)item).Name);
								}
								else if (val4.ItemInstance == null)
								{
									val4.SetStoredItem(item, false);
								}
								else
								{
									val4.InsertItem(item);
								}
							}
						}
						catch (Exception ex)
						{
							Mod.Warn("Unpack output restore failed: " + ex.Message);
						}
					}
					_saved.Remove(key);
				}
				Slots[key] = list;
				Owners[key] = b;
			}
		}

		internal static void Refill()
		{
			if (!Net.IsHost || Slots.Count == 0 || Time.realtimeSinceStartup < _nextRefill)
			{
				return;
			}
			_nextRefill = Time.realtimeSinceStartup + 0.5f;
			RescueOrphans();
			foreach (KeyValuePair<string, List<ItemSlot>> slot in Slots)
			{
				if (!Owners.TryGetValue(slot.Key, out var value) || (Object)(object)value == (Object)null)
				{
					continue;
				}
				BrickPress obj = ((Il2CppObjectBase)value).TryCast<BrickPress>();
				object obj2 = ((obj != null) ? obj.OutputSlot : null);
				if (obj2 == null)
				{
					PackagingStation obj3 = ((Il2CppObjectBase)value).TryCast<PackagingStation>();
					obj2 = ((obj3 != null) ? obj3.OutputSlot : null);
				}
				ItemSlot val = (ItemSlot)obj2;
				if (val == null || val.IsLocked)
				{
					continue;
				}
				foreach (ItemSlot item in slot.Value)
				{
					if (item.ItemInstance != null && item.Quantity > 0 && !item.IsLocked)
					{
						int num = Math.Min(item.Quantity, val.GetCapacityForItem(item.ItemInstance, false));
						if (num > 0)
						{
							val.InsertItem(item.ItemInstance.GetCopy(num));
							item.ChangeQuantity(-num, false);
						}
					}
				}
			}
		}

		private static void RescueOrphans()
		{
			if (Time.timeSinceLevelLoad < 15f)
			{
				return;
			}
			PlayerInventory instance = PlayerSingleton<PlayerInventory>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			foreach (string item in (from kv in Owners
				where (Object)(object)kv.Value == (Object)null
				select kv.Key).ToList())
			{
				List<ItemSlot> source = Slots[item];
				int num = 0;
				foreach (ItemSlot item2 in source.Where((ItemSlot x) => x.ItemInstance != null && x.Quantity > 0))
				{
					if (!instance.CanItemFitInInventory(item2.ItemInstance, item2.Quantity))
					{
						num += item2.Quantity;
						continue;
					}
					instance.AddItemToInventory(item2.ItemInstance.GetCopy(item2.Quantity));
					item2.ClearStoredInstance(false);
				}
				if (num == 0)
				{
					Slots.Remove(item);
					Owners.Remove(item);
					_saved.Remove(item);
					Ui.Toast("Unpack output from a removed station moved to your pockets");
				}
				else if (Time.realtimeSinceStartup > _nextOrphanToast)
				{
					_nextOrphanToast = Time.realtimeSinceStartup + 30f;
					Ui.Toast($"{num} packages from a removed station's unpack output are waiting: free some pocket space");
				}
			}
		}

		internal static void SaveAll()
		{
			Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(_saved);
			foreach (KeyValuePair<string, List<ItemSlot>> slot in Slots)
			{
				List<string> list = (from s in slot.Value
					where s.ItemInstance != null && s.Quantity > 0
					select ((SaveData)s.ItemInstance.GetCopy(s.Quantity).GetItemData()).GetJson(false)).ToList();
				if (list.Count > 0)
				{
					dictionary[slot.Key] = list;
				}
				else
				{
					dictionary.Remove(slot.Key);
				}
			}
			try
			{
				SaveFiles.Write("UnpackOutputs", JsonSerializer.Serialize(dictionary));
			}
			catch (Exception ex)
			{
				Mod.Warn("Could not save unpack outputs: " + ex.Message);
			}
		}

		internal static void Reset()
		{
			Slots.Clear();
			Owners.Clear();
			Load();
		}
	}
	[HarmonyPatch(typeof(SaveManager), "Save", new Type[] { typeof(string) })]
	internal static class ExtraOutputsSavePatch
	{
		private static void Prefix()
		{
			try
			{
				ExtraOutputs.SaveAll();
			}
			catch (Exception ex)
			{
				Mod.Warn("Unpack outputs save failed: " + ex.Message);
			}
		}
	}
	internal static class Guest
	{
		private static bool _last;

		private static float _next;

		internal static bool Active
		{
			get
			{
				try
				{
					return InstanceFinder.IsClient && !InstanceFinder.IsServer;
				}
				catch
				{
					return false;
				}
			}
		}

		internal static bool On(MelonPreferences_Entry<bool> entry)
		{
			if (entry.Value)
			{
				return !Active;
			}
			return false;
		}

		internal static void Tick()
		{
			if (!(Time.realtimeSinceStartup < _next))
			{
				_next = Time.realtimeSinceStartup + 3f;
				bool active = Active;
				if (active != _last)
				{
					_last = active;
					Mod.Log(active ? "Guest on another player's server: balance features paused." : "Hosting: balance features active.");
					Stacks.Apply();
					Economy.ApplyLaunder();
					Mixing.Tick(force: true);
				}
			}
		}

		internal static void Reset()
		{
			_last = false;
			_next = 0f;
		}
	}
	internal class LaunderJob
	{
		public float Amount;

		public int MinsLeft;

		public int MinsTotal;
	}
	internal class LaunderInfo
	{
		public Business Business;

		public string Name;

		public float Capacity;

		public float InProgress;

		public List<LaunderJob> Jobs = new List<LaunderJob>();

		public float Free => Math.Max(0f, Capacity - InProgress);
	}
	internal static class Launder
	{
		private static readonly Dictionary<IntPtr, List<(float amount, int opsBefore, float until)>> Pending = new Dictionary<IntPtr, List<(float, int, float)>>();

		private static float _autoReadyAt;

		internal static void OnSaveLoaded()
		{
			_autoReadyAt = Time.realtimeSinceStartup + 60f;
			Pending.Clear();
		}

		internal static List<LaunderInfo> Owned()
		{
			List<LaunderInfo> list = new List<LaunderInfo>();
			if (Business.OwnedBusinesses == null)
			{
				return list;
			}
			Enumerator<Business> enumerator = Business.OwnedBusinesses.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Business current = enumerator.Current;
				if ((Object)(object)current == (Object)null)
				{
					continue;
				}
				LaunderInfo launderInfo = new LaunderInfo
				{
					Business = current,
					Name = ((Property)current).PropertyName,
					Capacity = current.LaunderCapacity
				};
				if (current.LaunderingOperations != null)
				{
					Enumerator<LaunderingOperation> enumerator2 = current.LaunderingOperations.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						LaunderingOperation current2 = enumerator2.Current;
						if (current2 != null)
						{
							launderInfo.InProgress += current2.amount;
							launderInfo.Jobs.Add(new LaunderJob
							{
								Amount = current2.amount,
								MinsTotal = current2.completionTime_Minutes,
								MinsLeft = Math.Max(0, current2.completionTime_Minutes - current2.minutesSinceStarted)
							});
						}
					}
				}
				if (Pending.TryGetValue(((Il2CppObjectBase)current).Pointer, out List<(float, int, float)> value))
				{
					int ops = current.LaunderingOperations?.Count ?? 0;
					value.RemoveAll(((float amount, int opsBefore, float until) x) => ops > x.opsBefore || Time.realtimeSinceStartup > x.until);
					foreach (var item in value)
					{
						launderInfo.InProgress += item.Item1;
					}
				}
				launderInfo.Jobs.Sort((LaunderJob a, LaunderJob c) => a.MinsLeft.CompareTo(c.MinsLeft));
				list.Add(launderInfo);
			}
			return list;
		}

		internal static float Cash()
		{
			if (!NetworkSingleton<MoneyManager>.InstanceExists)
			{
				return 0f;
			}
			return NetworkSingleton<MoneyManager>.Instance.cashBalance;
		}

		internal static int MinAmount()
		{
			try
			{
				return LaunderingInterface.MinLaunderAmount;
			}
			catch
			{
				return 10;
			}
		}

		internal static int MaxFor(LaunderInfo info)
		{
			return (int)Math.Min(info.Free, Cash());
		}

		internal static void AutoRun()
		{
			if (!(Time.realtimeSinceStartup < _autoReadyAt))
			{
				FillAll(Mod.AutoLaunderKeep.Value, "Auto-launder");
			}
		}

		internal static int FillAll(int keep, string logPrefix)
		{
			int num = 0;
			foreach (LaunderInfo item in Owned())
			{
				int num2 = (int)Math.Min(item.Free, Cash() - (float)keep);
				if (num2 >= MinAmount() && Start(item, num2, out var _))
				{
					num += num2;
					Mod.Log($"{logPrefix}: {MoneyManager.FormatAmount((float)num2, false, false)} at {item.Name}");
				}
			}
			return num;
		}

		internal static bool Start(LaunderInfo info, int amount, out string reason)
		{
			reason = null;
			if (amount < MinAmount())
			{
				reason = "minimum is " + MoneyManager.FormatAmount((float)MinAmount(), false, false);
				return false;
			}
			if ((float)amount > info.Free + 0.01f)
			{
				reason = "not enough free capacity";
				return false;
			}
			if ((float)amount > Cash() + 0.01f)
			{
				reason = "not enough cash on you";
				return false;
			}
			NetworkSingleton<MoneyManager>.Instance.ChangeCashBalance((float)(-amount), true, true);
			if (!Pending.TryGetValue(((Il2CppObjectBase)info.Business).Pointer, out List<(float, int, float)> value))
			{
				value = (Pending[((Il2CppObjectBase)info.Business).Pointer] = new List<(float, int, float)>());
			}
			int item = (info.Business.LaunderingOperations?.Count ?? 0) + value.Count;
			info.Business.StartLaunderingOperation((float)amount, 0);
			value.Add((amount, item, Time.realtimeSinceStartup + 10f));
			return true;
		}
	}
	internal static class ListSlots
	{
		[HarmonyPatch(typeof(RouteListFieldUI), "Start")]
		internal static class RoutesStartPatch
		{
			private static void Postfix(RouteListFieldUI __instance)
			{
				try
				{
					Started.Add(((Il2CppObjectBase)__instance).Pointer);
					if (EnsureRouteRows(__instance) && __instance.Fields.Count > 0 && __instance.Fields[0] != nu