Decompiled source of DealerAutoRestock v0.10.0

Mods/DealerAutoRestock.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using DealerAutoRestock;
using HarmonyLib;
using Il2CppEPOOutline;
using Il2CppFishNet;
using Il2CppFishNet.Connection;
using Il2CppFishNet.Managing.Client;
using Il2CppFishNet.Managing.Server;
using Il2CppFishNet.Object;
using Il2CppFishNet.Serializing;
using Il2CppFishNet.Transporting;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne.AvatarFramework;
using Il2CppScheduleOne.AvatarFramework.Animation;
using Il2CppScheduleOne.Building.Doors;
using Il2CppScheduleOne.Delivery;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dialogue;
using Il2CppScheduleOne.Doors;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.Interaction;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.NPCs.Schedules;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Phone;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using S1API.Internal.Abstraction;
using S1API.PhoneApp;
using S1API.Saveables;
using S1API.UI;
using S1API.Utils;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(DealerAutoRestockMod), "Dealer Auto Restock", "0.10.0", "SeaDoge", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonPlatformDomain(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DealerAutoRestock")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.10.0.0")]
[assembly: AssemblyInformationalVersion("0.10.0")]
[assembly: AssemblyProduct("DealerAutoRestock")]
[assembly: AssemblyTitle("DealerAutoRestock")]
[assembly: AssemblyVersion("0.10.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DealerAutoRestock
{
	public sealed class DealerAutoRestockSave : Saveable
	{
		[SaveableField("Assignments")]
		private List<SavedAssignment> savedAssignments;

		private static DealerAutoRestockSave? instance;

		private DealerAutoRestockSave()
		{
			instance = this;
			savedAssignments = DealerAutoRestockMod.Instance?.CreateSaveSnapshot() ?? new List<SavedAssignment>();
		}

		internal static void SyncFromMod()
		{
			if (instance != null && DealerAutoRestockMod.Instance != null)
			{
				instance.savedAssignments = DealerAutoRestockMod.Instance.CreateSaveSnapshot();
			}
		}

		protected override void OnCreated()
		{
			savedAssignments = new List<SavedAssignment>();
			DealerAutoRestockMod.Instance?.QueueSaveRestore(savedAssignments);
		}

		protected override void OnLoaded()
		{
			if (savedAssignments == null)
			{
				savedAssignments = new List<SavedAssignment>();
			}
			DealerAutoRestockMod.Instance?.QueueSaveRestore(savedAssignments);
		}

		protected override void OnDestroyed()
		{
			if (instance == this)
			{
				instance = null;
			}
		}
	}
	public sealed class SavedAssignment
	{
		public string DealerId { get; set; } = string.Empty;

		public RestockSourceKind SourceKind { get; set; }

		public string SourceGuid { get; set; } = string.Empty;

		public string SourceName { get; set; } = string.Empty;
	}
	public enum RestockSourceKind
	{
		PlaceableStorage,
		DeadDrop
	}
	public sealed class DealerRestockPhoneApp : PhoneApp
	{
		private sealed class DealerCardView
		{
			public Image Background { get; }

			public Image Accent { get; }

			public RectTransform AccentRect { get; }

			public Text Name { get; }

			public Text Status { get; }

			public Text Source { get; }

			public Image Portrait { get; }

			public Text Initials { get; }

			public DealerCardView(Image background, Image accent, RectTransform accentRect, Text name, Text status, Text source, Image portrait, Text initials)
			{
				Background = background;
				Accent = accent;
				AccentRect = accentRect;
				Name = name;
				Status = status;
				Source = source;
				Portrait = portrait;
				Initials = initials;
			}
		}

		private static readonly Color Canvas = new Color(0.025f, 0.035f, 0.047f, 1f);

		private static readonly Color Header = new Color(0.045f, 0.061f, 0.078f, 1f);

		private static readonly Color Panel = new Color(0.055f, 0.072f, 0.09f, 1f);

		private static readonly Color Raised = new Color(0.075f, 0.098f, 0.12f, 1f);

		private static readonly Color Card = new Color(0.085f, 0.11f, 0.135f, 1f);

		private static readonly Color CardSelected = new Color(0.12f, 0.135f, 0.145f, 1f);

		private static readonly Color Ink = new Color(0.93f, 0.95f, 0.96f, 1f);

		private static readonly Color MutedInk = new Color(0.57f, 0.65f, 0.71f, 1f);

		private static readonly Color Orange = new Color(0.94f, 0.35f, 0.075f, 1f);

		private static readonly Color Red = new Color(0.48f, 0.11f, 0.11f, 1f);

		private static Sprite? icon;

		private static DealerRestockPhoneApp? current;

		private RectTransform? dealerContent;

		private Text? summaryText;

		private Text? detailName;

		private Text? detailStatus;

		private Text? detailDescription;

		private Image? detailStatusBackground;

		private Image? detailPortrait;

		private Text? detailInitials;

		private Text? dealerStockText;

		private Text? sourceStockText;

		private Image? dealerStockFill;

		private Text? sourceTypeText;

		private Text? sourceNameText;

		private Text? sourceLocationText;

		private Text? sourceGlyph;

		private Text? actionLabel;

		private Button? actionButton;

		private Image? actionButtonImage;

		private Button? disableButton;

		private Image? disableButtonImage;

		private readonly Dictionary<string, DealerCardView> dealerCards = new Dictionary<string, DealerCardView>(StringComparer.Ordinal);

		private string rosterSignature = string.Empty;

		private Dealer? selectedDealer;

		private bool wasOpen;

		private float nextRefreshAt;

		protected override string AppName => "DealerAutoRestockApp";

		protected override string AppTitle => "Auto Restock";

		protected override string IconLabel => "Auto Restock";

		protected override string IconFileName => string.Empty;

		protected override EOrientation Orientation => (EOrientation)0;

		protected override Sprite? IconSprite => icon ?? (icon = CreateIcon());

		protected override void OnCreatedUI(GameObject container)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: 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_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			current = this;
			GameObject val = UIFactory.Panel("DispatchRoot", container.transform, Canvas, (Vector2?)null, (Vector2?)null, true);
			Stretch(UIFactory.Panel("Signal", val.transform, Orange, (Vector2?)new Vector2(0f, 0.987f), (Vector2?)Vector2.one, false).GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			GameObject val2 = UIFactory.Panel("Header", val.transform, Header, (Vector2?)new Vector2(0.018f, 0.865f), (Vector2?)new Vector2(0.982f, 0.965f), false);
			Stretch(val2.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("Eyebrow", "AUTO RESTOCK  /  OPERATIONS", val2.transform, 12, (TextAnchor)3, (FontStyle)1, Orange)).rectTransform, new Vector2(0f, 0.58f), new Vector2(0.55f, 0.92f), 20f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("Title", "DEALER LOGISTICS", val2.transform, 25, (TextAnchor)3, (FontStyle)1, Ink)).rectTransform, new Vector2(0f, 0.08f), new Vector2(0.55f, 0.62f), 20f, 0f, 0f, 0f);
			summaryText = MakeText("Summary", "0 ACTIVE  /  0 DEALERS", val2.transform, 15, (TextAnchor)5, (FontStyle)1, MutedInk);
			AnchorRect(((Graphic)summaryText).rectTransform, new Vector2(0.55f, 0f), Vector2.one, 0f, 22f, 0f, 0f);
			GameObject val3 = UIFactory.Panel("Roster", val.transform, Panel, (Vector2?)new Vector2(0.018f, 0.04f), (Vector2?)new Vector2(0.385f, 0.84f), false);
			Stretch(val3.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("RosterTitle", "RECRUITED DEALERS", val3.transform, 14, (TextAnchor)3, (FontStyle)1, MutedInk)).rectTransform, new Vector2(0f, 0.91f), Vector2.one, 18f, 16f, 0f, 0f);
			dealerContent = CreateList("DealerList", val3.transform, 14f, 14f, 14f, 64f);
			GameObject val4 = UIFactory.Panel("Workspace", val.transform, Panel, (Vector2?)new Vector2(0.405f, 0.04f), (Vector2?)new Vector2(0.982f, 0.84f), false);
			Stretch(val4.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			BuildDealerHeader(val4.transform);
			BuildMetrics(val4.transform);
			BuildSourceCard(val4.transform);
			BuildActions(val4.transform);
			Refresh();
		}

		private void BuildDealerHeader(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: 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_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = UIFactory.Panel("DealerHeader", parent, Raised, (Vector2?)new Vector2(0.025f, 0.69f), (Vector2?)new Vector2(0.975f, 0.965f), false);
			Stretch(val.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			detailPortrait = CreatePortrait("Portrait", val.transform, new Vector2(0f, 0.5f), new Vector2(58f, 0f), 96f, out detailInitials);
			detailName = MakeText("DealerName", "SELECT A DEALER", val.transform, 25, (TextAnchor)3, (FontStyle)1, Ink);
			AnchorRect(((Graphic)detailName).rectTransform, new Vector2(0f, 0.49f), new Vector2(0.67f, 0.88f), 122f, 0f, 0f, 0f);
			detailDescription = MakeText("DealerDescription", "Choose a recruited dealer from the roster.", val.transform, 14, (TextAnchor)0, (FontStyle)0, MutedInk);
			AnchorRect(((Graphic)detailDescription).rectTransform, new Vector2(0f, 0.12f), new Vector2(0.72f, 0.5f), 122f, 0f, 0f, 0f);
			GameObject val2 = UIFactory.Panel("StatusBadge", val.transform, ToneColor(DealerUiTone.Muted), (Vector2?)new Vector2(0.73f, 0.57f), (Vector2?)new Vector2(0.965f, 0.82f), false);
			Stretch(val2.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			detailStatusBackground = val2.GetComponent<Image>();
			detailStatus = MakeText("Status", "DISABLED", val2.transform, 13, (TextAnchor)4, (FontStyle)1, Ink);
			Fill(((Graphic)detailStatus).rectTransform, 5f, 5f, 0f, 0f);
		}

		private void BuildMetrics(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: 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_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = UIFactory.Panel("DealerStock", parent, Raised, (Vector2?)new Vector2(0.025f, 0.49f), (Vector2?)new Vector2(0.487f, 0.665f), false);
			Stretch(val.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("Label", "DEALER STOCK", val.transform, 12, (TextAnchor)3, (FontStyle)1, MutedInk)).rectTransform, new Vector2(0f, 0.58f), new Vector2(0.65f, 0.94f), 16f, 0f, 0f, 0f);
			dealerStockText = MakeText("Value", "-- / --", val.transform, 22, (TextAnchor)5, (FontStyle)1, Ink);
			AnchorRect(((Graphic)dealerStockText).rectTransform, new Vector2(0.55f, 0.48f), new Vector2(0.95f, 0.96f), 0f, 0f, 0f, 0f);
			GameObject val2 = UIFactory.Panel("Track", val.transform, new Color(0.025f, 0.035f, 0.043f, 1f), (Vector2?)new Vector2(0.055f, 0.18f), (Vector2?)new Vector2(0.945f, 0.31f), false);
			Stretch(val2.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			GameObject val3 = UIFactory.Panel("Fill", val2.transform, Orange, (Vector2?)Vector2.zero, (Vector2?)Vector2.one, false);
			dealerStockFill = val3.GetComponent<Image>();
			RectTransform component = val3.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0f, 1f);
			Stretch(component, 0f, 0f, 0f, 0f);
			GameObject val4 = UIFactory.Panel("SourceStock", parent, Raised, (Vector2?)new Vector2(0.513f, 0.49f), (Vector2?)new Vector2(0.975f, 0.665f), false);
			Stretch(val4.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("Label", "SOURCE INVENTORY", val4.transform, 12, (TextAnchor)3, (FontStyle)1, MutedInk)).rectTransform, new Vector2(0f, 0.58f), new Vector2(0.75f, 0.94f), 16f, 0f, 0f, 0f);
			sourceStockText = MakeText("Value", "--", val4.transform, 28, (TextAnchor)3, (FontStyle)1, Ink);
			AnchorRect(((Graphic)sourceStockText).rectTransform, new Vector2(0f, 0.12f), new Vector2(0.48f, 0.62f), 16f, 0f, 0f, 0f);
			AnchorRect(((Graphic)MakeText("Units", "PRODUCT UNITS", val4.transform, 11, (TextAnchor)5, (FontStyle)1, MutedInk)).rectTransform, new Vector2(0.45f, 0.12f), new Vector2(0.95f, 0.58f), 0f, 0f, 0f, 0f);
		}

		private void BuildSourceCard(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: 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_0227: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = UIFactory.Panel("Source", parent, Raised, (Vector2?)new Vector2(0.025f, 0.235f), (Vector2?)new Vector2(0.975f, 0.465f), false);
			Stretch(val.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			GameObject val2 = UIFactory.Panel("GlyphBox", val.transform, new Color(0.1f, 0.125f, 0.14f, 1f), (Vector2?)new Vector2(0.025f, 0.18f), (Vector2?)new Vector2(0.17f, 0.82f), false);
			Stretch(val2.GetComponent<RectTransform>(), 0f, 0f, 0f, 0f);
			sourceGlyph = MakeText("Glyph", "--", val2.transform, 21, (TextAnchor)4, (FontStyle)1, Orange);
			Fill(((Graphic)sourceGlyph).rectTransform, 0f, 0f, 0f, 0f);
			sourceTypeText = MakeText("Type", "RESTOCK SOURCE", val.transform, 12, (TextAnchor)3, (FontStyle)1, Orange);
			AnchorRect(((Graphic)sourceTypeText).rectTransform, new Vector2(0.2f, 0.63f), new Vector2(0.74f, 0.9f), 0f, 0f, 0f, 0f);
			sourceNameText = MakeText("Name", "No source assigned", val.transform, 20, (TextAnchor)3, (FontStyle)1, Ink);
			AnchorRect(((Graphic)sourceNameText).rectTransform, new Vector2(0.2f, 0.3f), new Vector2(0.94f, 0.67f), 0f, 0f, 0f, 0f);
			sourceLocationText = MakeText("Location", "Assign a storage or outdoor dead drop.", val.transform, 13, (TextAnchor)3, (FontStyle)0, MutedInk);
			AnchorRect(((Graphic)sourceLocationText).rectTransform, new Vector2(0.2f, 0.08f), new Vector2(0.94f, 0.34f), 0f, 0f, 0f, 0f);
		}

		private void BuildActions(Transform parent)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateButton("PrimaryAction", "ASSIGN SOURCE", parent, Orange);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.025f, 0.055f);
			component.anchorMax = new Vector2(0.69f, 0.19f);
			Stretch(component, 0f, 0f, 0f, 0f);
			actionLabel = val.GetComponentInChildren<Text>();
			actionButton = val.GetComponent<Button>();
			actionButtonImage = val.GetComponent<Image>();
			ButtonUtils.AddListener(actionButton, (Action)ChooseSource);
			GameObject val2 = CreateButton("Disable", "DISABLE", parent, Red);
			RectTransform component2 = val2.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0.715f, 0.055f);
			component2.anchorMax = new Vector2(0.975f, 0.19f);
			Stretch(component2, 0f, 0f, 0f, 0f);
			disableButton = val2.GetComponent<Button>();
			disableButtonImage = val2.GetComponent<Image>();
			ButtonUtils.AddListener(disableButton, (Action)DisableSelectedDealer);
		}

		internal static void Tick()
		{
			if (current != null)
			{
				bool flag = ((PhoneApp)current).IsOpen();
				if (flag && (!current.wasOpen || Time.unscaledTime >= current.nextRefreshAt))
				{
					current.nextRefreshAt = Time.unscaledTime + 0.75f;
					current.Refresh();
				}
				current.wasOpen = flag;
			}
		}

		private void Refresh()
		{
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			DealerAutoRestockMod instance = DealerAutoRestockMod.Instance;
			if (instance == null || (Object)(object)dealerContent == (Object)null)
			{
				return;
			}
			IReadOnlyList<Dealer> recruitedDealers = instance.GetRecruitedDealers();
			if ((Object)(object)selectedDealer != (Object)null)
			{
				selectedDealer = ((IEnumerable<Dealer>)recruitedDealers).FirstOrDefault((Func<Dealer, bool>)((Dealer dealer) => ((NPC)dealer).ID == ((NPC)selectedDealer).ID));
			}
			if ((Object)(object)selectedDealer == (Object)null && recruitedDealers.Count > 0)
			{
				selectedDealer = recruitedDealers[0];
			}
			string b = string.Join("|", recruitedDealers.Select((Dealer dealer) => $"{((NPC)dealer).ID}:{((Object)dealer).GetInstanceID()}"));
			if (!string.Equals(rosterSignature, b, StringComparison.Ordinal))
			{
				rosterSignature = b;
				dealerCards.Clear();
				UIFactory.ClearChildren((Transform)(object)dealerContent);
				foreach (Dealer item in recruitedDealers)
				{
					dealerCards[((NPC)item).ID] = CreateDealerCard(item);
				}
				if (recruitedDealers.Count == 0)
				{
					AddEmptyState((Transform)(object)dealerContent, "No recruited dealers available");
				}
			}
			int num = 0;
			foreach (Dealer item2 in recruitedDealers)
			{
				DealerUiState dealerUiState = instance.GetDealerUiState(item2);
				if (dealerUiState.Assigned)
				{
					num++;
				}
				if (dealerCards.TryGetValue(((NPC)item2).ID, out DealerCardView value))
				{
					UpdateDealerCard(value, item2, dealerUiState, (Object)(object)selectedDealer != (Object)null && ((NPC)item2).ID == ((NPC)selectedDealer).ID);
				}
			}
			if ((Object)(object)summaryText != (Object)null)
			{
				summaryText.text = $"{num} ACTIVE  /  {recruitedDealers.Count} DEALERS";
				((Graphic)summaryText).color = ((num > 0) ? ToneColor(DealerUiTone.Active) : MutedInk);
			}
			RefreshDetails();
		}

		private DealerCardView CreateDealerCard(Dealer dealer)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: 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_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Dealer_" + ((NPC)dealer).ID);
			val.transform.SetParent((Transform)(object)dealerContent, false);
			val.AddComponent<RectTransform>().sizeDelta = new Vector2(0f, 90f);
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.preferredHeight = 90f;
			obj.flexibleWidth = 1f;
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = Card;
			Button obj2 = val.AddComponent<Button>();
			((Selectable)obj2).targetGraphic = (Graphic)(object)val2;
			GameObject obj3 = UIFactory.Panel("Accent", val.transform, ToneColor(DealerUiTone.Muted), (Vector2?)null, (Vector2?)null, false);
			Image component = obj3.GetComponent<Image>();
			RectTransform component2 = obj3.GetComponent<RectTransform>();
			component2.anchorMin = Vector2.zero;
			component2.anchorMax = new Vector2(0f, 1f);
			component2.pivot = new Vector2(0f, 0.5f);
			component2.sizeDelta = new Vector2(3f, 0f);
			component2.anchoredPosition = Vector2.zero;
			Text initials;
			Image portrait = CreatePortrait("Portrait", val.transform, new Vector2(0f, 0.5f), new Vector2(42f, 0f), 62f, out initials);
			Text val3 = MakeText("Name", ((NPC)dealer).fullName, val.transform, 16, (TextAnchor)3, (FontStyle)1, Ink);
			AnchorRect(((Graphic)val3).rectTransform, new Vector2(0f, 0.53f), new Vector2(0.72f, 0.94f), 82f, 0f, 0f, 0f);
			Text val4 = MakeText("Status", string.Empty, val.transform, 11, (TextAnchor)5, (FontStyle)1, MutedInk);
			AnchorRect(((Graphic)val4).rectTransform, new Vector2(0.64f, 0.55f), new Vector2(0.96f, 0.92f), 0f, 0f, 0f, 0f);
			Text val5 = MakeText("Source", string.Empty, val.transform, 12, (TextAnchor)0, (FontStyle)0, MutedInk);
			val5.resizeTextForBestFit = true;
			val5.resizeTextMinSize = 10;
			val5.resizeTextMaxSize = 12;
			AnchorRect(((Graphic)val5).rectTransform, new Vector2(0f, 0.08f), new Vector2(0.96f, 0.52f), 82f, 0f, 0f, 0f);
			ButtonUtils.AddListener(obj2, (Action)delegate
			{
				SelectDealer(dealer);
			});
			return new DealerCardView(val2, component, component2, val3, val4, val5, portrait, initials);
		}

		private static void UpdateDealerCard(DealerCardView card, Dealer dealer, DealerUiState state, bool selected)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			((Graphic)card.Background).color = (selected ? CardSelected : Card);
			((Graphic)card.Accent).color = (selected ? Orange : ToneColor(state.Tone));
			card.AccentRect.sizeDelta = new Vector2(selected ? 5f : 3f, 0f);
			card.Name.text = ((NPC)dealer).fullName;
			card.Status.text = state.Status;
			((Graphic)card.Status).color = ToneColor(state.Tone);
			card.Source.text = (state.Assigned ? state.SourceName : state.Detail);
			SetPortrait(card.Portrait, card.Initials, dealer);
		}

		private void RefreshDetails()
		{
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_0472: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0434: Unknown result type (might be due to invalid IL or missing references)
			DealerAutoRestockMod instance = DealerAutoRestockMod.Instance;
			if (instance == null || (Object)(object)detailName == (Object)null || (Object)(object)detailStatus == (Object)null || (Object)(object)detailDescription == (Object)null || (Object)(object)detailStatusBackground == (Object)null || (Object)(object)dealerStockText == (Object)null || (Object)(object)sourceStockText == (Object)null || (Object)(object)sourceTypeText == (Object)null || (Object)(object)sourceNameText == (Object)null || (Object)(object)sourceLocationText == (Object)null || (Object)(object)sourceGlyph == (Object)null || (Object)(object)actionLabel == (Object)null || (Object)(object)disableButton == (Object)null || (Object)(object)disableButtonImage == (Object)null)
			{
				return;
			}
			if ((Object)(object)selectedDealer == (Object)null)
			{
				detailName.text = "NO DEALER SELECTED";
				detailStatus.text = "IDLE";
				((Graphic)detailStatusBackground).color = WithAlpha(ToneColor(DealerUiTone.Muted), 0.32f);
				detailDescription.text = "Recruit a dealer to configure automatic restocking.";
				SetPortrait(detailPortrait, detailInitials, null);
				dealerStockText.text = "-- / --";
				sourceStockText.text = "--";
				sourceTypeText.text = "RESTOCK SOURCE";
				sourceNameText.text = "No source assigned";
				sourceLocationText.text = "Select a dealer from the roster.";
				sourceGlyph.text = "--";
				actionLabel.text = "ASSIGN SOURCE";
				if ((Object)(object)actionButton != (Object)null && (Object)(object)actionButtonImage != (Object)null)
				{
					((Selectable)actionButton).interactable = false;
					((Graphic)actionButtonImage).color = WithAlpha(Orange, 0.35f);
				}
				((Selectable)disableButton).interactable = false;
				((Graphic)disableButtonImage).color = new Color(Red.r, Red.g, Red.b, 0.35f);
				SetProgress(0f);
				return;
			}
			DealerUiState dealerUiState = instance.GetDealerUiState(selectedDealer);
			detailName.text = ((NPC)selectedDealer).fullName.ToUpperInvariant();
			detailStatus.text = dealerUiState.Status;
			((Graphic)detailStatusBackground).color = WithAlpha(ToneColor(dealerUiState.Tone), 0.32f);
			detailDescription.text = dealerUiState.Detail;
			SetPortrait(detailPortrait, detailInitials, selectedDealer);
			dealerStockText.text = $"{dealerUiState.DealerStock} / {dealerUiState.TargetStock}";
			sourceStockText.text = (dealerUiState.Assigned ? dealerUiState.SourceStock.ToString() : "--");
			sourceTypeText.text = (dealerUiState.Assigned ? dealerUiState.SourceType : "RESTOCK SOURCE");
			sourceNameText.text = (dealerUiState.Assigned ? dealerUiState.SourceName : "No source assigned");
			sourceLocationText.text = ((!dealerUiState.Assigned) ? "Assign a storage or outdoor dead drop." : ((dealerUiState.SourceType == "DEAD DROP") ? "Outdoor collection point" : dealerUiState.DestinationName));
			sourceGlyph.text = ((dealerUiState.SourceType == "DEAD DROP") ? "DD" : (dealerUiState.Assigned ? "ST" : "--"));
			actionLabel.text = (dealerUiState.Assigned ? "CHANGE SOURCE" : "ASSIGN SOURCE");
			bool canConfigureAssignments = instance.CanConfigureAssignments;
			if ((Object)(object)actionButton != (Object)null && (Object)(object)actionButtonImage != (Object)null)
			{
				((Selectable)actionButton).interactable = canConfigureAssignments;
				((Graphic)actionButtonImage).color = (canConfigureAssignments ? Orange : WithAlpha(Orange, 0.35f));
			}
			((Selectable)disableButton).interactable = dealerUiState.Assigned && canConfigureAssignments;
			((Graphic)disableButtonImage).color = ((dealerUiState.Assigned && canConfigureAssignments) ? Red : WithAlpha(Red, 0.35f));
			SetProgress((dealerUiState.TargetStock > 0) ? Mathf.Clamp01((float)dealerUiState.DealerStock / (float)dealerUiState.TargetStock) : 0f);
		}

		private void SetProgress(float progress)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)dealerStockFill == (Object)null))
			{
				((Graphic)dealerStockFill).rectTransform.anchorMax = new Vector2(progress, 1f);
				((Graphic)dealerStockFill).color = ((progress >= 1f) ? ToneColor(DealerUiTone.Active) : Orange);
			}
		}

		private void SelectDealer(Dealer dealer)
		{
			selectedDealer = dealer;
			Refresh();
		}

		private void ChooseSource()
		{
			//IL_007c: 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)
			DealerAutoRestockMod instance = DealerAutoRestockMod.Instance;
			if (instance != null && !((Object)(object)selectedDealer == (Object)null))
			{
				if (instance.BeginSourceSelection(selectedDealer, out string message))
				{
					((PhoneApp)this).CloseApp();
				}
				else if ((Object)(object)detailDescription != (Object)null && (Object)(object)detailStatus != (Object)null && (Object)(object)detailStatusBackground != (Object)null)
				{
					detailDescription.text = message;
					detailStatus.text = "UNAVAILABLE";
					((Graphic)detailStatusBackground).color = WithAlpha(ToneColor(DealerUiTone.Danger), 0.32f);
				}
			}
		}

		private void DisableSelectedDealer()
		{
			DealerAutoRestockMod instance = DealerAutoRestockMod.Instance;
			if (instance != null && !((Object)(object)selectedDealer == (Object)null))
			{
				instance.ClearAssignment(selectedDealer);
				Refresh();
			}
		}

		private static Image CreatePortrait(string name, Transform parent, Vector2 anchor, Vector2 position, float size, out Text initials)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = UIFactory.Panel(name + "Frame", parent, new Color(0.025f, 0.034f, 0.042f, 1f), (Vector2?)null, (Vector2?)null, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = anchor;
			component.anchorMax = anchor;
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = position;
			component.sizeDelta = new Vector2(size, size);
			Outline obj = val.AddComponent<Outline>();
			((Shadow)obj).effectColor = new Color(0.2f, 0.24f, 0.27f, 1f);
			((Shadow)obj).effectDistance = new Vector2(1f, -1f);
			GameObject val2 = new GameObject(name + "Image");
			val2.transform.SetParent(val.transform, false);
			RectTransform obj2 = val2.AddComponent<RectTransform>();
			obj2.anchorMin = Vector2.zero;
			obj2.anchorMax = Vector2.one;
			Stretch(obj2, 3f, 3f, 3f, 3f);
			Image obj3 = val2.AddComponent<Image>();
			obj3.preserveAspect = true;
			initials = MakeText(name + "Initials", "--", val.transform, Mathf.RoundToInt(size * 0.28f), (TextAnchor)4, (FontStyle)1, MutedInk);
			Fill(((Graphic)initials).rectTransform, 3f, 3f, 3f, 3f);
			return obj3;
		}

		private static void SetPortrait(Image? image, Text? initials, Dealer? dealer)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)image == (Object)null) && !((Object)(object)initials == (Object)null))
			{
				Sprite val = (image.sprite = ((dealer != null) ? ((NPC)dealer).MugshotSprite : null) ?? ((dealer != null) ? ((NPC)dealer).GetMessagingIcon() : null));
				((Graphic)image).color = (((Object)(object)val != (Object)null) ? Color.white : Color.clear);
				initials.text = (((Object)(object)val == (Object)null && (Object)(object)dealer != (Object)null) ? GetInitials(((NPC)dealer).fullName) : string.Empty);
			}
		}

		private static string GetInitials(string name)
		{
			string[] array = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
			return array.Length switch
			{
				0 => "--", 
				1 => array[0][0].ToString().ToUpperInvariant(), 
				_ => string.Concat(array[0][0], array[^1][0]).ToUpperInvariant(), 
			};
		}

		private static RectTransform CreateList(string name, Transform parent, float left, float right, float bottom, float top)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			ScrollRect val2 = default(ScrollRect);
			RectTransform val = UIFactory.ScrollableVerticalList(name, parent, ref val2);
			Stretch(((Component)val2).GetComponent<RectTransform>(), left, right, bottom, top);
			val2.scrollSensitivity = 32f;
			val.anchoredPosition = Vector2.zero;
			val.sizeDelta = new Vector2(0f, val.sizeDelta.y);
			VerticalLayoutGroup component = ((Component)val).GetComponent<VerticalLayoutGroup>();
			if ((Object)(object)component != (Object)null)
			{
				((LayoutGroup)component).childAlignment = (TextAnchor)0;
				((HorizontalOrVerticalLayoutGroup)component).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)component).childForceExpandWidth = true;
				((HorizontalOrVerticalLayoutGroup)component).spacing = 9f;
				((LayoutGroup)component).padding = new RectOffset(0, 4, 4, 8);
			}
			return val;
		}

		private static GameObject CreateButton(string name, string label, Transform parent, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			val.AddComponent<RectTransform>();
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = color;
			((Selectable)val.AddComponent<Button>()).targetGraphic = (Graphic)(object)val2;
			Fill(((Graphic)MakeText("Label", label, val.transform, 15, (TextAnchor)4, (FontStyle)1, Ink)).rectTransform, 8f, 8f, 4f, 4f);
			return val;
		}

		private static Text MakeText(string name, string value, Transform parent, int size, TextAnchor anchor, FontStyle style, Color color)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			Text obj = UIFactory.Text(name, value, parent, size, anchor, style);
			((Graphic)obj).color = color;
			return obj;
		}

		private static void AddEmptyState(Transform parent, string message)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			LayoutElement obj = ((Component)MakeText("Empty", message, parent, 14, (TextAnchor)4, (FontStyle)0, MutedInk)).gameObject.AddComponent<LayoutElement>();
			obj.preferredHeight = 100f;
			obj.flexibleWidth = 1f;
		}

		private static Color ToneColor(DealerUiTone tone)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(tone switch
			{
				DealerUiTone.Active => new Color(0.32f, 0.76f, 0.43f, 1f), 
				DealerUiTone.Working => Orange, 
				DealerUiTone.Warning => new Color(0.9f, 0.65f, 0.25f, 1f), 
				DealerUiTone.Danger => new Color(0.9f, 0.3f, 0.27f, 1f), 
				_ => new Color(0.42f, 0.48f, 0.53f, 1f), 
			});
		}

		private static Color WithAlpha(Color color, float alpha)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return new Color(color.r, color.g, color.b, alpha);
		}

		private static void Stretch(RectTransform rect, float left, float right, float bottom, float top)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			rect.offsetMin = new Vector2(left, bottom);
			rect.offsetMax = new Vector2(0f - right, 0f - top);
		}

		private static void Fill(RectTransform rect, float left, float right, float bottom, float top)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = Vector2.zero;
			rect.anchorMax = Vector2.one;
			Stretch(rect, left, right, bottom, top);
		}

		private static void AnchorRect(RectTransform rect, Vector2 min, Vector2 max, float left, float right, float bottom, float top)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = min;
			rect.anchorMax = max;
			Stretch(rect, left, right, bottom, top);
		}

		private static Sprite CreateIcon()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(96, 96, (TextureFormat)4, false);
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(0f, 0f, 0f, 0f);
			Color val3 = default(Color);
			((Color)(ref val3))..ctor(0.94f, 0.29f, 0.065f, 1f);
			Color color = default(Color);
			((Color)(ref color))..ctor(0.97f, 0.98f, 0.96f, 1f);
			for (int i = 0; i < 96; i++)
			{
				for (int j = 0; j < 96; j++)
				{
					bool flag = IsInsideRoundedSquare(j, i, 96, 0f, 20f);
					val.SetPixel(j, i, flag ? val3 : val2);
				}
			}
			FillRect(val, color, 18, 18, 69, 52);
			FillRect(val, color, 14, 52, 73, 62);
			FillRect(val, val3, 40, 18, 47, 62);
			PaintCircle(val, 70, 70, 21, val3);
			PaintCircle(val, 70, 70, 17, color);
			FillRect(val, val3, 66, 59, 74, 81);
			FillRect(val, val3, 59, 66, 81, 74);
			val.Apply();
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Object)val).name = "DealerAutoRestockIcon";
			return Sprite.Create(val, new Rect(0f, 0f, 96f, 96f), new Vector2(0.5f, 0.5f));
		}

		private static bool IsInsideRoundedSquare(int x, int y, int size, float margin, float radius)
		{
			float num = ((float)size - 1f) * 0.5f;
			float num2 = num - margin;
			float num3 = Mathf.Max(Mathf.Abs((float)x - num) - (num2 - radius), 0f);
			float num4 = Mathf.Max(Mathf.Abs((float)y - num) - (num2 - radius), 0f);
			return num3 * num3 + num4 * num4 <= radius * radius;
		}

		private static void FillRect(Texture2D texture, Color color, int minX, int minY, int maxX, int maxY)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			for (int i = minY; i <= maxY; i++)
			{
				for (int j = minX; j <= maxX; j++)
				{
					texture.SetPixel(j, i, color);
				}
			}
		}

		private static void PaintCircle(Texture2D texture, int centerX, int centerY, int radius, Color color)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			for (int i = centerY - radius; i <= centerY + radius; i++)
			{
				for (int j = centerX - radius; j <= centerX + radius; j++)
				{
					if (j >= 0 && i >= 0 && j < ((Texture)texture).width && i < ((Texture)texture).height && (j - centerX) * (j - centerX) + (i - centerY) * (i - centerY) <= radius * radius)
					{
						texture.SetPixel(j, i, color);
					}
				}
			}
		}
	}
	public sealed class DealerAutoRestockMod : MelonMod
	{
		private sealed class Assignment
		{
			public Dealer Dealer { get; }

			public StorageEntity StorageEntity { get; }

			public Transform StorageTransform { get; }

			public string StorageName { get; }

			public string DestinationName { get; }

			public Vector3 ExteriorPoint { get; }

			public RestockSourceKind SourceKind { get; }

			public string SourceGuid { get; }

			public PlaceableStorageEntity? PlaceableStorage { get; }

			public string DealerId { get; }

			public float NextAttemptAt { get; set; }

			public Assignment(Dealer dealer, StorageEntity storageEntity, Transform storageTransform, string storageName, string destinationName, Vector3 exteriorPoint, RestockSourceKind sourceKind, string sourceGuid, PlaceableStorageEntity? placeableStorage = null)
			{
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				Dealer = dealer;
				StorageEntity = storageEntity;
				StorageTransform = storageTransform;
				StorageName = storageName;
				DestinationName = destinationName;
				ExteriorPoint = exteriorPoint;
				SourceKind = sourceKind;
				SourceGuid = sourceGuid;
				PlaceableStorage = placeableStorage;
				DealerId = ((NPC)dealer).ID;
			}
		}

		internal sealed class RestockSource
		{
			public string DisplayName { get; }

			public StorageEntity StorageEntity { get; }

			public Transform StorageTransform { get; }

			public string StorageName { get; }

			public string DestinationName { get; }

			public Vector3 ExteriorPoint { get; }

			public RestockSourceKind SourceKind { get; }

			public string SourceGuid { get; }

			public PlaceableStorageEntity? PlaceableStorage { get; }

			public RestockSource(string displayName, StorageEntity storageEntity, Transform storageTransform, string storageName, string destinationName, Vector3 exteriorPoint, RestockSourceKind sourceKind, string sourceGuid, PlaceableStorageEntity? placeableStorage = null)
			{
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				DisplayName = displayName;
				StorageEntity = storageEntity;
				StorageTransform = storageTransform;
				StorageName = storageName;
				DestinationName = destinationName;
				ExteriorPoint = exteriorPoint;
				SourceKind = sourceKind;
				SourceGuid = sourceGuid;
				PlaceableStorage = placeableStorage;
			}
		}

		private sealed class SelectionResolution
		{
			public static readonly SelectionResolution NoTarget = new SelectionResolution(null, "No valid storage or dead drop under the crosshair.", null, null);

			public RestockSource? Source { get; }

			public string Error { get; }

			public Collider? TargetCollider { get; }

			public PlaceableStorageEntity? OutlineStorage { get; }

			public Bounds? TargetBounds { get; }

			public DeadDrop? OutlineDeadDrop { get; }

			public SelectionResolution(RestockSource? source, string error, Collider? targetCollider, PlaceableStorageEntity? outlineStorage, Bounds? targetBounds = null, DeadDrop? outlineDeadDrop = null)
			{
				Source = source;
				Error = error;
				TargetCollider = targetCollider;
				OutlineStorage = outlineStorage;
				TargetBounds = targetBounds;
				OutlineDeadDrop = outlineDeadDrop;
			}
		}

		private sealed class Journey
		{
			public Assignment Assignment { get; }

			public Vector3 ExteriorPoint { get; set; }

			public float StartedAt { get; }

			public float StateStartedAt { get; private set; }

			public Vector3 LastPosition { get; private set; }

			public float LastDistanceToTarget { get; private set; }

			public float LastProgressAt { get; private set; }

			public bool StuckWarningLogged { get; set; }

			public bool RouteIssued { get; set; }

			public bool ExitRequested { get; set; }

			public bool ControlSuspended { get; set; }

			public bool ScheduleWasEnabled { get; set; }

			public bool DialoguePaused { get; set; }

			public bool CollectionStarted { get; set; }

			public bool GrabAnimationActive { get; set; }

			public string? GrabAnimationParameter { get; set; }

			public AnimatorControllerParameterType GrabAnimationParameterType { get; set; }

			public float NextGrabAnimationAt { get; set; }

			public bool SprintApplied { get; set; }

			public int MovedUnits { get; set; }

			public float CollectionDuration { get; set; }

			public float LastRouteAt { get; set; }

			public NPCScheduleManager? ScheduleManager { get; set; }

			public NPCSpeedController? SpeedController { get; set; }

			public string? SuspendedActionName { get; set; }

			public JourneyState State { get; private set; }

			public Journey(Assignment assignment, float startedAt)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				Assignment = assignment;
				ExteriorPoint = assignment.ExteriorPoint;
				StartedAt = startedAt;
				StateStartedAt = startedAt;
				LastPosition = ((Component)assignment.Dealer).transform.position;
				LastDistanceToTarget = Vector3.Distance(LastPosition, ExteriorPoint);
				LastProgressAt = startedAt;
				State = JourneyState.GoingToProperty;
			}

			public void SetState(JourneyState state)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				State = state;
				StateStartedAt = Time.unscaledTime;
				LastPosition = ((Component)Assignment.Dealer).transform.position;
				LastDistanceToTarget = Vector3.Distance(LastPosition, ExteriorPoint);
				LastProgressAt = Time.unscaledTime;
				StuckWarningLogged = false;
				RouteIssued = false;
				ExitRequested = false;
			}

			public void RecordProgress(Vector3 position)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				float num = Vector3.Distance(position, ExteriorPoint);
				if (!(LastDistanceToTarget - num < 0.1f))
				{
					LastPosition = position;
					LastDistanceToTarget = num;
					LastProgressAt = Time.unscaledTime;
					StuckWarningLogged = false;
				}
			}

			public void EnforceRoute()
			{
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				Dealer dealer = Assignment.Dealer;
				if ((Object)(object)dealer == (Object)null || !((NetworkBehaviour)dealer).IsServerInitialized)
				{
					return;
				}
				if (IsDealerInDialogue(dealer))
				{
					if (!DialoguePaused)
					{
						((NPC)dealer).Movement.Stop();
						DialoguePaused = true;
					}
					return;
				}
				if (DialoguePaused)
				{
					DialoguePaused = false;
					RouteIssued = false;
					LastDistanceToTarget = Vector3.Distance(((Component)dealer).transform.position, ExteriorPoint);
					LastProgressAt = Time.unscaledTime;
				}
				if (!((NPC)dealer).isInBuilding && ((NPC)dealer).Movement.CanMove() && State == JourneyState.GoingToProperty)
				{
					if ((Object)(object)ScheduleManager != (Object)null && ScheduleManager.ScheduleEnabled)
					{
						ScheduleManager.DisableSchedule();
					}
					if (!RouteIssued || (!((NPC)dealer).Movement.HasDestination && Time.unscaledTime - LastRouteAt >= 2f))
					{
						((NPC)dealer).Movement.Stop();
						((NPC)dealer).Movement.SetDestination(ExteriorPoint);
						RouteIssued = true;
						LastRouteAt = Time.unscaledTime;
					}
				}
			}
		}

		private enum JourneyState
		{
			LeavingCurrentBuilding,
			GoingToProperty,
			Collecting,
			WaitingForInventorySync,
			ExitingProperty
		}

		private sealed class PacketReader
		{
			private readonly List<int>? packet;

			private int index;

			public bool IsAtEnd
			{
				get
				{
					if (packet != null)
					{
						return index == packet.Count;
					}
					return false;
				}
			}

			public PacketReader(List<int>? packet)
			{
				this.packet = packet;
			}

			public int ReadInt()
			{
				if (packet == null || index >= packet.Count)
				{
					throw new InvalidOperationException("Unexpected end of packet.");
				}
				return packet[index++];
			}

			public string ReadString(int maximumLength)
			{
				int num = ReadInt();
				if (num < 0 || num > maximumLength || packet == null || index + num > packet.Count)
				{
					throw new InvalidOperationException("Invalid packet string length.");
				}
				char[] array = new char[num];
				for (int i = 0; i < num; i++)
				{
					array[i] = (char)packet[index++];
				}
				return new string(array);
			}
		}

		private enum NetworkOpcode
		{
			SnapshotRequest = 1,
			AssignRequest,
			ClearRequest,
			MutationResult,
			Snapshot
		}

		private sealed record SnapshotRecord(string DealerId, RestockSourceKind SourceKind, string SourceGuid, int JourneyState);

		private const float SelectionDistance = 8f;

		private const float DoorArrivalDistance = 1.75f;

		private const float MinCollectionDuration = 2f;

		private const float MaxCollectionDuration = 8f;

		private const float CollectionSecondsPerPackage = 0.65f;

		private const float GrabAnimationInterval = 1.1f;

		private const float InventorySyncDelay = 3f;

		private const float PostWarpSettleDelay = 0.5f;

		private const float RepathInterval = 2f;

		private const float BuildingTransitionTimeout = 15f;

		private const float ExitBuildingDelay = 0.5f;

		private const float JourneyTimeout = 180f;

		private const float StuckWarningDelay = 15f;

		private const float StuckAbortDelay = 45f;

		private const float StatusDuration = 5f;

		private const float JourneyTickInterval = 0.1f;

		private const float SaveRestoreTimeout = 15f;

		private const float SaveRestoreRetryInterval = 0.5f;

		private const string SprintSpeedControlId = "DealerAutoRestockSprint";

		private const int SprintSpeedControlPriority = 100;

		private const int MaxTargetStock = 1000;

		private readonly Dictionary<string, Assignment> assignments = new Dictionary<string, Assignment>(StringComparer.Ordinal);

		private readonly Dictionary<string, Journey> journeys = new Dictionary<string, Journey>(StringComparer.Ordinal);

		private readonly List<Journey> journeySnapshot = new List<Journey>();

		private MelonPreferences_Entry<int> targetStockPreference;

		private MelonPreferences_Entry<float> checkIntervalPreference;

		private MelonPreferences_Entry<bool> sprintPreference;

		private MelonPreferences_Entry<bool> allowClientConfigurationPreference;

		private float nextCheckTime;

		private float nextJourneyTickTime;

		private Dealer? pendingSourceDealer;

		private Collider? selectionTargetCollider;

		private Bounds? selectionTargetBounds;

		private PlaceableStorageEntity? outlinedStorage;

		private int outlinedStorageId = int.MinValue;

		private bool outlinedStorageIsValid;

		private DeadDrop? outlinedDeadDrop;

		private Outlinable? deadDropOutlineEffect;

		private int outlinedDeadDropId = int.MinValue;

		private bool outlinedDeadDropIsValid;

		private string selectionTargetText = string.Empty;

		private bool selectionTargetIsValid;

		private int suppressInteractionThroughFrame = -1;

		private bool phoneWasOpenable;

		private bool hotbarWasEnabled;

		private bool equippingWasEnabled;

		private bool selectionControlsCaptured;

		private bool phoneControlsCaptured;

		private bool inventoryControlsCaptured;

		private bool selectionTargetingActive;

		private float selectionActivationAt;

		private readonly Dictionary<int, SelectionResolution> selectionResolutionCache = new Dictionary<int, SelectionResolution>();

		private List<SavedAssignment>? pendingSaveRestore;

		private float saveRestoreStartedAt;

		private float nextSaveRestoreAttemptAt;

		private const int NetworkMagic = 1145131597;

		private const int NetworkProtocol = 1;

		private const float NetworkSnapshotInterval = 1f;

		private const float NetworkRequestInterval = 0.25f;

		private const float NetworkPeerTimeout = 5f;

		private const int MaxNetworkPacketSize = 1024;

		private readonly Dictionary<int, float> lastMutationRequestAt = new Dictionary<int, float>();

		private readonly Dictionary<int, float> lastSnapshotRequestAt = new Dictionary<int, float>();

		private readonly Dictionary<string, JourneyState> remoteJourneyStates = new Dictionary<string, JourneyState>(StringComparer.Ordinal);

		private ServerManager? registeredServerManager;

		private ClientManager? registeredClientManager;

		private Action<NetworkConnection, DealerAutoRestockBroadcast>? serverPacketHandler;

		private Action<DealerAutoRestockBroadcast>? clientPacketHandler;

		private Action<Writer, DealerAutoRestockBroadcast>? broadcastWriter;

		private Func<Reader, DealerAutoRestockBroadcast>? broadcastReader;

		private float nextNetworkSnapshotAt;

		private float nextSnapshotRequestAt;

		private float lastServerPacketAt = float.MinValue;

		private int networkRevision;

		private int nextRequestId;

		private int remoteTargetStock = 20;

		private bool remoteConfigurationAllowed;

		private bool networkAuthorityInitialized;

		private bool networkWasServerAuthority;

		private int TargetStock => Math.Clamp(targetStockPreference.Value, 1, 1000);

		private float CheckInterval => Math.Clamp(checkIntervalPreference.Value, 1f, 30f);

		internal static bool ShouldSuppressInteraction
		{
			get
			{
				if (Instance != null)
				{
					if (!((Object)(object)Instance.pendingSourceDealer != (Object)null))
					{
						return Time.frameCount <= Instance.suppressInteractionThroughFrame;
					}
					return true;
				}
				return false;
			}
		}

		internal static DealerAutoRestockMod? Instance { get; private set; }

		internal bool IsServerAuthority
		{
			get
			{
				ServerManager serverManager = InstanceFinder.ServerManager;
				if (serverManager == null)
				{
					return false;
				}
				return serverManager.Started;
			}
		}

		internal bool CanConfigureAssignments
		{
			get
			{
				if (!IsServerAuthority)
				{
					if (remoteConfigurationAllowed)
					{
						ClientManager? obj = registeredClientManager;
						if (obj != null && obj.Started)
						{
							return Time.unscaledTime - lastServerPacketAt <= 5f;
						}
					}
					return false;
				}
				return true;
			}
		}

		private int DisplayedTargetStock
		{
			get
			{
				if (!IsServerAuthority)
				{
					return remoteTargetStock;
				}
				return TargetStock;
			}
		}

		public override void OnInitializeMelon()
		{
			MelonPreferences_Category val = MelonPreferences.CreateCategory("DealerAutoRestock", "Dealer Auto Restock");
			targetStockPreference = val.CreateEntry<int>("TargetStock", 20, "Target stock", $"Total sellable product units carried after restocking. Packages contain 1, jars 5, and bags 20. Range: 1-{1000}.", false, false, (ValueValidator)null, (string)null);
			checkIntervalPreference = val.CreateEntry<float>("CheckIntervalSeconds", 3f, "Check interval", "Seconds between dealer stock checks. Range: 1-30.", false, false, (ValueValidator)null, (string)null);
			sprintPreference = val.CreateEntry<bool>("SprintToRestock", false, "Sprint to restock", "Makes dealers run while travelling to their assigned restock source.", false, false, (ValueValidator)null, (string)null);
			allowClientConfigurationPreference = val.CreateEntry<bool>("AllowClientConfiguration", true, "Allow client configuration", "Allows connected players with the mod to assign and disable dealer restock sources. The host validates every request.", false, false, (ValueValidator)null, (string)null);
			Instance = this;
			((MelonBase)this).LoggerInstance.Msg("Initialized. Configure recruited dealers from the Auto Restock phone app.");
		}

		public override void OnUpdate()
		{
			try
			{
				UpdateMultiplayer();
				DealerRestockPhoneApp.Tick();
				HandleSourceSelection();
				RestoreSavedAssignments();
				if (Time.unscaledTime >= nextJourneyTickTime)
				{
					nextJourneyTickTime = Time.unscaledTime + 0.1f;
					UpdateJourneys();
				}
				if (!(Time.unscaledTime < nextCheckTime))
				{
					nextCheckTime = Time.unscaledTime + CheckInterval;
					UpdateAssignments();
				}
			}
			catch (Exception value)
			{
				((MelonBase)this).LoggerInstance.Error($"Update failed: {value}");
			}
		}

		public override void OnGUI()
		{
			if (selectionTargetingActive)
			{
				DrawSourceSelectionHud();
			}
		}

		public override void OnDeinitializeMelon()
		{
			ShutdownMultiplayer();
			EndSourceSelection();
			FillJourneySnapshot();
			foreach (Journey item in journeySnapshot)
			{
				FinishJourney(item, "Restored " + ((NPC)item.Assignment.Dealer).fullName + " during mod shutdown.");
			}
			Instance = null;
		}

		internal IReadOnlyList<Dealer> GetRecruitedDealers()
		{
			List<Dealer> list = new List<Dealer>();
			List<Dealer> allPlayerDealers = Dealer.AllPlayerDealers;
			if (allPlayerDealers == null)
			{
				return list;
			}
			Enumerator<Dealer> enumerator = allPlayerDealers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dealer current = enumerator.Current;
				if ((Object)(object)current != (Object)null && current.IsRecruited)
				{
					list.Add(current);
				}
			}
			list.Sort((Dealer left, Dealer right) => string.Compare(((NPC)left).fullName, ((NPC)right).fullName, StringComparison.OrdinalIgnoreCase));
			return list;
		}

		internal string GetAssignmentText(Dealer dealer)
		{
			if (!assignments.TryGetValue(((NPC)dealer).ID, out Assignment value))
			{
				return "Disabled";
			}
			if (!string.Equals(value.StorageName, value.DestinationName, StringComparison.OrdinalIgnoreCase))
			{
				return value.StorageName + " - " + value.DestinationName;
			}
			return value.StorageName;
		}

		internal DealerUiState GetDealerUiState(Dealer dealer)
		{
			int dealerStock = dealer.GetPackagedProductAmount();
			if (!assignments.TryGetValue(((NPC)dealer).ID, out Assignment assignment))
			{
				return new DealerUiState(assigned: false, "DISABLED", "No restock source assigned", DealerUiTone.Muted, dealerStock, DisplayedTargetStock, 0, string.Empty, string.Empty);
			}
			int sourceStock = CountPackagedProductUnits(assignment.StorageEntity);
			string sourceType = ((assignment.SourceKind == RestockSourceKind.DeadDrop) ? "DEAD DROP" : "STORAGE");
			if (TryGetDisplayedJourneyState(((NPC)dealer).ID, out var state))
			{
				return state switch
				{
					JourneyState.LeavingCurrentBuilding => CreateState("DEPARTING", "Leaving current location", DealerUiTone.Working), 
					JourneyState.GoingToProperty => CreateState("EN ROUTE", "Heading to " + assignment.DestinationName, DealerUiTone.Working), 
					JourneyState.Collecting => CreateState("COLLECTING", "Loading products at " + assignment.StorageName, DealerUiTone.Working), 
					JourneyState.WaitingForInventorySync => CreateState("SYNCING", "Waiting for inventory synchronization", DealerUiTone.Working), 
					JourneyState.ExitingProperty => CreateState("FINISHING", "Returning to the normal schedule", DealerUiTone.Working), 
					_ => CreateState("ACTIVE", "Auto restock enabled", DealerUiTone.Active), 
				};
			}
			if (!((NPC)dealer).IsConscious)
			{
				return CreateState("UNAVAILABLE", "Dealer is unconscious", DealerUiTone.Danger);
			}
			if (((NPC)dealer).IsPanicked)
			{
				return CreateState("PAUSED", "Dealer is panicked", DealerUiTone.Warning);
			}
			if (((NPC)dealer).IsInVehicle)
			{
				return CreateState("PAUSED", "Dealer is currently in a vehicle", DealerUiTone.Warning);
			}
			if ((Object)(object)dealer.currentContract != (Object)null || ((Object)(object)dealer._attendDealBehaviour != (Object)null && ((Behaviour)dealer._attendDealBehaviour).Active) || IsDealerInDialogue(dealer))
			{
				return CreateState("BUSY", "Waiting for the dealer to become available", DealerUiTone.Warning);
			}
			if (!IsStorageAvailable(assignment))
			{
				return CreateState("SOURCE BUSY", "Waiting for access to the restock source", DealerUiTone.Warning);
			}
			if (dealerStock > 0)
			{
				return CreateState("STOCKED", "Ready for customer orders", DealerUiTone.Active);
			}
			if (sourceStock == 0)
			{
				return CreateState("SOURCE EMPTY", "No packaged products available", DealerUiTone.Danger);
			}
			return CreateState("READY", "Restock trip will begin shortly", DealerUiTone.Active);
			DealerUiState CreateState(string status, string detail, DealerUiTone tone)
			{
				return new DealerUiState(assigned: true, status, detail, tone, dealerStock, DisplayedTargetStock, sourceStock, assignment.StorageName, sourceType, assignment.DestinationName);
			}
		}

		private static int CountPackagedProductUnits(StorageEntity? storage)
		{
			if (((storage != null) ? storage.ItemSlots : null) == null)
			{
				return 0;
			}
			int num = 0;
			Enumerator<ItemSlot> enumerator = storage.ItemSlots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				ItemInstance itemInstance = current.ItemInstance;
				ProductItemInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
				if ((Object)(object)((val != null) ? val.AppliedPackaging : null) != (Object)null && current.Quantity > 0 && !current.IsLocked && !current.IsRemovalLocked)
				{
					num += current.Quantity * Math.Max(1, val.Amount);
				}
			}
			return num;
		}

		internal bool AssignFromPhone(Dealer dealer, RestockSource source, out string message)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)dealer == (Object)null || !dealer.IsRecruited)
			{
				message = "Dealer is no longer available.";
				return false;
			}
			if (!((NetworkBehaviour)dealer).IsServerInitialized)
			{
				return SendAssignmentRequest(((NPC)dealer).ID, source.SourceKind, source.SourceGuid, out message);
			}
			if ((Object)(object)source.StorageEntity == (Object)null || (Object)(object)source.StorageTransform == (Object)null)
			{
				message = "The selected source is no longer available.";
				return false;
			}
			if (!IsAuthorizedRestockSource(source))
			{
				message = "The selected storage is not on an owned property.";
				return false;
			}
			SetAssignment(dealer, new Assignment(dealer, source.StorageEntity, source.StorageTransform, source.StorageName, source.DestinationName, source.ExteriorPoint, source.SourceKind, source.SourceGuid, source.PlaceableStorage));
			message = ((NPC)dealer).fullName + " assigned to " + source.DisplayName + ".";
			ShowStatus(message);
			return true;
		}

		internal bool BeginSourceSelection(Dealer dealer, out string message)
		{
			if ((Object)(object)dealer == (Object)null || !dealer.IsRecruited)
			{
				message = "Dealer is no longer available.";
				return false;
			}
			if (!((NetworkBehaviour)dealer).IsServerInitialized && !CanConfigureAssignments)
			{
				message = "The host is not running a compatible Dealer Auto Restock version.";
				return false;
			}
			EndSourceSelection();
			pendingSourceDealer = dealer;
			float num = (PlayerSingleton<Phone>.InstanceExists ? PlayerSingleton<Phone>.Instance.rotationTime : 0f);
			selectionActivationAt = Time.unscaledTime + Mathf.Max(0.35f, num + 0.1f);
			message = string.Empty;
			((MelonBase)this).LoggerInstance.Msg("Entering source selection for " + ((NPC)dealer).fullName + ".");
			return true;
		}

		internal string ClearAssignment(Dealer dealer)
		{
			if ((Object)(object)dealer == (Object)null)
			{
				return "Dealer is no longer available.";
			}
			if (!((NetworkBehaviour)dealer).IsServerInitialized)
			{
				return SendClearRequest(((NPC)dealer).ID);
			}
			if (journeys.TryGetValue(((NPC)dealer).ID, out Journey value))
			{
				FinishJourney(value, "Assignment cleared from phone app.");
			}
			RemovePendingSaveRestore(((NPC)dealer).ID);
			string text = (assignments.Remove(((NPC)dealer).ID) ? ("Restocking disabled for " + ((NPC)dealer).fullName + ".") : (((NPC)dealer).fullName + " already has auto restock disabled."));
			ShowStatus(text);
			DealerAutoRestockSave.SyncFromMod();
			MarkNetworkStateDirty();
			return text;
		}

		private void HandleSourceSelection()
		{
			if ((Object)(object)pendingSourceDealer == (Object)null)
			{
				return;
			}
			if (Input.GetKeyDown((KeyCode)27) || Input.GetMouseButtonDown(1))
			{
				((MelonBase)this).LoggerInstance.Msg("Source selection cancelled.");
				suppressInteractionThroughFrame = Time.frameCount + 1;
				EndSourceSelection();
				return;
			}
			if (!selectionTargetingActive)
			{
				if (!(Time.unscaledTime < selectionActivationAt))
				{
					if (!CaptureSelectionControls())
					{
						ShowStatus("Could not enter source selection mode. See the MelonLoader log.");
					}
					else
					{
						selectionTargetingActive = true;
					}
				}
				return;
			}
			UpdateSelectionTarget(out RestockSource source);
			if (Input.GetKeyDown((KeyCode)101) && source != null)
			{
				AssignFromPhone(pendingSourceDealer, source, out string _);
				suppressInteractionThroughFrame = Time.frameCount + 1;
				EndSourceSelection();
			}
		}

		private void UpdateSelectionTarget(out RestockSource? source)
		{
			SelectionResolution selectionResolution = ResolveAimedRestockSource();
			source = selectionResolution.Source;
			selectionTargetIsValid = selectionResolution.Source != null;
			selectionTargetText = selectionResolution.Source?.DisplayName ?? selectionResolution.Error;
			selectionTargetCollider = selectionResolution.TargetCollider;
			selectionTargetBounds = selectionResolution.TargetBounds;
			SetOutlinedStorage(selectionResolution.OutlineStorage, selectionTargetIsValid);
			SetOutlinedDeadDrop(selectionResolution.OutlineDeadDrop, selectionTargetIsValid);
		}

		private void SetOutlinedStorage(PlaceableStorageEntity? storage, bool valid)
		{
			//IL_008d: 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)
			int num = (((Object)(object)storage != (Object)null) ? ((Object)storage).GetInstanceID() : int.MinValue);
			if (num == outlinedStorageId && valid == outlinedStorageIsValid)
			{
				return;
			}
			HideOutlinedStorage();
			outlinedStorage = storage;
			outlinedStorageId = num;
			outlinedStorageIsValid = valid;
			if ((Object)(object)outlinedStorage == (Object)null)
			{
				return;
			}
			try
			{
				((BuildableItem)outlinedStorage).ShowOutline(valid ? new Color(0.2f, 0.95f, 0.35f, 1f) : new Color(1f, 0.2f, 0.16f, 1f));
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Failed to show source outline: " + ex.Message);
			}
		}

		private void HideOutlinedStorage()
		{
			if ((Object)(object)outlinedStorage != (Object)null)
			{
				try
				{
					((BuildableItem)outlinedStorage).HideOutline();
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Failed to hide source outline: " + ex.Message);
				}
			}
			outlinedStorage = null;
			outlinedStorageId = int.MinValue;
		}

		private void SetOutlinedDeadDrop(DeadDrop? deadDrop, bool valid)
		{
			//IL_0150: 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_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			int num = (((Object)(object)deadDrop != (Object)null) ? ((Object)deadDrop).GetInstanceID() : int.MinValue);
			if (num == outlinedDeadDropId && valid == outlinedDeadDropIsValid)
			{
				return;
			}
			HideOutlinedDeadDrop();
			outlinedDeadDrop = deadDrop;
			outlinedDeadDropId = num;
			outlinedDeadDropIsValid = valid;
			if ((Object)(object)outlinedDeadDrop == (Object)null)
			{
				return;
			}
			try
			{
				GameObject gameObject = ((Component)outlinedDeadDrop).gameObject;
				deadDropOutlineEffect = gameObject.GetComponent<Outlinable>();
				if ((Object)(object)deadDropOutlineEffect == (Object)null)
				{
					deadDropOutlineEffect = gameObject.AddComponent<Outlinable>();
					deadDropOutlineEffect.OutlineParameters.BlurShift = 0f;
					deadDropOutlineEffect.OutlineParameters.DilateShift = 0.5f;
					deadDropOutlineEffect.OutlineParameters.FillPass.Shader = Resources.Load<Shader>("Easy performant outline/Shaders/Fills/ColorFill");
					foreach (MeshRenderer componentsInChild in gameObject.GetComponentsInChildren<MeshRenderer>())
					{
						((Renderer)componentsInChild).allowOcclusionWhenDynamic = false;
						deadDropOutlineEffect.TryAddTarget(new OutlineTarget((Renderer)(object)componentsInChild, 0));
					}
				}
				Color val = (valid ? new Color(0.2f, 0.95f, 0.35f, 1f) : new Color(1f, 0.2f, 0.16f, 1f));
				deadDropOutlineEffect.OutlineParameters.Color = val;
				Color32 val2 = Color32.op_Implicit(val);
				val2.a = 9;
				deadDropOutlineEffect.OutlineParameters.FillPass.SetColor("_PublicColor", Color32.op_Implicit(val2));
				((Behaviour)deadDropOutlineEffect).enabled = true;
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Failed to show dead drop outline: " + ex.Message);
				deadDropOutlineEffect = null;
			}
		}

		private void HideOutlinedDeadDrop()
		{
			if ((Object)(object)deadDropOutlineEffect != (Object)null)
			{
				try
				{
					((Behaviour)deadDropOutlineEffect).enabled = false;
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Failed to hide dead drop outline: " + ex.Message);
				}
			}
			deadDropOutlineEffect = null;
			outlinedDeadDrop = null;
			outlinedDeadDropId = int.MinValue;
		}

		private bool CaptureSelectionControls()
		{
			if (selectionControlsCaptured)
			{
				return true;
			}
			selectionControlsCaptured = true;
			try
			{
				if (PlayerSingleton<Phone>.InstanceExists)
				{
					Phone instance = PlayerSingleton<Phone>.Instance;
					phoneWasOpenable = instance.isOpenable;
					phoneControlsCaptured = true;
					instance.SetOpenable(false);
				}
				if (Singleton<GameplayMenu>.InstanceExists)
				{
					Singleton<GameplayMenu>.Instance.SetIsOpen(false);
				}
				else if (PlayerSingleton<Phone>.InstanceExists)
				{
					PlayerSingleton<Phone>.Instance.SetIsOpen(false);
				}
				if (PlayerSingleton<PlayerInventory>.InstanceExists)
				{
					PlayerInventory instance2 = PlayerSingleton<PlayerInventory>.Instance;
					hotbarWasEnabled = instance2.HotbarEnabled;
					equippingWasEnabled = instance2.EquippingEnabled;
					inventoryControlsCaptured = true;
					instance2.SetInventoryEnabled(false);
					instance2.SetEquippingEnabled(false);
				}
				return true;
			}
			catch (Exception value)
			{
				((MelonBase)this).LoggerInstance.Error($"Failed to capture source-selection controls: {value}");
				EndSourceSelection();
				return false;
			}
		}

		private void EndSourceSelection()
		{
			HideOutlinedStorage();
			HideOutlinedDeadDrop();
			if (selectionControlsCaptured)
			{
				try
				{
					if (phoneControlsCaptured && PlayerSingleton<Phone>.InstanceExists)
					{
						PlayerSingleton<Phone>.Instance.SetOpenable(phoneWasOpenable);
					}
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Failed to restore phone controls: " + ex.Message);
				}
				try
				{
					if (inventoryControlsCaptured && PlayerSingleton<PlayerInventory>.InstanceExists)
					{
						PlayerInventory instance = PlayerSingleton<PlayerInventory>.Instance;
						instance.SetInventoryEnabled(hotbarWasEnabled);
						instance.SetEquippingEnabled(equippingWasEnabled);
					}
				}
				catch (Exception ex2)
				{
					((MelonBase)this).LoggerInstance.Warning("Failed to restore inventory controls: " + ex2.Message);
				}
			}
			pendingSourceDealer = null;
			selectionTargetText = string.Empty;
			selectionTargetIsValid = false;
			selectionTargetCollider = null;
			selectionTargetBounds = null;
			selectionTargetingActive = false;
			selectionActivationAt = 0f;
			selectionResolutionCache.Clear();
			selectionControlsCaptured = false;
			phoneControlsCaptured = false;
			inventoryControlsCaptured = false;
		}

		private SelectionResolution ResolveAimedRestockSource()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			RaycastHit hit = default(RaycastHit);
			if ((Object)(object)main == (Object)null || !Physics.Raycast(((Component)main).transform.position, ((Component)main).transform.forward, ref hit, 8f))
			{
				return SelectionResolution.NoTarget;
			}
			PlaceableStorageEntity componentInParent = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<PlaceableStorageEntity>();
			int num = (((Object)(object)componentInParent != (Object)null) ? ((Object)componentInParent).GetInstanceID() : ((Object)((RaycastHit)(ref hit)).collider).GetInstanceID());
			if (selectionResolutionCache.TryGetValue(num, out SelectionResolution value))
			{
				return value;
			}
			if ((Object)(object)componentInParent != (Object)null)
			{
				Collider targetCollider = (Collider)(((Object)(object)((BuildableItem)componentInParent).BoundingCollider != (Object)null) ? ((object)((BuildableItem)componentInParent).BoundingCollider) : ((object)((RaycastHit)(ref hit)).collider));
				if (!((Object)(object)((Il2CppObjectBase)componentInParent).TryCast<BedItem>() != (Object)null))
				{
					StorageEntity storageEntity = componentInParent.StorageEntity;
					if (((storageEntity != null) ? storageEntity.ItemSlots : null) != null && componentInParent.StorageEntity.ItemSlots.Count != 0)
					{
						Property val = FindStorageProperty(componentInParent);
						if ((Object)(object)val == (Object)null)
						{
							return CacheSelectionResolution(num, new SelectionResolution(null, "That storage is not attached to a player property.", targetCollider, componentInParent));
						}
						if (!val.IsOwned)
						{
							return CacheSelectionResolution(num, new SelectionResolution(null, "That storage is not on an owned property.", targetCollider, componentInParent));
						}
						if (!TryGetPropertyAccessPoint(componentInParent, val, out Vector3 accessPoint, out string _))
						{
							return CacheSelectionResolution(num, new SelectionResolution(null, "No reachable entrance found for " + val.PropertyName + ".", targetCollider, componentInParent));
						}
						return CacheSelectionResolution(num, new SelectionResolution(new RestockSource(componentInParent.Name + " - " + val.PropertyName, componentInParent.StorageEntity, ((Component)componentInParent).transform, componentInParent.Name, val.PropertyName, accessPoint, RestockSourceKind.PlaceableStorage, ((object)((BuildableItem)componentInParent).GUID/*cast due to .constrained prefix*/).ToString(), componentInParent), string.Empty, targetCollider, componentInParent));
					}
				}
				return CacheSelectionResolution(num, new SelectionResolution(null, "That object is not a usable product storage.", targetCollider, componentInParent));
			}
			DeadDrop val2 = ResolveAimedDeadDrop(hit);
			if ((Object)(object)val2 == (Object)null)
			{
				return CacheSelectionResolution(num, new SelectionResolution(null, "No valid storage or dead drop under the crosshair.", null, null));
			}
			if ((Object)(object)val2.Storage == (Object)null || ((StorageEntity)val2.Storage).ItemSlots == null || ((StorageEntity)val2.Storage).ItemSlots.Count == 0)
			{
				return CacheSelectionResolution(num, new SelectionResolution(null, "That dead drop is not a usable product storage.", ((RaycastHit)(ref hit)).collider, null, TryGetDeadDropBounds(val2), val2));
			}
			return CacheSelectionResolution(num, new SelectionResolution(new RestockSource("Dead drop - " + val2.DeadDropName, (StorageEntity)(object)val2.Storage, ((Component)val2).transform, val2.DeadDropName, val2.DeadDropName, ((Component)val2).transform.position, RestockSourceKind.DeadDrop, ((object)val2.GUID/*cast due to .constrained prefix*/).ToString()), string.Empty, ((RaycastHit)(ref hit)).collider, null, TryGetDeadDropBounds(val2), val2));
		}

		private SelectionResolution CacheSelectionResolution(int targetId, SelectionResolution resolution)
		{
			selectionResolutionCache[targetId] = resolution;
			return resolution;
		}

		private static Bounds? TryGetDeadDropBounds(DeadDrop deadDrop)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)deadDrop.Storage == (Object)null)
			{
				return null;
			}
			Il2CppArrayBase<Renderer> componentsInChildren = ((Component)deadDrop.Storage).GetComponentsInChildren<Renderer>(true);
			Bounds? result = null;
			foreach (Renderer item in componentsInChildren)
			{
				if (!((Object)(object)item == (Object)null) && item.enabled)
				{
					if (result.HasValue)
					{
						Bounds value = result.Value;
						((Bounds)(ref value)).Encapsulate(item.bounds);
						result = value;
					}
					else
					{
						result = item.bounds;
					}
				}
			}
			return result;
		}

		private static DeadDrop? ResolveAimedDeadDrop(RaycastHit hit)
		{
			DeadDrop componentInParent = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<DeadDrop>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return componentInParent;
			}
			WorldStorageEntity componentInParent2 = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<WorldStorageEntity>();
			List<DeadDrop> deadDrops = DeadDrop.DeadDrops;
			if ((Object)(object)componentInParent2 == (Object)null || deadDrops == null)
			{
				return null;
			}
			Enumerator<DeadDrop> enumerator = deadDrops.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DeadDrop current = enumerator.Current;
				if (!((Object)(object)current == (Object)null) && (Object)(object)current.Storage == (Object)(object)componentInParent2)
				{
					return current;
				}
			}
			return null;
		}

		private void SetAssignment(Dealer dealer, Assignment assignment)
		{
			if (journeys.TryGetValue(((NPC)dealer).ID, out Journey value))
			{
				FinishJourney(value, "Assignment changed while the dealer was travelling.");
			}
			RemovePendingSaveRestore(((NPC)dealer).ID);
			assignments[((NPC)dealer).ID] = assignment;
			DealerAutoRestockSave.SyncFromMod();
			MarkNetworkStateDirty();
		}

		private void RemovePendingSaveRestore(string dealerId)
		{
			pendingSaveRestore?.RemoveAll((SavedAssignment saved) => string.Equals(saved.DealerId, dealerId, StringComparison.Ordinal));
		}

		internal List<SavedAssignment> CreateSaveSnapshot()
		{
			if (!IsServerAuthority)
			{
				ClientManager? obj = registeredClientManager;
				if (obj != null && obj.Started)
				{
					return new List<SavedAssignment>();
				}
			}
			List<SavedAssignment> list = new List<SavedAssignment>(assignments.Count);
			foreach (Assignment value in assignments.Values)
			{
				if ((Object)(object)value.Dealer != (Object)null && value.Dealer.IsRecruited)
				{
					list.Add(new SavedAssignment
					{
						DealerId = value.DealerId,
						SourceKind = value.SourceKind,
						SourceGuid = value.SourceGuid,
						SourceName = value.StorageName
					});
				}
			}
			return list;
		}

		internal void QueueSaveRestore(IEnumerable<SavedAssignment> savedAssignments)
		{
			PrepareForSaveLoad();
			pendingSaveRestore = (from saved in savedAssignments
				where !string.IsNullOrWhiteSpace(saved.DealerId) && !string.IsNullOrWhiteSpace(saved.SourceGuid)
				select new SavedAssignment
				{
					DealerId = saved.DealerId,
					SourceKind = saved.SourceKind,
					SourceGuid = saved.SourceGuid,
					SourceName = saved.SourceName
				}).ToList();
			saveRestoreStartedAt = -1f;
			nextSaveRestoreAttemptAt = 0f;
		}

		internal void PrepareForSaveLoad()
		{
			EndSourceSelection();
			FillJourneySnapshot();
			foreach (Journey item in journeySnapshot)
			{
				FinishJourney(item, "Restock trip stopped while loading a save.");
			}
			assignments.Clear();
			pendingSaveRestore = null;
		}

		private void RestoreSavedAssignments()
		{
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			if (!IsServerAuthority)
			{
				ClientManager? obj = registeredClientManager;
				if (obj != null && obj.Started)
				{
					pendingSaveRestore = null;
					return;
				}
			}
			if (pendingSaveRestore == null || !Singleton<LoadManager>.InstanceExists || !Singleton<LoadManager>.Instance.IsGameLoaded)
			{
				return;
			}
			if (saveRestoreStartedAt < 0f)
			{
				saveRestoreStartedAt = Time.unscaledTime;
			}
			if (Time.unscaledTime < nextSaveRestoreAttemptAt)
			{
				return;
			}
			nextSaveRestoreAttemptAt = Time.unscaledTime + 0.5f;
			for (int num = pendingSaveRestore.Count - 1; num >= 0; num--)
			{
				SavedAssignment savedAssignment = pendingSaveRestore[num];
				Dealer val = FindRecruitedDealer(savedAssignment.DealerId);
				if (!((Object)(object)val == (Object)null) && TryResolveSavedSource(savedAssignment, out RestockSource source))
				{
					assignments[((NPC)val).ID] = new Assignment(val, source.StorageEntity, source.StorageTransform, source.StorageName, source.DestinationName, source.ExteriorPoint, source.SourceKind, source.SourceGuid, source.PlaceableStorage);
					pendingSaveRestore.RemoveAt(num);
					((MelonBase)this).LoggerInstance.Msg($"Restored auto restock for {((NPC)val).fullName}: {source.DisplayName}.");
				}
			}
			if (pendingSaveRestore.Count > 0 && Time.unscaledTime - saveRestoreStartedAt < 15f)
			{
				return;
			}
			foreach (SavedAssignment item in pendingSaveRestore)
			{
				((MelonBase)this).LoggerInstance.Warning($"Could not restore auto restock for dealer {item.DealerId}: {item.SourceKind} {item.SourceName} ({item.SourceGuid}) is unavailable.");
			}
			pendingSaveRestore = null;
			DealerAutoRestockSave.SyncFromMod();
			MarkNetworkStateDirty();
		}

		private Dealer? FindRecruitedDealer(string dealerId)
		{
			List<Dealer> allPlayerDealers = Dealer.AllPlayerDealers;
			if (allPlayerDealers == null)
			{
				return null;
			}
			Enumerator<Dealer> enumerator = allPlayerDealers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dealer current = enumerator.Current;
				if ((Object)(object)current != (Object)null && current.IsRecruited && string.Equals(((NPC)current).ID, dealerId, StringComparison.Ordinal))
				{
					return current;
				}
			}
			return null;
		}

		private bool TryResolveSavedSource(SavedAssignment saved, out RestockSource source)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (saved.SourceKind == RestockSourceKind.PlaceableStorage)
			{
				foreach (PlaceableStorageEntity item in Object.FindObjectsOfType<PlaceableStorageEntity>(true))
				{
					if (!((Object)(object)item == (Object)null) && string.Equals(((object)((BuildableItem)item).GUID/*cast due to .constrained prefix*/).ToString(), saved.SourceGuid, StringComparison.OrdinalIgnoreCase))
					{
						Property val = FindStorageProperty(item);
						if ((Object)(object)item.StorageEntity != (Object)null && val != null && val.IsOwned && TryGetPropertyAccessPoint(item, val, out Vector3 accessPoint, out string _))
						{
							source = new RestockSource(item.Name + " - " + val.PropertyName, item.StorageEntity, ((Component)item).transform, item.Name, val.PropertyName, accessPoint, RestockSourceKind.PlaceableStorage, saved.SourceGuid, item);
							return true;
						}
					}
				}
			}
			else if (saved.SourceKind == RestockSourceKind.DeadDrop && DeadDrop.DeadDrops != null)
			{
				Enumerator<DeadDrop> enumerator2 = DeadDrop.DeadDrops.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					DeadDrop current2 = enumerator2.Current;
					if (!((Object)(object)current2 == (Object)null) && !((Object)(object)current2.Storage == (Object)null) && string.Equals(((object)current2.GUID/*cast due to .constrained prefix*/).ToString(), saved.SourceGuid, StringComparison.OrdinalIgnoreCase))
					{
						source = new RestockSource("Dead drop - " + current2.DeadDropName, (StorageEntity)(object)current2.Storage, ((Component)current2).transform, current2.DeadDropName, current2.DeadDropName, ((Component)current2).transform.position, RestockSourceKind.DeadDrop, saved.SourceGuid);
						return true;
					}
				}
			}
			source = null;
			return false;
		}

		private static bool IsAuthorizedRestockSource(RestockSource source)
		{
			if (source.SourceKind == RestockSourceKind.DeadDrop)
			{
				return true;
			}
			if (source.SourceKind == RestockSourceKind.PlaceableStorage && (Object)(object)source.PlaceableStorage != (Object)null)
			{
				Property? obj = FindStorageProperty(source.PlaceableStorage);
				if (obj == null)
				{
					return false;
				}
				return obj.IsOwned;
			}
			return false;
		}

		private void UpdateAssignments()
		{
			if (!IsServerAuthority)
			{
				return;
			}
			bool flag = false;
			KeyValuePair<string, Assignment>[] array = assignments.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<string, Assignment> keyValuePair = array[i];
				Assignment value = keyValuePair.Value;
				try
				{
					if ((Object)(object)value.Dealer == (Object)null || !value.Dealer.IsRecruited || (Object)(object)value.StorageEntity == (Object)null)
					{
						if (journeys.TryGetValue(keyValuePair.Key, out Journey value2))
						{
							FinishJourney(value2, "Restock trip stopped because its assignment is unavailable.");
						}
						assignments.Remove(keyValuePair.Key);
						flag = true;
					}
					else
					{
						UpdateAssignment(value);
					}
				}
				catch (Exception value3)
				{
					((MelonBase)this).LoggerInstance.Error($"Failed to update {value.DealerId}: {value3}");
					if (journeys.TryGetValue(value.DealerId, out Journey value4))
					{
						FinishJourney(value4, "Restock trip aborted after an error.");
					}
				}
			}
			if (flag)
			{
				DealerAutoRestockSave.SyncFromMod();
				MarkNetworkStateDirty();
			}
		}

		private void UpdateJourneys()
		{
			if (!IsServerAuthority)
			{
				return;
			}
			FillJourneySnapshot();
			foreach (Journey item in journeySnapshot)
			{
				try
				{
					item.EnforceRoute();
					UpdateJourney(item);
				}
				catch (Exception value)
				{
					((MelonBase)this).LoggerInstance.Error($"Failed to update journey for {item.Assignment.DealerId}: {value}");
					FinishJourney(item, "Restock trip aborted after an error.");
				}
			}
		}

		private void FillJourneySnapshot()
		{
			journeySnapshot.Clear();
			foreach (Journey value in journeys.Values)
			{
				journeySnapshot.Add(value);
			}
		}

		private void UpdateAssignment(Assignment assignment)
		{
			Dealer dealer = assignment.Dealer;
			if (!((Object)(object)dealer == (Object)null) && !((Object)(object)assignment.StorageEntity == (Object)null) && ((NetworkBehaviour)dealer).IsServerInitialized && !journeys.ContainsKey(((NPC)dealer).ID) && dealer.GetPackagedProductAmount() <= 0 && !(Time.unscaledTime < assignment.NextAttemptAt) && CanStartJourney(assignment))
			{
				StartJourney(assignment);
			}
		}

		private static bool CanStartJourney(Assignment assignment)
		{
			Dealer dealer = assignment.Dealer;
			if (!dealer.IsRecruited || !((NPC)dealer).IsConscious || ((NPC)dealer).IsInVehicle || ((NPC)dealer).IsPanicked)
			{
				return false;
			}
			if ((Object)(object)dealer.currentContract != (Object)null || ((Object)(object)dealer._attendDealBehaviour != (Object)null && ((Behaviour)dealer._attendDealBehaviour).Active))
			{
				return false;
			}
			if (IsDealerInDialogue(dealer))
			{
				return false;
			}
			StorageEntity storageEntity = assignment.StorageEntity;
			if (!((Object)(object)storageEntity == (Object)null) && !storageEntity.IsOpened && !((Object)(object)storageEntity.CurrentPlayerAccessor != (Object)null))
			{
				PlaceableStorageEntity? placeableStorage = assignment.PlaceableStorage;
				if (!((Object)(object)((placeableStorage != null) ? placeableStorage.NPCUserObject : null) != (Object)null))
				{
					Enumerator<ItemSlot> enumerator = storageEntity.ItemSlots.GetEnumerator();
					while (enumerator.MoveNext())
					{
						ItemSlot current = enumerator.Current;
						ItemInstance itemInstance = current.ItemInstance;
						ProductItemInstance obj = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
						if ((Object)(object)((obj != null) ? obj.AppliedPackaging : null) != (Object)null && current.Quantity > 0 && !current.IsLocked && !current.IsRemovalLocked)
						{
							return true;
						}
					}
					return false;