Decompiled source of InnangardServerLagFix v1.0.12

plugins/InnangardServerLagFix.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("InnangardServerLagFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("InnangardServerLagFix")]
[assembly: AssemblyTitle("InnangardServerLagFix")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace InnangardServerLagFix
{
	internal static class BedExitPositionTuning
	{
		private sealed class ExitPoint
		{
			internal Component Settler;

			internal Vector3 Position;
		}

		private const string PersistedBedExitKey = "inn_lagfix_bed_exit";

		private const string PersistedBedExitValidKey = "inn_lagfix_bed_exit_valid";

		private const float PersistedPoseMaxDrift = 6f;

		private static readonly ConditionalWeakTable<object, ExitPoint> ExitPoints = new ConditionalWeakTable<object, ExitPoint>();

		private static ManualLogSource _log;

		private static FieldInfo _settlerField;

		private static bool _installed;

		private static bool Active
		{
			get
			{
				if (Plugin.Enabled != null)
				{
					return Plugin.Enabled.Value;
				}
				return false;
			}
		}

		internal static void Initialize(ManualLogSource log, Harmony harmony)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			if (_installed || log == null || harmony == null)
			{
				return;
			}
			_log = log;
			Type type = AccessTools.TypeByName("Innangard.SettlerRest");
			if (type == null)
			{
				_log.LogWarning((object)"[BED-EXIT] Innangard.SettlerRest was not found; exact bed entry/exit restoration is unavailable.");
				return;
			}
			_settlerField = AccessTools.Field(type, "_settler");
			MethodInfo methodInfo = AccessTools.Method(type, "StartSleep", new Type[1] { typeof(Transform) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type, "StopSleep", Type.EmptyTypes, (Type[])null);
			Type type2 = AccessTools.TypeByName("Innangard.SettlerController");
			MethodInfo methodInfo3 = ((type2 != null) ? AccessTools.Method(type2, "Awake", Type.EmptyTypes, (Type[])null) : null);
			if (_settlerField == null || methodInfo == null || methodInfo2 == null)
			{
				_log.LogWarning((object)"[BED-EXIT] SettlerRest sleep bindings were incomplete; stock bed wake position remains unchanged.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BedExitPositionTuning), "StartSleepPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(BedExitPositionTuning), "StopSleepPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(BedExitPositionTuning), "SettlerAwakePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				_log.LogWarning((object)"[BED-RELOAD] Could not bind SettlerController.Awake; interrupted bed-pose restoration is unavailable.");
			}
			_installed = true;
			_log.LogVerbose("[BED-EXIT] All settlers leave a bed at the exact standing position from which they entered it. That proven floor point is persisted while asleep and restored after an interrupted unload/relog before normal pathing resumes.");
		}

		private static void StartSleepPrefix(object __instance)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || __instance == null || _settlerField == null)
			{
				return;
			}
			try
			{
				object? value = _settlerField.GetValue(__instance);
				Component val = (Component)((value is Component) ? value : null);
				if (!((Object)val == (Object)null))
				{
					Vector3 position = val.transform.position;
					ExitPoints.Remove(__instance);
					ExitPoints.Add(__instance, new ExitPoint
					{
						Settler = val,
						Position = position
					});
					PersistBedExit(val, position);
				}
			}
			catch (Exception ex)
			{
				if (Plugin.Diagnostics != null && Plugin.Diagnostics.Value)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("[BED-EXIT] Could not remember bed entry point: " + ex.GetType().Name + ": " + ex.Message));
					}
				}
			}
		}

		private static void StopSleepPostfix(object __instance)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || __instance == null || _settlerField == null)
			{
				return;
			}
			try
			{
				object? value = _settlerField.GetValue(__instance);
				Component val = (Component)((value is Component) ? value : null);
				if ((Object)val == (Object)null)
				{
					return;
				}
				bool flag = false;
				Vector3 point;
				if (ExitPoints.TryGetValue(__instance, out var value2) && value2 != null)
				{
					ExitPoints.Remove(__instance);
					if ((Object)value2.Settler != (Object)null)
					{
						val = value2.Settler;
						point = value2.Position;
						flag = true;
					}
					else
					{
						point = default(Vector3);
					}
				}
				else
				{
					flag = TryReadPersistedBedExit(val, out point);
				}
				if (flag)
				{
					ApplyBedExit(val, point);
				}
			}
			catch (Exception ex)
			{
				if (Plugin.Diagnostics != null && Plugin.Diagnostics.Value)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("[BED-EXIT] Could not restore bed entry point: " + ex.GetType().Name + ": " + ex.Message));
					}
				}
			}
		}

		private static void PersistBedExit(Component settler, Vector3 point)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = ViewOf(settler);
			if (!((Object)val == (Object)null) && val.IsValid() && val.IsOwner())
			{
				ZDO zDO = val.GetZDO();
				if (zDO != null)
				{
					zDO.Set("inn_lagfix_bed_exit", point);
					zDO.Set("inn_lagfix_bed_exit_valid", true);
				}
			}
		}

		private static bool TryReadPersistedBedExit(Component settler, out Vector3 point)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			point = default(Vector3);
			ZNetView val = ViewOf(settler);
			if ((Object)val == (Object)null || !val.IsValid() || !val.IsOwner())
			{
				return false;
			}
			ZDO zDO = val.GetZDO();
			if (zDO == null || !zDO.GetBool("inn_lagfix_bed_exit_valid", false))
			{
				return false;
			}
			point = zDO.GetVec3("inn_lagfix_bed_exit", settler.transform.position);
			return Finite(point);
		}

		private static void ApplyBedExit(Component settler, Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!Finite(point))
			{
				return;
			}
			settler.transform.position = point;
			Rigidbody component = settler.GetComponent<Rigidbody>();
			if ((Object)component != (Object)null)
			{
				component.position = point;
				component.useGravity = true;
				if (!component.isKinematic)
				{
					component.linearVelocity = Vector3.zero;
				}
			}
			ZNetView val = ViewOf(settler);
			if ((Object)val != (Object)null && val.IsValid() && val.IsOwner())
			{
				ZDO zDO = val.GetZDO();
				if (zDO != null)
				{
					zDO.SetPosition(point);
					zDO.Set("inn_lagfix_bed_exit_valid", false);
					zDO.Set("inn_lagfix_bed_exit", Vector3.zero);
				}
			}
		}

		private static ZNetView ViewOf(Component settler)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if ((Object)settler == (Object)null)
			{
				return null;
			}
			ZNetView val = settler.GetComponent<ZNetView>();
			if ((Object)val == (Object)null)
			{
				val = settler.GetComponentInParent<ZNetView>();
			}
			return val;
		}

		private static bool Finite(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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 (!float.IsNaN(point.x) && !float.IsNaN(point.y) && !float.IsNaN(point.z) && !float.IsInfinity(point.x) && !float.IsInfinity(point.y))
			{
				return !float.IsInfinity(point.z);
			}
			return false;
		}

		private static void SettlerAwakePostfix(object __instance)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || __instance == null)
			{
				return;
			}
			try
			{
				Component val = (Component)((__instance is Component) ? __instance : null);
				if ((Object)val == (Object)null || !TryReadPersistedBedExit(val, out var point))
				{
					return;
				}
				Vector3 position = val.transform.position;
				ZNetView val2 = ViewOf(val);
				ZDO val3 = (((Object)val2 != (Object)null && val2.IsValid()) ? val2.GetZDO() : null);
				if (!Finite(point) || Vector3.Distance(position, point) > 6f)
				{
					if (val3 != null && val2.IsOwner())
					{
						val3.Set("inn_lagfix_bed_exit_valid", false);
						val3.Set("inn_lagfix_bed_exit", Vector3.zero);
					}
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)"[BED-RELOAD] Discarded an implausible persisted bed-exit point instead of moving the resident across the world.");
					}
				}
				else
				{
					ApplyBedExit(val, point);
					_log?.LogVerbose("[BED-RELOAD] Restored a resident from an interrupted bed attach point to its proven pre-sleep floor position.");
				}
			}
			catch (Exception ex)
			{
				if (Plugin.Diagnostics != null && Plugin.Diagnostics.Value)
				{
					ManualLogSource log2 = _log;
					if (log2 != null)
					{
						log2.LogWarning((object)("[BED-RELOAD] Could not restore interrupted bed position: " + ex.GetType().Name + ": " + ex.Message));
					}
				}
			}
		}
	}
	internal static class BedStationManagementTuning
	{
		private sealed class PendingBedAssignment
		{
			internal object Settler;

			internal ZDOID Bed;

			internal float Until;
		}

		private readonly struct FavouriteChairRef
		{
			internal readonly ZDOID ViewId;

			internal readonly string SeatKey;

			internal bool IsNone => ViewId == ZDOID.None;

			internal FavouriteChairRef(ZDOID viewId, string seatKey)
			{
				//IL_0001: 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)
				ViewId = viewId;
				SeatKey = seatKey ?? string.Empty;
			}
		}

		private const string StationIgnoreKey = "inn_lagfix_ignore_station";

		private const string StationToggleRpc = "InnLagFix_StationIgnore_104";

		private const string BedAssignRpc = "InnLagFix_BedAssign_104";

		private const string BedAssignForceRpc = "InnLagFix_BedAssignForce_104";

		private const string FavouriteChairAssignRpc = "InnLagFix_FavouriteChairAssign_108seat";

		private const string BedKey = "inn_bed";

		internal const string FavouriteChairKey = "inn_favourite_chair";

		internal const string FavouriteChairSeatKey = "inn_favourite_chair_seat";

		private const string BedClaimKey = "inn_claim";

		private const string BedClaimIdentityKey = "inn_claim_identity";

		private const long BedOwnerMarker = 424242L;

		private const float BedAssignWaitSeconds = 4f;

		private static ManualLogSource _log;

		private static ConfigEntry<KeyCode> _modifier;

		private static Type _settlerType;

		private static Type _restType;

		private static Type _innConfigType;

		private static Type _caretakerJobType;

		private static Type _cookJobType;

		private static Type _frithType;

		private static Type _networkRequestType;

		private static Type _settlementRosterType;

		private static Type[] _stationTypes;

		private static FieldInfo _settlerViewField;

		private static FieldInfo _settlerInstancesField;

		private static PropertyInfo _restProperty;

		private static PropertyInfo _panelNameProperty;

		private static PropertyInfo _stableIdentityProperty;

		private static PropertyInfo _myZdoidProperty;

		private static PropertyInfo _homePositionProperty;

		private static MethodInfo _canManageMethod;

		private static MethodInfo _inSettlementAreaMethod;

		private static MethodInfo _releaseBedMethod;

		private static MethodInfo _claimBedMethod;

		private static MethodInfo _stopSleepMethod;

		private static FieldInfo _bedSearchRadiusField;

		private static FieldInfo _caretakerTargetField;

		private static FieldInfo _cookTargetField;

		private static FieldInfo _frithInstancesField;

		private static MethodInfo _frithCoversPointMethod;

		private static MethodInfo _frithCanManageMethod;

		private static PropertyInfo _frithOwnerIdProperty;

		private static PropertyInfo _frithNetProperty;

		private static MethodInfo _rosterTitleOfMethod;

		private static MethodInfo _networkAuthenticateMethod;

		private static object _selectedSettler;

		private static float _selectedUntil;

		private static readonly Dictionary<int, PendingBedAssignment> PendingBeds = new Dictionary<int, PendingBedAssignment>();

		private static readonly HashSet<int> RegisteredStationViews = new HashSet<int>();

		private static bool _loggedBedFailure;

		private static bool _loggedStationFailure;

		private static bool Active
		{
			get
			{
				if (Plugin.Enabled != null)
				{
					return Plugin.Enabled.Value;
				}
				return false;
			}
		}

		internal static void Initialize(ConfigFile config, ManualLogSource log, Harmony harmony)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			_log = log;
			_modifier = config.Bind<KeyCode>("UI", "ResidentStationManagementModifierKey", (KeyCode)306, "Modifier held with Valheim's normal Use/Interact key for Innangard management shortcuts: select a resident for bed/chair assignment, assign/swap a bed, assign/swap/unassign a favourite chair, or toggle an Innangard-operated production station ignored. Default LeftControl + Use. Player use of ignored stations is unchanged.");
			if ((int)_modifier.Value == 308)
			{
				_modifier.Value = (KeyCode)306;
			}
			_settlerType = AccessTools.TypeByName("Innangard.SettlerController");
			_restType = AccessTools.TypeByName("Innangard.SettlerRest");
			_innConfigType = AccessTools.TypeByName("Innangard.InnConfig");
			_caretakerJobType = AccessTools.TypeByName("Innangard.Jobs.CaretakerJob");
			_cookJobType = AccessTools.TypeByName("Innangard.Jobs.CookJob");
			_frithType = AccessTools.TypeByName("Innangard.Frithstone");
			_networkRequestType = AccessTools.TypeByName("Innangard.NetworkRequest");
			_settlementRosterType = AccessTools.TypeByName("Innangard.SettlementRoster");
			if (_settlerType == null || _restType == null)
			{
				_log.LogWarning((object)"[MANAGE] Innangard resident/bed internals not found; bed reassignment disabled.");
			}
			else
			{
				BindBedInternals();
				PatchBedManagement(harmony);
			}
			BindStationInternals();
			PatchStationManagement(harmony);
			_log.LogVerbose("[MANAGE] LeftControl+Use (configurable): select resident -> assign/swap bed or assign/swap/unassign favourite chair; operated production station -> toggle ignored by Innangard.");
			_log.LogVerbose("[FAVOURITE-CHAIR] Chair hover shows the loaded resident(s) who favour that exact seat. Multi-seat benches keep independent favourite-seat identities. A selected resident can assign a free seat, swap favourites with its current owner, or press the same seat again to unassign; chair selection stays active for repeated edits. Ordinary idle/social/meal seating still prefers the favourite whenever usable/free, then falls back to Innangard's normal nearest-seat choice.");
		}

		internal static void Tick()
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			if (!Active)
			{
				return;
			}
			if (_selectedSettler != null && Time.unscaledTime >= _selectedUntil)
			{
				_selectedSettler = null;
			}
			if (PendingBeds.Count == 0)
			{
				return;
			}
			List<int> list = null;
			foreach (KeyValuePair<int, PendingBedAssignment> pendingBed in PendingBeds)
			{
				PendingBedAssignment value = pendingBed.Value;
				if (value == null || value.Settler == null || Time.unscaledTime >= value.Until)
				{
					if (list == null)
					{
						list = new List<int>();
					}
					list.Add(pendingBed.Key);
					continue;
				}
				ZNetView val = SettlerView(value.Settler);
				if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && TryAssignBedNow(value.Settler, value.Bed, force: false))
				{
					if (list == null)
					{
						list = new List<int>();
					}
					list.Add(pendingBed.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (int item in list)
			{
				PendingBeds.Remove(item);
			}
		}

		internal static bool IsStationIgnored(ZNetView view)
		{
			if (!Active || (Object)(object)view == (Object)null || !view.IsValid() || !ViewBelongsToSupportedStation(view))
			{
				return false;
			}
			try
			{
				int num;
				if (view.GetZDO() != null)
				{
					num = (view.GetZDO().GetBool("inn_lagfix_ignore_station", false) ? 1 : 0);
					if (num != 0)
					{
						Plugin.ForgetStationLease(view);
					}
				}
				else
				{
					num = 0;
				}
				return (byte)num != 0;
			}
			catch
			{
				return false;
			}
		}

		private static void BindBedInternals()
		{
			_settlerViewField = AccessTools.Field(_settlerType, "_nview");
			_settlerInstancesField = AccessTools.Field(_settlerType, "Instances");
			_restProperty = AccessTools.Property(_settlerType, "Rest");
			_panelNameProperty = AccessTools.Property(_settlerType, "PanelName");
			_stableIdentityProperty = AccessTools.Property(_settlerType, "StableIdentity");
			_myZdoidProperty = AccessTools.Property(_settlerType, "MyZdoid");
			_homePositionProperty = AccessTools.Property(_settlerType, "HomePosition") ?? AccessTools.Property(_settlerType, "Home");
			_canManageMethod = AccessTools.Method(_settlerType, "CanManage", new Type[1] { typeof(long) }, (Type[])null);
			_inSettlementAreaMethod = AccessTools.Method(_settlerType, "InSettlementArea", new Type[1] { typeof(Vector3) }, (Type[])null);
			_releaseBedMethod = AccessTools.Method(_restType, "ReleaseBed", Type.EmptyTypes, (Type[])null);
			_claimBedMethod = AccessTools.Method(_restType, "ClaimBed", new Type[3]
			{
				typeof(Bed),
				typeof(float),
				typeof(string)
			}, (Type[])null);
			_stopSleepMethod = AccessTools.Method(_restType, "StopSleep", Type.EmptyTypes, (Type[])null);
			_bedSearchRadiusField = ((_innConfigType != null) ? AccessTools.Field(_innConfigType, "BedSearchRadius") : null);
		}

		private static bool TryPatch(Harmony harmony, MethodInfo original, string label, string prefixName = null, string postfixName = null)
		{
			//IL_0020: 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)
			if (original == null)
			{
				return false;
			}
			try
			{
				HarmonyMethod val = (string.IsNullOrEmpty(prefixName) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(BedStationManagementTuning), prefixName, (Type[])null));
				HarmonyMethod val2 = (string.IsNullOrEmpty(postfixName) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(BedStationManagementTuning), postfixName, (Type[])null));
				harmony.Patch((MethodBase)original, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("[MANAGE] Could not patch " + label + "; that management hook is disabled. " + ex.GetType().Name + ": " + ex.Message));
				return false;
			}
		}

		private static void PatchBedManagement(Harmony harmony)
		{
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(_settlerType, "Awake", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(_settlerType, "GetHoverText", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(_settlerType, "Interact", new Type[3]
			{
				typeof(Humanoid),
				typeof(bool),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(Bed), "GetHoverText", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(Bed), "Interact", new Type[3]
			{
				typeof(Humanoid),
				typeof(bool),
				typeof(bool)
			}, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(Chair), "GetHoverText", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(Chair), "Interact", new Type[3]
			{
				typeof(Humanoid),
				typeof(bool),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo != null)
			{
				TryPatch(harmony, methodInfo, "SettlerController.Awake", null, "SettlerAwakePostfix");
			}
			if (methodInfo2 != null)
			{
				TryPatch(harmony, methodInfo2, "SettlerController.GetHoverText", null, "SettlerHoverPostfix");
			}
			if (methodInfo3 != null)
			{
				TryPatch(harmony, methodInfo3, "SettlerController.Interact", "SettlerInteractPrefix");
			}
			if (methodInfo4 != null)
			{
				TryPatch(harmony, methodInfo4, "Bed.GetHoverText", null, "BedHoverPostfix");
			}
			if (methodInfo5 != null)
			{
				TryPatch(harmony, methodInfo5, "Bed.Interact", "BedInteractPrefix");
			}
			if (methodInfo6 != null)
			{
				TryPatch(harmony, methodInfo6, "Chair.GetHoverText favourite assignment", null, "ChairHoverPostfix");
			}
			if (methodInfo7 != null)
			{
				try
				{
					HarmonyMethod val = new HarmonyMethod(typeof(BedStationManagementTuning), "ChairInteractPrefix", (Type[])null);
					val.priority = 800;
					harmony.Patch((MethodBase)methodInfo7, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				catch (Exception ex)
				{
					_log.LogWarning((object)("[FAVOURITE-CHAIR] Could not patch Chair.Interact; favourite-chair assignment is disabled. " + ex.GetType().Name + ": " + ex.Message));
				}
			}
			if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || methodInfo5 == null || methodInfo7 == null || _settlerViewField == null || _restProperty == null || _releaseBedMethod == null || _claimBedMethod == null)
			{
				_log.LogWarning((object)"[MANAGE] Some bed/chair-management bindings are missing; resident assignment shortcuts may be unavailable.");
			}
		}

		private static void BindStationInternals()
		{
			_stationTypes = new Type[3]
			{
				typeof(CookingStation),
				typeof(Smelter),
				typeof(Fireplace)
			};
			_caretakerTargetField = ((_caretakerJobType != null) ? AccessTools.Field(_caretakerJobType, "_target") : null);
			_cookTargetField = ((_cookJobType != null) ? AccessTools.Field(_cookJobType, "_target") : null);
			if (_frithType != null)
			{
				_frithInstancesField = AccessTools.Field(_frithType, "Instances");
				_frithCoversPointMethod = _frithType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "CoversPoint" && m.GetParameters().Length == 2);
				_frithCanManageMethod = AccessTools.Method(_frithType, "CanManage", new Type[1] { typeof(long) }, (Type[])null);
				_frithOwnerIdProperty = AccessTools.Property(_frithType, "OwnerId");
				_frithNetProperty = AccessTools.Property(_frithType, "Net");
				_rosterTitleOfMethod = ((_settlementRosterType != null) ? AccessTools.Method(_settlementRosterType, "TitleOf", new Type[2]
				{
					typeof(ZDO),
					typeof(long)
				}, (Type[])null) : null);
				LogLeadershipBinding();
			}
			_networkAuthenticateMethod = ((_networkRequestType != null) ? AccessTools.Method(_networkRequestType, "AuthenticatePlayer", new Type[3]
			{
				typeof(long),
				typeof(long),
				typeof(string)
			}, (Type[])null) : null);
			if (_frithInstancesField == null || _frithCoversPointMethod == null || _frithCanManageMethod == null || _networkAuthenticateMethod == null)
			{
				_log.LogWarning((object)"[STATION-IGNORE] Frith permission/auth bindings are incomplete; station toggles will fail closed rather than allow unmanaged edits.");
			}
		}

		private static void PatchStationManagement(Harmony harmony)
		{
			HashSet<MethodInfo> hashSet = new HashSet<MethodInfo>();
			HashSet<MethodInfo> hashSet2 = new HashSet<MethodInfo>();
			if (_stationTypes != null)
			{
				Type[] stationTypes = _stationTypes;
				foreach (Type type in stationTypes)
				{
					if (!(type == null))
					{
						MethodInfo methodInfo = FindInstanceMethodQuiet(type, "Interact", typeof(Humanoid), typeof(bool), typeof(bool));
						if (methodInfo != null && hashSet.Add(methodInfo))
						{
							TryPatch(harmony, methodInfo, type.FullName + ".Interact", "StationInteractPrefix");
						}
						MethodInfo methodInfo2 = FindInstanceMethodQuiet(type, "GetHoverText");
						if (methodInfo2 != null && hashSet2.Add(methodInfo2))
						{
							TryPatch(harmony, methodInfo2, type.FullName + ".GetHoverText", null, "StationHoverPostfix");
						}
					}
				}
			}
			Type type2 = AccessTools.TypeByName("Switch");
			if (type2 != null)
			{
				MethodInfo methodInfo3 = FindInstanceMethodQuiet(type2, "Interact", typeof(Humanoid), typeof(bool), typeof(bool));
				if (methodInfo3 != null && hashSet.Add(methodInfo3))
				{
					TryPatch(harmony, methodInfo3, "Switch.Interact", "StationInteractPrefix");
				}
				MethodInfo methodInfo4 = FindInstanceMethodQuiet(type2, "GetHoverText");
				if (methodInfo4 != null && hashSet2.Add(methodInfo4))
				{
					TryPatch(harmony, methodInfo4, "Switch.GetHoverText", null, "StationHoverPostfix");
				}
			}
			MethodInfo methodInfo5 = ((_caretakerJobType != null) ? AccessTools.Method(_caretakerJobType, "TargetStillValid", (Type[])null, (Type[])null) : null);
			if (methodInfo5 != null && _caretakerTargetField != null)
			{
				TryPatch(harmony, methodInfo5, "CaretakerJob.TargetStillValid", null, "CaretakerTargetStillValidPostfix");
			}
			MethodInfo methodInfo6 = ((_cookJobType != null) ? AccessTools.Method(_cookJobType, "StillWorthDoing", Type.EmptyTypes, (Type[])null) : null);
			if (methodInfo6 != null && _cookTargetField != null)
			{
				TryPatch(harmony, methodInfo6, "CookJob.StillWorthDoing", null, "CookStillWorthDoingPostfix");
			}
			MethodInfo methodInfo7 = AccessTools.Method(typeof(ZNetView), "Awake", Type.EmptyTypes, (Type[])null);
			if (methodInfo7 != null)
			{
				TryPatch(harmony, methodInfo7, "ZNetView.Awake station RPC registration", null, "ZNetViewAwakePostfix");
			}
		}

		private static MethodInfo FindInstanceMethodQuiet(Type type, string name, params Type[] parameterTypes)
		{
			if (type == null || string.IsNullOrEmpty(name))
			{
				return null;
			}
			Type[] wanted = parameterTypes ?? Type.EmptyTypes;
			return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(delegate(MethodInfo method)
			{
				if (!string.Equals(method.Name, name, StringComparison.Ordinal))
				{
					return false;
				}
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length != wanted.Length)
				{
					return false;
				}
				for (int i = 0; i < parameters.Length; i++)
				{
					if (parameters[i].ParameterType != wanted[i])
					{
						return false;
					}
				}
				return true;
			});
		}

		private static bool ModifierHeld()
		{
			//IL_000e: 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)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (_modifier == null)
			{
				return false;
			}
			KeyCode value = _modifier.Value;
			if ((int)value != 0)
			{
				return Input.GetKey(value);
			}
			return true;
		}

		internal static bool ManagementModifierHeld()
		{
			return ModifierHeld();
		}

		internal static string ManagementModifierLabel()
		{
			return ModifierLabel();
		}

		private unsafe static string ModifierLabel()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			KeyCode val = (KeyCode)((_modifier == null) ? 306 : ((int)_modifier.Value));
			if ((int)val == 0)
			{
				return "E";
			}
			string text = ((object)(*(KeyCode*)(&val))/*cast due to .constrained prefix*/).ToString();
			if (text.StartsWith("Left", StringComparison.Ordinal))
			{
				text = text.Substring(4);
			}
			else if (text.StartsWith("Right", StringComparison.Ordinal))
			{
				text = text.Substring(5);
			}
			if (string.Equals(text, "Control", StringComparison.Ordinal))
			{
				text = "Ctrl";
			}
			return text + "+E";
		}

		private static void SettlerAwakePostfix(object __instance)
		{
			RegisterSettlerRpc(__instance);
		}

		private static void RegisterSettlerRpc(object settler)
		{
			if (settler == null)
			{
				return;
			}
			ZNetView val = SettlerView(settler);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				val.Register<ZDOID>("InnLagFix_BedAssign_104", (Action<long, ZDOID>)delegate(long sender, ZDOID bed)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					HandleBedAssignmentRpc(settler, bed, force: false);
				});
				val.Register<ZDOID>("InnLagFix_BedAssignForce_104", (Action<long, ZDOID>)delegate(long sender, ZDOID bed)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					HandleBedAssignmentRpc(settler, bed, force: true);
				});
				val.Register<ZDOID, string>("InnLagFix_FavouriteChairAssign_108seat", (Action<long, ZDOID, string>)delegate(long sender, ZDOID chair, string seatKey)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					HandleFavouriteChairAssignmentRpc(settler, chair, seatKey);
				});
			}
			catch (Exception ex)
			{
				if (!_loggedBedFailure)
				{
					_loggedBedFailure = true;
					_log.LogWarning((object)("[MANAGE] Could not register bed/chair-assignment RPC: " + ex.Message));
				}
			}
		}

		private static void SettlerHoverPostfix(object __instance, ref string __result)
		{
			if (Active && __instance != null && CanLocalPlayerManage(__instance))
			{
				__result = __result + "\n[<color=yellow><b>" + ModifierLabel() + "</b></color>] Assign Bed/Chair";
			}
		}

		private static bool SettlerInteractPrefix(object __instance, Humanoid __0, bool __1, ref bool __result)
		{
			if (!Active || __1 || !ModifierHeld() || __instance == null || !IsLocalPlayer(__0))
			{
				return true;
			}
			if (!CanLocalPlayerManage(__instance))
			{
				return true;
			}
			_selectedSettler = __instance;
			_selectedUntil = Time.unscaledTime + 60f;
			Say("Selected " + PanelName(__instance) + " for bed/chair assignment. " + ModifierLabel() + " a bed or chair to assign it.");
			__result = true;
			return false;
		}

		private static void ChairHoverPostfix(Chair __instance, ref string __result)
		{
			if (!Active || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			ZNetView val = ViewOf((Component)(object)__instance);
			if ((Object)(object)val == (Object)null || !val.IsValid() || val.GetZDO() == null)
			{
				return;
			}
			FavouriteChairRef favouriteChairRef = ReferenceForChair(__instance, val);
			if (favouriteChairRef.IsNone)
			{
				return;
			}
			List<object> list = ResidentsFavouringChair(favouriteChairRef);
			if (list.Count > 0)
			{
				string text = string.Join(", ", list.Select(PanelName).ToArray());
				__result = __result + "\n<color=#d9c58c>Favourite chair: " + text + "</color>";
			}
			object selected = ValidSelectedSettler();
			if (selected == null || !CanLocalPlayerManage(selected) || !ChairEligibleForFavourite(selected, __instance, val))
			{
				return;
			}
			FavouriteChairRef a = FavouriteChairReference(selected);
			string text2;
			if (SameFavouriteSeat(a, favouriteChairRef))
			{
				text2 = "Unassign Favourite Chair from " + PanelName(selected);
			}
			else
			{
				object obj = list.FirstOrDefault((object owner) => owner != null && owner != selected);
				text2 = ((obj != null && !a.IsNone) ? ("Swap " + PanelName(selected) + " with " + PanelName(obj)) : ((obj == null) ? ("Assign Favourite Chair to " + PanelName(selected)) : ("Occupied by " + PanelName(obj))));
			}
			__result = __result + "\n[<color=yellow><b>" + ModifierLabel() + "</b></color>] " + text2;
		}

		private static bool ChairInteractPrefix(Chair __instance, Humanoid __0, bool __1, ref bool __result)
		{
			object obj = ValidSelectedSettler();
			if (!Active || obj == null || __1 || !ModifierHeld() || !IsLocalPlayer(__0) || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (!CanLocalPlayerManage(obj))
			{
				return true;
			}
			ZNetView val = ViewOf((Component)(object)__instance);
			if (!ChairEligibleForFavourite(obj, __instance, val))
			{
				Say("That chair cannot be assigned as this resident's favourite.");
				__result = true;
				return false;
			}
			RequestFavouriteChairAssignment(obj, __instance, val);
			_selectedUntil = Time.unscaledTime + 60f;
			__result = true;
			return false;
		}

		private static void RequestFavouriteChairAssignment(object selected, Chair targetChair, ZNetView targetView)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			if (selected == null || (Object)(object)targetChair == (Object)null || (Object)(object)targetView == (Object)null || !targetView.IsValid())
			{
				return;
			}
			ZNetView val = SettlerView(selected);
			ZDO zDO = targetView.GetZDO();
			if ((Object)(object)val == (Object)null || !val.IsValid() || zDO == null)
			{
				Say("Could not assign that favourite chair.");
				return;
			}
			FavouriteChairRef favouriteChairRef = ReferenceForChair(targetChair, targetView);
			FavouriteChairRef favouriteChairRef2 = FavouriteChairReference(selected);
			if (SameFavouriteSeat(favouriteChairRef2, favouriteChairRef))
			{
				InvokeFavouriteChairAssignment(val, new FavouriteChairRef(ZDOID.None, string.Empty));
				Say("Unassigned " + PanelName(selected) + "'s favourite chair.");
				return;
			}
			List<object> list = (from owner in ResidentsFavouringChair(favouriteChairRef)
				where owner != null && owner != selected
				select owner).ToList();
			if (list.Count > 0)
			{
				object settler = list[0];
				if (favouriteChairRef2.IsNone)
				{
					Say("That chair belongs to " + PanelName(settler) + ", and " + PanelName(selected) + " has no favourite chair to swap with.");
					return;
				}
				Chair val2 = ResolveChair(favouriteChairRef2);
				ZNetView view = ViewOf((Component)(object)val2);
				if ((Object)(object)val2 == (Object)null || !ChairEligibleForFavourite(settler, val2, view))
				{
					Say("Cannot swap those favourite chairs because " + PanelName(selected) + "'s current chair is unavailable to " + PanelName(settler) + ".");
					return;
				}
				for (int num = 0; num < list.Count; num++)
				{
					object settler2 = list[num];
					if (!CanLocalPlayerManage(settler2))
					{
						Say("That chair is assigned to a resident you cannot manage.");
						return;
					}
					ZNetView val3 = SettlerView(settler2);
					if ((Object)(object)val3 == (Object)null || !val3.IsValid())
					{
						Say("The resident currently assigned to that chair is not available to swap.");
						return;
					}
				}
				InvokeFavouriteChairAssignment(SettlerView(settler), favouriteChairRef2);
				for (int num2 = 1; num2 < list.Count; num2++)
				{
					InvokeFavouriteChairAssignment(SettlerView(list[num2]), new FavouriteChairRef(ZDOID.None, string.Empty));
				}
				InvokeFavouriteChairAssignment(val, favouriteChairRef);
				Say("Swapping favourite chairs: " + PanelName(selected) + " <-> " + PanelName(settler) + ".");
			}
			else
			{
				InvokeFavouriteChairAssignment(val, favouriteChairRef);
				Say("Assigned that chair as " + PanelName(selected) + "'s favourite.");
			}
		}

		private static void InvokeFavouriteChairAssignment(ZNetView settlerView, FavouriteChairRef chair)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)settlerView == (Object)null) && settlerView.IsValid())
			{
				settlerView.InvokeRPC("InnLagFix_FavouriteChairAssign_108seat", new object[2]
				{
					chair.ViewId,
					chair.SeatKey ?? string.Empty
				});
			}
		}

		private static void HandleFavouriteChairAssignmentRpc(object settler, ZDOID desiredChair, string desiredSeatKey)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_014c: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || settler == null)
			{
				return;
			}
			ZNetView val = SettlerView(settler);
			if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner())
			{
				return;
			}
			ZDO zDO = val.GetZDO();
			if (zDO == null)
			{
				return;
			}
			if (desiredChair == ZDOID.None)
			{
				FavouriteChairRef favouriteChairRef = FavouriteChairReference(settler);
				zDO.Set("inn_favourite_chair", ZDOID.None);
				zDO.Set("inn_favourite_chair_seat", string.Empty);
				_log.LogVerbose("[FAVOURITE-CHAIR] " + PanelName(settler) + " unassigned favourite chair " + ((object)favouriteChairRef.ViewId/*cast due to .constrained prefix*/).ToString() + "/" + favouriteChairRef.SeatKey + ".");
				return;
			}
			FavouriteChairRef favourite = new FavouriteChairRef(desiredChair, desiredSeatKey);
			Chair val2 = ResolveChair(favourite);
			ZNetView view = ViewOf((Component)(object)val2);
			if (ChairEligibleForFavourite(settler, val2, view))
			{
				favourite = ReferenceForChair(val2, view);
				zDO.Set("inn_favourite_chair", favourite.ViewId);
				zDO.Set("inn_favourite_chair_seat", favourite.SeatKey);
				_log.LogVerbose("[FAVOURITE-CHAIR] " + PanelName(settler) + " assigned favourite chair " + ((object)favourite.ViewId/*cast due to .constrained prefix*/).ToString() + "/" + favourite.SeatKey + ".");
			}
		}

		private static List<object> ResidentsFavouringChair(FavouriteChairRef chair)
		{
			List<object> list = new List<object>();
			if (chair.IsNone || _settlerInstancesField == null)
			{
				return list;
			}
			IEnumerable enumerable = null;
			try
			{
				enumerable = _settlerInstancesField.GetValue(null) as IEnumerable;
			}
			catch
			{
			}
			if (enumerable == null)
			{
				return list;
			}
			foreach (object item in enumerable)
			{
				if (item == null)
				{
					continue;
				}
				try
				{
					if (SameFavouriteSeat(FavouriteChairReference(item), chair))
					{
						list.Add(item);
					}
				}
				catch
				{
				}
			}
			return list;
		}

		internal static bool TryResolveFavouriteChair(object settler, out Chair chair)
		{
			chair = null;
			FavouriteChairRef favourite = FavouriteChairReference(settler);
			if (favourite.IsNone)
			{
				return false;
			}
			chair = ResolveChair(favourite);
			return (Object)(object)chair != (Object)null;
		}

		private static FavouriteChairRef FavouriteChairReference(object settler)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = SettlerView(settler);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return new FavouriteChairRef(ZDOID.None, string.Empty);
			}
			ZDO zDO = val.GetZDO();
			if (zDO == null)
			{
				return new FavouriteChairRef(ZDOID.None, string.Empty);
			}
			ZDOID zDOID = zDO.GetZDOID("inn_favourite_chair");
			string seatKey = zDO.GetString("inn_favourite_chair_seat", string.Empty);
			FavouriteChairRef favouriteChairRef = new FavouriteChairRef(zDOID, seatKey);
			if (!favouriteChairRef.IsNone && string.IsNullOrEmpty(favouriteChairRef.SeatKey))
			{
				Chair val2 = ResolveChair(favouriteChairRef);
				if ((Object)(object)val2 != (Object)null)
				{
					ZNetView view = ViewOf((Component)(object)val2);
					return ReferenceForChair(val2, view);
				}
			}
			return favouriteChairRef;
		}

		private static FavouriteChairRef ReferenceForChair(Chair chair, ZNetView view)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0053: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)chair == (Object)null || (Object)(object)view == (Object)null || !view.IsValid() || view.GetZDO() == null)
			{
				return new FavouriteChairRef(ZDOID.None, string.Empty);
			}
			Chair[] componentsInChildren = ((Component)view).GetComponentsInChildren<Chair>(true);
			int num = -1;
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)componentsInChildren[i] == (Object)chair)
				{
					num = i;
					break;
				}
			}
			string seatKey = ((num >= 0) ? ("seat:" + num) : ("chair:" + ((Component)chair).transform.GetSiblingIndex()));
			return new FavouriteChairRef(view.GetZDO().m_uid, seatKey);
		}

		private static bool SameFavouriteSeat(FavouriteChairRef a, FavouriteChairRef b)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (a.ViewId == b.ViewId && !a.IsNone)
			{
				return string.Equals(a.SeatKey ?? string.Empty, b.SeatKey ?? string.Empty, StringComparison.Ordinal);
			}
			return false;
		}

		private static Chair ResolveChair(FavouriteChairRef favourite)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (favourite.IsNone || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			GameObject val = ZNetScene.instance.FindInstance(favourite.ViewId);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			Chair[] componentsInChildren = val.GetComponentsInChildren<Chair>(true);
			if (componentsInChildren == null || componentsInChildren.Length == 0)
			{
				return val.GetComponent<Chair>();
			}
			string text = favourite.SeatKey ?? string.Empty;
			if (text.StartsWith("seat:", StringComparison.Ordinal))
			{
				if (int.TryParse(text.Substring(5), out var result) && result >= 0 && result < componentsInChildren.Length)
				{
					return componentsInChildren[result];
				}
				return null;
			}
			if (string.IsNullOrEmpty(text))
			{
				return componentsInChildren[0];
			}
			if (text.StartsWith("chair:", StringComparison.Ordinal) && int.TryParse(text.Substring(6), out var result2))
			{
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					if (((Component)componentsInChildren[i]).transform.GetSiblingIndex() == result2)
					{
						return componentsInChildren[i];
					}
				}
			}
			return null;
		}

		private static bool ChairEligibleForFavourite(object settler, Chair chair, ZNetView view)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if (settler == null || (Object)(object)chair == (Object)null || (Object)(object)view == (Object)null || !view.IsValid() || (Object)(object)chair.m_attachPoint == (Object)null || !((Behaviour)chair).isActiveAndEnabled || !((Component)chair).gameObject.activeInHierarchy)
			{
				return false;
			}
			Piece val = ((Component)chair).GetComponent<Piece>() ?? ((Component)chair).GetComponentInParent<Piece>();
			if ((Object)(object)val == (Object)null || !val.IsPlacedByPlayer())
			{
				return false;
			}
			if ((Object)(object)((Component)chair).GetComponentInParent<Ship>() != (Object)null || (Object)(object)((Component)chair).GetComponentInParent<Vagon>() != (Object)null)
			{
				return false;
			}
			try
			{
				if (_inSettlementAreaMethod == null)
				{
					return false;
				}
				object obj = _inSettlementAreaMethod.Invoke(settler, new object[1] { ((Component)chair).transform.position });
				return obj is bool && (bool)obj;
			}
			catch
			{
				return false;
			}
		}

		private static void BedHoverPostfix(Bed __instance, ref string __result)
		{
			object obj = ValidSelectedSettler();
			if (Active && obj != null && !((Object)(object)__instance == (Object)null))
			{
				ZNetView val = ViewOf((Component)(object)__instance);
				if (!((Object)(object)val == (Object)null) && val.IsValid() && BedEligibleForInnangard(__instance, val))
				{
					object obj2 = ResidentClaiming(val.GetZDO());
					string text = ((obj2 != null && obj2 != obj) ? ("Swap " + PanelName(obj) + " with " + PanelName(obj2)) : ("Assign to " + PanelName(obj)));
					__result = __result + "\n[<color=yellow><b>" + ModifierLabel() + "</b></color>] " + text;
				}
			}
		}

		private static bool BedInteractPrefix(Bed __instance, Humanoid __0, bool __1, ref bool __result)
		{
			object obj = ValidSelectedSettler();
			if (!Active || obj == null || __1 || !ModifierHeld() || !IsLocalPlayer(__0) || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			ZNetView val = ViewOf((Component)(object)__instance);
			if ((Object)(object)val == (Object)null || !val.IsValid() || !BedEligibleForInnangard(__instance, val))
			{
				Say("That bed cannot be assigned to an Innangard resident.");
				__result = true;
				return false;
			}
			if (!WithinBedRange(obj, __instance))
			{
				Say("That bed is outside " + PanelName(obj) + "'s Innangard bed-search range.");
				__result = true;
				return false;
			}
			RequestBedAssignment(obj, __instance, val);
			_selectedSettler = null;
			__result = true;
			return false;
		}

		private static void RequestBedAssignment(object selected, Bed targetBed, ZNetView targetView)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_004a: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = SettlerView(selected);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				Say("Could not find that resident's network view.");
				return;
			}
			ZDO zDO = val.GetZDO();
			ZDO zDO2 = targetView.GetZDO();
			if (zDO == null || zDO2 == null)
			{
				return;
			}
			ZDOID uid = zDO2.m_uid;
			ZDOID zDOID = zDO.GetZDOID("inn_bed");
			if (zDOID == uid)
			{
				Say(PanelName(selected) + " already has that bed.");
				return;
			}
			object obj = ResidentClaiming(zDO2);
			if (obj != null && obj != selected)
			{
				if (zDOID == ZDOID.None)
				{
					Say("That bed belongs to " + PanelName(obj) + ", and " + PanelName(selected) + " has no bed to swap with.");
					return;
				}
				Bed val2 = ResolveBed(zDOID);
				if ((Object)(object)val2 == (Object)null || !WithinBedRange(obj, val2))
				{
					Say("Cannot swap those beds because the current bed is unavailable to " + PanelName(obj) + ".");
					return;
				}
				ZNetView val3 = SettlerView(obj);
				if ((Object)(object)val3 == (Object)null || !val3.IsValid())
				{
					Say("The resident currently assigned to that bed is not available to swap.");
					return;
				}
				val3.InvokeRPC("InnLagFix_BedAssignForce_104", new object[1] { zDOID });
				val.InvokeRPC("InnLagFix_BedAssign_104", new object[1] { uid });
				Say("Swapping beds: " + PanelName(selected) + " <-> " + PanelName(obj) + ".");
			}
			else if (HasForeignBedClaim(zDO2, selected))
			{
				Say("That bed has an Innangard claim whose resident is not currently loaded; it was left unchanged.");
			}
			else
			{
				val.InvokeRPC("InnLagFix_BedAssign_104", new object[1] { uid });
				Say("Reassigning " + PanelName(selected) + " to that bed.");
			}
		}

		private static void HandleBedAssignmentRpc(object settler, ZDOID desiredBed, bool force)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || settler == null || desiredBed == ZDOID.None)
			{
				return;
			}
			ZNetView val = SettlerView(settler);
			if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner())
			{
				return;
			}
			if (force || TryAssignBedNow(settler, desiredBed, force: false))
			{
				if (force)
				{
					TryAssignBedNow(settler, desiredBed, force: true);
				}
				return;
			}
			object obj = ((settler is Object) ? settler : null);
			int key = ((obj != null) ? ((Object)obj).GetInstanceID() : settler.GetHashCode());
			PendingBeds[key] = new PendingBedAssignment
			{
				Settler = settler,
				Bed = desiredBed,
				Until = Time.unscaledTime + 4f
			};
		}

		private unsafe static bool TryAssignBedNow(object settler, ZDOID desiredBed, bool force)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			Bed val = ResolveBed(desiredBed);
			if (settler == null || (Object)(object)val == (Object)null)
			{
				return false;
			}
			ZNetView val2 = ViewOf((Component)(object)val);
			if ((Object)(object)val2 == (Object)null || !val2.IsValid() || !BedEligibleForInnangard(val, val2) || !WithinBedRange(settler, val))
			{
				return false;
			}
			ZDO zDO = val2.GetZDO();
			if (!force && HasForeignBedClaim(zDO, settler))
			{
				return false;
			}
			object obj = _restProperty?.GetValue(settler, null);
			if (obj == null)
			{
				return false;
			}
			try
			{
				_stopSleepMethod?.Invoke(obj, null);
				_releaseBedMethod.Invoke(obj, null);
				float num = Distance(HomePosition(settler), ((Component)val).transform.position);
				_claimBedMethod.Invoke(obj, new object[3] { val, num, "was reassigned to a bed" });
				ManualLogSource log = _log;
				string[] obj2 = new string[6]
				{
					"[BED] ",
					PanelName(settler),
					" assigned bed ",
					null,
					null,
					null
				};
				ZDOID val3 = desiredBed;
				obj2[3] = ((object)(*(ZDOID*)(&val3))/*cast due to .constrained prefix*/).ToString();
				obj2[4] = (force ? " (swap leg)" : string.Empty);
				obj2[5] = ".";
				log.LogVerbose(string.Concat(obj2));
				return true;
			}
			catch (Exception ex)
			{
				if (!_loggedBedFailure)
				{
					_loggedBedFailure = true;
					_log.LogWarning((object)("[BED] Bed reassignment failed once; stock bed handling continues. " + ex.GetType().Name + ": " + ex.Message));
				}
				return false;
			}
		}

		private static object ValidSelectedSettler()
		{
			if (_selectedSettler == null || Time.unscaledTime >= _selectedUntil)
			{
				_selectedSettler = null;
				return null;
			}
			object selectedSettler = _selectedSettler;
			Component val = (Component)((selectedSettler is Component) ? selectedSettler : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.gameObject == (Object)null || !val.gameObject.activeInHierarchy)
			{
				_selectedSettler = null;
				return null;
			}
			return _selectedSettler;
		}

		private static bool CanLocalPlayerManage(object settler)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (settler == null || (Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			long playerID = localPlayer.GetPlayerID();
			try
			{
				if (_canManageMethod != null)
				{
					object obj = _canManageMethod.Invoke(settler, new object[1] { playerID });
					if (!(obj is bool) || !(bool)obj)
					{
						return false;
					}
				}
			}
			catch
			{
				return false;
			}
			return CanRequesterLeadFrith(FindManagingFrith(HomePosition(settler)), playerID);
		}

		private static bool BedEligibleForInnangard(Bed bed, ZNetView view)
		{
			if ((Object)(object)bed == (Object)null || (Object)(object)view == (Object)null || !view.IsValid())
			{
				return false;
			}
			Piece val = ((Component)bed).GetComponent<Piece>() ?? ((Component)bed).GetComponentInParent<Piece>();
			if ((Object)(object)val != (Object)null && !val.IsPlacedByPlayer())
			{
				return false;
			}
			ZDO zDO = view.GetZDO();
			if (zDO == null)
			{
				return false;
			}
			long num = zDO.GetLong(ZDOVars.s_owner, 0L);
			if (num != 0L)
			{
				return num == 424242;
			}
			return true;
		}

		private static bool WithinBedRange(object settler, Bed bed)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (settler == null || (Object)(object)bed == (Object)null)
			{
				return false;
			}
			float num = 30f;
			try
			{
				if (_bedSearchRadiusField?.GetValue(null) is ConfigEntry<float> val)
				{
					num = Mathf.Max(1f, val.Value);
				}
			}
			catch
			{
			}
			return Distance(HomePosition(settler), ((Component)bed).transform.position) <= num;
		}

		private static object ResidentClaiming(ZDO bedZdo)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			if (bedZdo == null || _settlerInstancesField == null)
			{
				return null;
			}
			string text = bedZdo.GetString("inn_claim_identity", string.Empty);
			ZDOID zDOID = bedZdo.GetZDOID("inn_claim");
			if (string.IsNullOrEmpty(text) && zDOID == ZDOID.None)
			{
				return null;
			}
			if (!(_settlerInstancesField.GetValue(null) is IEnumerable enumerable))
			{
				return null;
			}
			foreach (object item in enumerable)
			{
				if (item == null)
				{
					continue;
				}
				if (!string.IsNullOrEmpty(text))
				{
					if (_stableIdentityProperty?.GetValue(item, null) as string == text)
					{
						return item;
					}
				}
				else if (_myZdoidProperty != null)
				{
					object value = _myZdoidProperty.GetValue(item, null);
					if (value is ZDOID && (ZDOID)value == zDOID)
					{
						return item;
					}
				}
			}
			return null;
		}

		private static bool HasForeignBedClaim(ZDO bedZdo, object settler)
		{
			//IL_004f: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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)
			if (bedZdo == null)
			{
				return true;
			}
			string text = bedZdo.GetString("inn_claim_identity", string.Empty);
			if (!string.IsNullOrEmpty(text))
			{
				string text2 = _stableIdentityProperty?.GetValue(settler, null) as string;
				if (!string.IsNullOrEmpty(text2))
				{
					return text != text2;
				}
				return true;
			}
			ZDOID zDOID = bedZdo.GetZDOID("inn_claim");
			if (zDOID == ZDOID.None)
			{
				return false;
			}
			if (_myZdoidProperty == null)
			{
				return true;
			}
			object value = _myZdoidProperty.GetValue(settler, null);
			if (value is ZDOID)
			{
				return (ZDOID)value != zDOID;
			}
			return true;
		}

		private static Bed ResolveBed(ZDOID id)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (id == ZDOID.None || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return null;
			}
			GameObject val = ZNetScene.instance.FindInstance(id);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			return val.GetComponent<Bed>() ?? val.GetComponentInChildren<Bed>(true);
		}

		private static ZNetView SettlerView(object settler)
		{
			if (settler == null)
			{
				return null;
			}
			try
			{
				object? obj = _settlerViewField?.GetValue(settler);
				ZNetView val = (ZNetView)((obj is ZNetView) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			catch
			{
			}
			Component val2 = (Component)((settler is Component) ? settler : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.GetComponent<ZNetView>() ?? val2.GetComponentInParent<ZNetView>();
		}

		private static string PanelName(object settler)
		{
			try
			{
				string text = _panelNameProperty?.GetValue(settler, null) as string;
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			catch
			{
			}
			object obj2 = ((settler is Component) ? settler : null);
			object obj3;
			if (obj2 == null)
			{
				obj3 = null;
			}
			else
			{
				GameObject gameObject = ((Component)obj2).gameObject;
				obj3 = ((gameObject != null) ? ((Object)gameObject).name : null);
			}
			if (obj3 == null)
			{
				obj3 = "resident";
			}
			return (string)obj3;
		}

		private static Vector3 HomePosition(object settler)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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)
			try
			{
				object obj = _homePositionProperty?.GetValue(settler, null);
				if (obj is Vector3)
				{
					return (Vector3)obj;
				}
			}
			catch
			{
			}
			object obj3 = ((settler is Component) ? settler : null);
			if (obj3 == null)
			{
				return Vector3.zero;
			}
			return ((Component)obj3).transform.position;
		}

		private static float Distance(Vector3 a, Vector3 b)
		{
			//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_000d: 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)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return Mathf.Sqrt(num * num + num2 * num2);
		}

		private static bool IsLocalPlayer(Humanoid user)
		{
			Player val = (Player)(object)((user is Player) ? user : null);
			if ((Object)(object)val != (Object)null)
			{
				return (Object)(object)val == (Object)(object)Player.m_localPlayer;
			}
			return false;
		}

		private static void Say(string message)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				((Character)localPlayer).Message((MessageType)2, message, 0, (Sprite)null, false);
			}
		}

		private static void ZNetViewAwakePostfix(ZNetView __instance)
		{
			RegisterStationRpc(__instance);
		}

		private static void RegisterStationRpc(ZNetView view)
		{
			if ((Object)(object)view == (Object)null || !ViewBelongsToSupportedStation(view))
			{
				return;
			}
			int instanceID = ((Object)view).GetInstanceID();
			if (!RegisteredStationViews.Add(instanceID))
			{
				return;
			}
			try
			{
				view.Register<long, bool>("InnLagFix_StationIgnore_104", (Action<long, long, bool>)delegate(long sender, long requesterId, bool ignored)
				{
					ApplyStationToggle(view, sender, requesterId, ignored);
				});
			}
			catch (Exception ex)
			{
				RegisteredStationViews.Remove(instanceID);
				if (!_loggedStationFailure)
				{
					_loggedStationFailure = true;
					_log.LogWarning((object)("[STATION-IGNORE] Could not register station toggle RPC: " + ex.Message));
				}
			}
		}

		private static bool StationInteractPrefix(object __instance, Humanoid __0, bool __1, ref bool __result)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || __1 || !ModifierHeld() || !IsLocalPlayer(__0))
			{
				return true;
			}
			Component val = (Component)((__instance is Component) ? __instance : null);
			ZNetView val2 = ViewOf(val);
			if ((Object)(object)val2 == (Object)null || !val2.IsValid() || !ViewBelongsToSupportedStation(val2))
			{
				return true;
			}
			if (!PrivateArea.CheckAccess(val.transform.position, 0f, false, false))
			{
				return true;
			}
			if (!CanLocalPlayerManageStation(val2))
			{
				return true;
			}
			bool flag = !IsStationIgnored(val2);
			RequestStationIgnored(val2, flag);
			Say(StationName(val) + (flag ? " will now be ignored by Innangard." : " is available to Innangard again."));
			__result = true;
			return false;
		}

		private static void StationHoverPostfix(object __instance, ref string __result)
		{
			if (!Active)
			{
				return;
			}
			ZNetView val = ViewOf((Component)((__instance is Component) ? __instance : null));
			if (!((Object)(object)val == (Object)null) && val.IsValid() && ViewBelongsToSupportedStation(val) && CanLocalPlayerManageStation(val))
			{
				bool flag = IsStationIgnored(val);
				__result = __result + "\n[<color=yellow><b>" + ModifierLabel() + "</b></color>] " + (flag ? "Use Station" : "Ignore Station");
				if (flag)
				{
					__result += "\n<color=#d99a76>Ignored by Innangard</color>";
				}
			}
		}

		private static void ApplyStationToggle(ZNetView view, long sender, long requesterId, bool ignored)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || (Object)(object)view == (Object)null || !view.IsValid() || !view.IsOwner())
			{
				return;
			}
			try
			{
				if (!AuthenticateRequester(sender, requesterId) || !CanRequesterManageStation(view, requesterId))
				{
					_log.LogWarning((object)("[STATION-IGNORE] Rejected unmanaged station toggle for requester=" + requesterId + "."));
					return;
				}
				ZDO zDO = view.GetZDO();
				if (zDO != null)
				{
					zDO.Set("inn_lagfix_ignore_station", ignored);
					if (ignored)
					{
						zDO.Set("inn_station_claim", ZDOID.None);
						zDO.Set("inn_station_claim_until", 0L);
					}
					Plugin.ForgetStationLease(view);
					_log.LogVerbose("[STATION-IGNORE] " + StationName(view) + " ignored=" + ignored + " by " + requesterId + ".");
				}
			}
			catch (Exception ex)
			{
				if (!_loggedStationFailure)
				{
					_loggedStationFailure = true;
					_log.LogWarning((object)("[STATION-IGNORE] Toggle failed once: " + ex.GetType().Name + ": " + ex.Message));
				}
			}
		}

		private static void CaretakerTargetStillValidPostfix(object __instance, ref bool __result)
		{
			if (Active && __result && __instance != null && !(_caretakerTargetField == null))
			{
				object? value = _caretakerTargetField.GetValue(__instance);
				GameObject val = (GameObject)((value is GameObject) ? value : null);
				if ((Object)(object)val != (Object)null && IsStationIgnored(ViewOf((Component)(object)val.transform)))
				{
					__result = false;
				}
			}
		}

		private static void CookStillWorthDoingPostfix(object __instance, ref bool __result)
		{
			if (Active && __result && __instance != null && !(_cookTargetField == null))
			{
				object? value = _cookTargetField.GetValue(__instance);
				Component val = (Component)((value is Component) ? value : null);
				if ((Object)(object)val != (Object)null && IsStationIgnored(ViewOf(val)))
				{
					__result = false;
				}
			}
		}

		internal static bool IsSupportedStation(ZNetView view)
		{
			return ViewBelongsToSupportedStation(view);
		}

		internal static ZNetView GetSupportedStationView(Component component)
		{
			ZNetView val = ViewOf(component);
			if (!ViewBelongsToSupportedStation(val))
			{
				return null;
			}
			return val;
		}

		internal static Component GetSupportedStationComponent(ZNetView view)
		{
			if ((Object)(object)view == (Object)null || !ViewBelongsToSupportedStation(view) || _stationTypes == null)
			{
				return null;
			}
			Type[] stationTypes = _stationTypes;
			foreach (Type type in stationTypes)
			{
				if (!(type == null))
				{
					Component component = ((Component)view).GetComponent(type);
					if ((Object)(object)component != (Object)null)
					{
						return component;
					}
					Component componentInParent = ((Component)view).GetComponentInParent(type);
					if ((Object)(object)componentInParent != (Object)null)
					{
						return componentInParent;
					}
					Component componentInChildren = ((Component)view).GetComponentInChildren(type, true);
					if ((Object)(object)componentInChildren != (Object)null)
					{
						return componentInChildren;
					}
				}
			}
			return null;
		}

		internal static void RequestStationIgnored(ZNetView view, bool ignored)
		{
			if (Active && !((Object)(object)view == (Object)null) && view.IsValid() && ViewBelongsToSupportedStation(view))
			{
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null) && CanLocalPlayerManageStation(view))
				{
					RegisterStationRpc(view);
					view.InvokeRPC("InnLagFix_StationIgnore_104", new object[2]
					{
						localPlayer.GetPlayerID(),
						ignored
					});
				}
			}
		}

		internal static bool CanLocalPlayerManageStation(ZNetView view)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				return CanRequesterManageStation(view, localPlayer.GetPlayerID());
			}
			return false;
		}

		private static bool AuthenticateRequester(long sender, long requesterId)
		{
			if (_networkAuthenticateMethod == null || requesterId == 0L)
			{
				return false;
			}
			try
			{
				object obj = _networkAuthenticateMethod.Invoke(null, new object[3] { sender, requesterId, "station ignore toggle" });
				return obj is bool && (bool)obj;
			}
			catch
			{
				return false;
			}
		}

		private static bool CanRequesterManageStation(ZNetView view, long requesterId)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (requesterId == 0L || (Object)(object)view == (Object)null || !view.IsValid())
			{
				return false;
			}
			Component supportedStationComponent = GetSupportedStationComponent(view);
			if ((Object)(object)supportedStationComponent == (Object)null)
			{
				return false;
			}
			Piece val = supportedStationComponent.GetComponent<Piece>() ?? supportedStationComponent.GetComponentInParent<Piece>();
			if ((Object)(object)val == (Object)null || !val.IsPlacedByPlayer())
			{
				return false;
			}
			object obj = FindManagingFrith(supportedStationComponent.transform.position);
			if (obj == null || _frithCanManageMethod == null)
			{
				return false;
			}
			try
			{
				object obj2 = _frithCanManageMethod.Invoke(obj, new object[1] { requesterId });
				if (!(obj2 is bool) || !(bool)obj2)
				{
					return false;
				}
				return CanRequesterLeadFrith(obj, requesterId);
			}
			catch
			{
				return false;
			}
		}

		internal static bool CanLocalPlayerStrictlyManageFrith(object frith)
		{
			Player localPlayer = Player.m_localPlayer;
			if (frith == null || (Object)(object)localPlayer == (Object)null || _frithCanManageMethod == null)
			{
				return false;
			}
			long playerID = localPlayer.GetPlayerID();
			try
			{
				object obj = _frithCanManageMethod.Invoke(frith, new object[1] { playerID });
				return obj is bool && (bool)obj && CanRequesterLeadFrith(frith, playerID);
			}
			catch
			{
				return false;
			}
		}

		private static bool CanRequesterLeadFrith(object frith, long requesterId)
		{
			if (frith == null || requesterId == 0L)
			{
				return false;
			}
			try
			{
				if (_frithOwnerIdProperty != null)
				{
					object value = _frithOwnerIdProperty.GetValue(frith, null);
					if (value is long && (long)value == requesterId)
					{
						return true;
					}
				}
			}
			catch
			{
			}
			try
			{
				object? obj2 = _frithNetProperty?.GetValue(frith, null);
				ZNetView val = (ZNetView)((obj2 is ZNetView) ? obj2 : null);
				if ((Object)(object)val == (Object)null)
				{
					Component val2 = (Component)((frith is Component) ? frith : null);
					if ((Object)(object)val2 != (Object)null)
					{
						val = val2.GetComponent<ZNetView>() ?? val2.GetComponentInParent<ZNetView>();
					}
				}
				ZDO val3 = (((Object)(object)val != (Object)null && val.IsValid()) ? val.GetZDO() : null);
				if (val3 != null && _rosterTitleOfMethod != null)
				{
					object obj3 = _rosterTitleOfMethod.Invoke(null, new object[2] { val3, requesterId });
					if (obj3 != null && Convert.ToInt32(obj3) == 1)
					{
						return true;
					}
				}
			}
			catch
			{
			}
			Component val4 = (Component)((frith is Component) ? frith : null);
			if ((Object)(object)val4 != (Object)null)
			{
				Piece val5 = val4.GetComponent<Piece>() ?? val4.GetComponentInParent<Piece>();
				if ((Object)(object)val5 != (Object)null && val5.GetCreator() == requesterId)
				{
					return true;
				}
			}
			return false;
		}

		private static void LogLeadershipBinding()
		{
			string text = ((_frithOwnerIdProperty != null) ? "OK" : "missing");
			string text2 = ((_frithNetProperty != null) ? "OK" : "missing");
			string text3 = ((_rosterTitleOfMethod != null) ? "OK" : "missing");
			_log.LogVerbose("[MANAGE-PERM] Innangard leadership binding: Frithstone.OwnerId=" + text + ", Frithstone.Net=" + text2 + ", SettlementRoster.TitleOf=" + text3 + ". Founder and appointed Leader share explicit management shortcuts; SharedAccess alone does not.");
		}

		internal static bool CanRequesterStrictlyManageSettler(object settler, long requesterId)
		{
			//IL_004d: 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_0053: 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)
			if (settler == null || requesterId == 0L)
			{
				return false;
			}
			try
			{
				if (_canManageMethod != null)
				{
					object obj = _canManageMethod.Invoke(settler, new object[1] { requesterId });
					if (!(obj is bool) || !(bool)obj)
					{
						return false;
					}
				}
			}
			catch
			{
				return false;
			}
			Vector3 position = HomePosition(settler);
			object obj3 = FindManagingFrith(position);
			if (obj3 == null)
			{
				obj3 = FindNearestLoadedFrith(position, 160f);
			}
			return CanRequesterLeadFrith(obj3, requesterId);
		}

		private static object FindNearestLoadedFrith(Vector3 position, float maxDistance)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (_frithInstancesField == null)
			{
				return null;
			}
			if (!(_frithInstancesField.GetValue(null) is IEnumerable enumerable))
			{
				return null;
			}
			object result = null;
			float num = Mathf.Max(0f, maxDistance);
			foreach (object item in enumerable)
			{
				Component val = (Component)((item is Component) ? item : null);
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.gameObject == (Object)null) && val.gameObject.activeInHierarchy)
				{
					float num2 = Distance(val.transform.position, position);
					if (num2 <= num)
					{
						num = num2;
						result = item;
					}
				}
			}
			return result;
		}

		internal static bool CanRequesterStrictlyManageAt(Vector3 position, long requesterId)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (requesterId == 0L || _frithCanManageMethod == null)
			{
				return false;
			}
			object obj = FindManagingFrith(position);
			if (obj == null)
			{
				return false;
			}
			try
			{
				object obj2 = _frithCanManageMethod.Invoke(obj, new object[1] { requesterId });
				return obj2 is bool && (bool)obj2 && CanRequesterLeadFrith(obj, requesterId);
			}
			catch
			{
				return false;
			}
		}

		internal static bool CanLocalPlayerStrictlyManageAt(Vector3 position)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				return CanRequesterStrictlyManageAt(position, localPlayer.GetPlayerID());
			}
			return false;
		}

		internal static bool AuthenticateManagementRequester(long sender, long requesterId, string action)
		{
			if (_networkAuthenticateMethod == null || requesterId == 0L)
			{
				return false;
			}
			try
			{
				object obj = _networkAuthenticateMethod.Invoke(null, new object[3]
				{
					sender,
					requesterId,
					action ?? "Innangard management"
				});
				return obj is bool && (bool)obj;
			}
			catch
			{
				return false;
			}
		}

		private static object FindManagingFrith(Vector3 position)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			if (_frithInstancesField == null || _frithCoversPointMethod == null)
			{
				return null;
			}
			if (!(_frithInstancesField.GetValue(null) is IEnumerable enumerable))
			{
				return null;
			}
			object result = null;
			float num = float.MaxValue;
			foreach (object item in enumerable)
			{
				Component val = (Component)((item is Component) ? item : null);
				if ((Object)(object)val == (Object)null || !val.gameObject.activeInHierarchy)
				{
					continue;
				}
				try
				{
					object obj = _frithCoversPointMethod.Invoke(item, new object[2] { position, 18f });
					if (!(obj is bool) || !(bool)obj)
					{
						continue;
					}
					goto IL_00b3;
				}
				catch
				{
				}
				continue;
				IL_00b3:
				float num2 = Vector3.Distance(val.transform.position, position);
				if (num2 < num)
				{
					num = num2;
					result = item;
				}
			}
			return result;
		}

		private static bool ViewBelongsToSupportedStation(ZNetView view)
		{
			if ((Object)(object)view == (Object)null || _stationTypes == null)
			{
				return false;
			}
			Type[] stationTypes = _stationTypes;
			foreach (Type type in stationTypes)
			{
				if (!(type == null) && ((Object)(object)((Component)view).GetComponent(type) != (Object)null || (Object)(object)((Component)view).GetComponentInParent(type) != (Object)null || (Object)(object)((Component)view).GetComponentInChildren(type, true) != (Object)null))
				{
					return true;
				}
			}
			return false;
		}

		private static ZNetView ViewOf(Component component)
		{
			if ((Object)(object)component == (Object)null)
			{
				return null;
			}
			return component.GetComponent<ZNetView>() ?? component.GetComponentInParent<ZNetView>() ?? component.GetComponentInChildren<ZNetView>(true);
		}

		private static string StationName(Component component)
		{
			if ((Object)(object)component == (Object)null)
			{
				return "Station";
			}
			Piece val = component.GetComponent<Piece>() ?? component.GetComponentInParent<Piece>();
			if ((Object)(object)val != (Object)null && !string.IsNullOrEmpty(val.m_name))
			{
				return val.m_name;
			}
			if (!((Object)(object)component.gameObject != (Object)null))
			{
				return "Station";
			}
			return ((Object)component.gameObject).name;
		}

		private static string StationName(ZNetView view)
		{
			return StationName((Component)(object)view);
		}
	}
	internal static class BetterOrganisationFavoriteTuning
	{
		private const string FavoriteMetadataKey = "ChestCategories_Favorite";

		private const string SortCargoKey = "inn_sort_cargo";

		private static ManualLogSource _log;

		private static Type _favoriteType;

		private static MethodInfo _isFavoriteMethod;

		private static MethodInfo _drawerTargetMatchesMethod;

		private static bool _loggedIncompatible;

		private static readonly HashSet<string> LoggedBlockedMetadata = new HashSet<string>(StringComparer.Ordinal);

		private static bool Active
		{
			get
			{
				if (Plugin.Enabled != null)
				{
					return Plugin.Enabled.Value;
				}
				return false;
			}
		}

		internal static void Initialize(ConfigFile config, ManualLogSource log, Harmony harmony)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			_log = log;
			if (!BindBetterOrganisation())
			{
				return;
			}
			Type type = AccessTools.TypeByName("Innangard.ChestSortRules");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "IsSortable", new Type[1] { typeof(ItemData) }, (Type[])null));
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(BetterOrganisationFavoriteTuning), "IsSortablePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Type type2 = AccessTools.TypeByName("Innangard.ItemDrawerBridge");
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "CanStore", (Type[])null, (Type[])null));
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(BetterOrganisationFavoriteTuning), "CanStorePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo3 = AccessTools.Method(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(BetterOrganisationFavoriteTuning), "SortingCargoAddPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)"[BO-FAVOURITE] Inventory.AddItem(ItemData) was not found; committed sorting cargo will keep BO favourite metadata until deposited.");
				}
			}
			if (methodInfo != null || methodInfo2 != null || methodInfo3 != null)
			{
				_log?.LogVerbose("[BO-FAVOURITE] Better Organisation favourites use known key 'ChestCategories_Favorite': active favourites are excluded from caretaker sorting, and the key is stripped when committed inn_sort_cargo enters an inventory. No Better Organisation IL scanning is used.");
			}
		}

		private static void IsSortablePostfix(ItemData __0, ref bool __result)
		{
			if (Active && __result && __0 != null && RawIsFavorite(__0))
			{
				__result = false;
			}
		}

		[HarmonyPriority(600)]
		private static void CanStorePostfix(ItemData __0, object __1, ref bool __result)
		{
			if (!(!Active | __result) && __0 != null && __1 != null && !((Object)(object)__0.m_dropPrefab == (Object)null) && __0.m_stack > 0 && !__0.m_equipped && __0.m_customData != null && __0.m_customData.Count != 0 && !RawIsFavorite(__0))
			{
				if (MetadataContainsOnly(__0, "ChestCategories_Favorite", allowSortCargo: false) && TargetMatches(__1, ((Object)__0.m_dropPrefab).name, __0.m_quality))
				{
					__result = true;
				}
				else
				{
					LogBlockedMetadataOnce(__0);
				}
			}
		}

		private static void SortingCargoAddPrefix(ItemData __0)
		{
			if (Active && __0?.m_customData != null && __0.m_customData.ContainsKey("inn_sort_cargo"))
			{
				__0.m_customData.Remove("ChestCategories_Favorite");
			}
		}

		private static bool MetadataContainsOnly(ItemData item, string allowedKey, bool allowSortCargo)
		{
			if (item?.m_customData == null || string.IsNullOrEmpty(allowedKey))
			{
				return false;
			}
			foreach (string key in item.m_customData.Keys)
			{
				if (!string.Equals(key, allowedKey, StringComparison.Ordinal) && (!allowSortCargo || !string.Equals(key, "inn_sort_cargo", StringComparison.Ordinal)))
				{
					return false;
				}
			}
			return item.m_customData.ContainsKey(allowedKey);
		}

		private static bool TargetMatches(object target, string prefab, int quality)
		{
			if (target == null || string.IsNullOrEmpty(prefab))
			{
				return false;
			}
			try
			{
				Type type = target.GetType();
				if (_drawerTargetMatchesMethod == null || _drawerTargetMatchesMethod.DeclaringType != type)
				{
					_drawerTargetMatchesMethod = AccessTools.Method(type, "Matches", new Type[2]
					{
						typeof(string),
						typeof(int)
					}, (Type[])null);
				}
				if (_drawerTargetMatchesMethod == null)
				{
					return false;
				}
				object obj = _drawerTargetMatchesMethod.Invoke(target, new object[2] { prefab, quality });
				return obj is bool && (bool)obj;
			}
			catch
			{
				return false;
			}
		}

		private static bool BindBetterOrganisation()
		{
			if (_favoriteType != null && _isFavoriteMethod != null)
			{
				return true;
			}
			Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => string.Equals(a.GetName().Name, "ChestCategories", StringComparison.OrdinalIgnoreCase));
			if (assembly == null)
			{
				return false;
			}
			_favoriteType = assembly.GetType("ChestCategories.Features.ItemFavorites", throwOnError: false);
			if (_favoriteType != null)
			{
				_isFavoriteMethod = AccessTools.Method(_favoriteType, "IsFavorite", new Type[1] { typeof(ItemData) }, (Type[])null);
			}
			if (_isFavoriteMethod == null && !_loggedIncompatible)
			{
				_loggedIncompatible = true;
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)"[BO-FAVOURITE] Better Organisation is installed, but its ItemFavorites API could not be bound; favourite-specific caretaker filtering is disabled.");
				}
			}
			return _isFavoriteMethod != null;
		}

		private static bool RawIsFavorite(ItemData item)
		{
			if (item == null)
			{
				return false;
			}
			if (_isFavoriteMethod == null && !BindBetterOrganisation())
			{
				return false;
			}
			try
			{
				object obj = _isFavoriteMethod.Invoke(null, new object[1] { item });
				return obj is bool && (bool)obj;
			}
			catch
			{
				return false;
			}
		}

		internal static void LogCommittedCargoMetadata(object settler, GameObject goal)
		{
			if (_log == null || settler == null)
			{
				return;
			}
			try
			{
				object? obj = settler.GetType().GetProperty("Inv", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(settler, null);
				Inventory val = (Inventory)((obj is Inventory) ? obj : null);
				if (val == null)
				{
					return;
				}
				foreach (ItemData allItem in val.GetAllItems())
				{
					if (allItem?.m_customData != null && allItem.m_customData.ContainsKey("inn_sort_cargo"))
					{
						string text = (((Object)(object)allItem.m_dropPrefab != (Object)null) ? ((Object)allItem.m_dropPrefab).name : (allItem.m_shared?.m_name ?? "<unknown>"));
						string text2 = string.Join(",", allItem.m_customData.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal));
						_log.LogVerbose("[BO-FAVOURITE] Committed drawer cargo diagnostic: prefab=" + text + " favouriteNow=" + RawIsFavorite(allItem) + " knownFavouriteKeyPresent=" + allItem.m_customData.ContainsKey("ChestCategories_Favorite") + " customData=[" + text2 + "] target=" + (((Object)(object)goal != (Object)null) ? ((Object)goal).name : "<none>") + ".");
						break;
					}
				}
			}
			catch
			{
			}
		}

		private static void LogBlockedMetadataOnce(ItemData item)
		{
			if (_log != null && item?.m_customData != null && item.m_customData.Count != 0)
			{
				string text = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : (item.m_shared?.m_name ?? "<unknown>"));
				string text2 = string.Join(",", item.m_customData.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal));
				string item2 = text + "|" + text2;
				if (LoggedBlockedMetadata.Add(item2))
				{
					_log.LogVerbose("[BO-FAVOURITE] Drawer sorting left " + text + " metadata intact because it contains custom data beyond the known Better Organisation favourite key. customData keys=[" + text2 + "].");
				}
			}
		}
	}
	internal static class BetterOrganisationIntegration
	{
		private static ConfigEntry<bool> _enabled;

		private static Harmony _harmony;

		private static bool _present;

		private static bool _rulesInstalled;

		private static bool _uiInstalled;

		private static float _nextRestoreOnlyScan;

		internal static ManualLogSource Log { get; private set; }

		internal static bool Active
		{
			get
			{
				if (Plugin.Enabled != null && Plugin.Enabled.Value && _present && _enabled != null)
				{
					return _enabled.Value;
				}
				return false;
			}
		}

		internal static void Initialize(ConfigFile config, ManualLogSource log, Harmony harmony)
		{
			Log = log;
			_harmony = harmony;
			_present = AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => string.Equals(a.GetName().Name, "ChestCategories", StringComparison.OrdinalIgnoreCase));
			if (_present)
			{
				_enabled = config.Bind<bool>("Better Organisation", "IntegrateWithInnangard", true, "When Better Organisation is installed, use its category/item destination rules for Innangard sorting and replace Innangard's redundant chest-rules material picker (Shift+E by default) on BO-managed chests with an Open Better Organisation button.");
				BetterOrganisationRules.Bind();
				BetterOrganisationDrawerPriority.Initialize(harmony);
				InstallPatches();
				BetterOrganisationRules.Refresh(forceSummary: true);
			}
		}

		internal static void Tick()
		{
			if (Active)
			{
				InstallPatches();
				BetterOrganisationRules.RefreshIncremental(4);
			}
		}

		internal static void RestoreMigratedDataOnlyTick()
		{
			if (Time.unscaledTime < _nextRestoreOnlyScan)
			{
				return;
			}
			_nextRestoreOnlyScan = Time.unscaledTime + 5f;
			int num = BetterOrganisationRules.RestoreLoadedMirrorsNoBinding();
			if (num > 0)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[020-RESTORE] Restored stock Innangard chest sorting fields on " + num + " loaded container(s); Better Organisation backup keys were retained."));
				}
			}
		}

		internal static void Shutdown()
		{
			if (_present)
			{
				BetterOrganisationRules.RestoreAll();
			}
		}

		private static void InstallPatches()
		{
			if (_harmony != null && Active)
			{
				if (!_rulesInstalled)
				{
					_rulesInstalled = BetterOrganisationRules.Install(_harmony);
				}
				if (!_uiInstalled)
				{
					_uiInstalled = BetterOrganisationChestPanelCompat.Install(_harmony);
				}
			}
		}

		internal static string Root(Exception e)
		{
			while (e is TargetInvocationException && e.InnerException != null)
			{
				e = e.InnerException;
			}
			if (e != null)
			{
				return e.ToString();
			}
			return "unknown error";
		}
	}
	internal static class BetterOrganisationDrawerPriority
	{
		private sealed class Query
		{
			internal Vector3 Centre;

			internal float Radius;

			internal float Seen;

			internal int BuiltFrame = -1;

			internal readonly HashSet<string> UsableNames = new HashSet<string>(StringComparer.Ordinal);
		}

		private static readonly List<Query> Recent = new List<Query>();

		private static MethodInfo _findTargets;

		private static PropertyInfo _home;

		private static PropertyInfo _scanRadius;

		private static PropertyInfo _targetValid;

		private static PropertyInfo _targetView;

		private static MethodInfo _itemTemplate;

		private static MethodInfo _externalTryGetReal;

		private static MethodInfo _externalGetFreeSpace;

		private static bool _installed;

		internal static void Initialize(Harmony harmony)
		{
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			if (_installed || harmony == null)
			{
				return;
			}
			Type type = AccessTools.TypeByName("Innangard.SettlerController");
			Type type2 = AccessTools.TypeByName("Innangard.ItemDrawerBridge");
			if (!(type == null) && !(type2 == null))
			{
				_findTargets = AccessTools.Method(type2, "FindTargets", (Type[])null, (Type[])null);
				_home = AccessTools.Property(type, "Home");
				_scanRadius = AccessTools.Property(type, "SettlementScanRadius");
				Type nestedType = type2.GetNestedType("Target", BindingFlags.Public | BindingFlags.NonPublic);
				if (nestedType != null)
				{
					_targetValid = AccessTools.Property(nestedType, "IsValid");
					_targetView = AccessTools.Property(nestedType, "View");
					_itemTemplate = AccessTools.Method(nestedType, "ItemTemplate", (Type[])null, (Type[])null);
				}
				Type type3 = AccessTools.TypeByName("InnangardBetrValheimDrawerBridge.Bridge");
				if (type3 != null)
				{
					_externalTryGetReal = AccessTools.Method(type3, "TryGetReal", (Type[])null, (Type[])null);
					_externalGetFreeSpace = AccessTools.Method(type3, "GetFreeSpace", (Type[])null, (Type[])null);
				}
				if (_findTargets == null || _home == null || _scanRadius == null || _targetValid == null || _itemTemplate == null)
				{
					BetterOrganisationIntegration.Log.LogWarning((object)"[BO] Could not bind Innangard drawer scan context; BO rules still work but transient drawer-first fallback protection is unavailable.");
					return;
				}
				harmony.Patch((MethodBase)_findTargets, (HarmonyMethod)null, new HarmonyMethod(typeof(BetterOrganisationDrawerPriority), "FindTargetsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_installed = true;
				BetterOrganisationIntegration.Log.LogVerbose("[BO] Matching ItemDrawers use virtual priority 2 inside the existing BO/Innangard precision comparison: priority 1 may override; priority 2 ties and larger values yield to the drawer. Usable drawer item names are derived once per frame per settlement query instead of reflection-scanning every drawer for every Precision check.");
			}
		}

		private static void FindTargetsPostfix(object __0, object __result)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_00e1: 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)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (__0 == null)
			{
				return;
			}
			try
			{
				Vector3 val = (Vector3)_home.GetValue(__0, null);
				float num = Convert.ToSingle(_scanRadius.GetValue(__0, null));
				float now = Time.unscaledTime;
				int frameCount = Time.frameCount;
				Recent.RemoveAll((Query q) => q == null || now - q.Seen > 3f);
				Query query = null;
				float num2 = float.MaxValue;
				for (int num3 = 0; num3 < Recent.Count; num3++)
				{
					Query query2 = Recent[num3];
					if (query2 != null && !(Mathf.Abs(query2.Radius - num) >= 1f))
					{
						float num4 = Vector3.Distance(query2.Centre, val);
						if (!(num4 >= 1f) && !(num4 >= num2))
						{
							query = query2;
							num2 = num4;
						}
					}
				}
				if (query == null)
				{
					query = new Query();
					Recent.Add(query);
				}
				query.Centre = val;
				query.Radius = num;
				query.Seen = now;
				if (query.BuiltFrame != frameCount)
				{
					query.BuiltFrame = frameCount;
					query.UsableNames.Clear();
					if (__result is IEnumerable enumerable)
					{
						foreach (object item in enumerable)
						{
							if (TryGetUsableTargetName(item, out var sharedName))
							{
								query.UsableNames.Add(sharedName);
							}
						}
					}
				}
				while (Recent.Count > 8)
				{
					int index = 0;
					float seen = Recent[0].Seen;
					for (int num5 = 1; num5 < Recent.Count; num5++)
					{
						if (Recent[num5].Seen < seen)
						{
							index = num5;
							seen = Recent[num5].Seen;
						}
					}
					Recent.RemoveAt(index);
				}
			}
			catch (Exception e)
			{
				BetterOrganisationIntegration.Log.LogWarning((object)("[BO] Could not remember Innangard drawer scan: " + BetterOrganisationIntegration.Root(e)));
			}
		}

		internal static bool MatchingDrawerBeforeBo(Container chest, string sharedName)
		{
			//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_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (!_installed || (Object)(object)chest == (Object)null || string.IsNullOrEmpty(sharedName))
			{
				return false;
			}
			float unscaledTime = Time.unscaledTime;
			Query query = null;
			float num = float.MaxValue;
			Vector3 position = ((Component)chest).transform.position;
			for (int i = 0; i < Recent.Count; i++)
			{
				Query query2 = Recent[i];
				if (query2 != null && !(unscaledTime - query2.Seen > 2f))
				{
					float num2 = Vector3.Distance(position, query2.Centre);
					if (!(num2 > query2.Radius + 10f) && !(num2 >= num))
					{
						query = query2;
						num = num2;
					}
				}
			}
			return query?.UsableNames.Contains(sharedName) ?? false;
		}

		private static bool TryGetUsableTargetName(object target, out string sharedName)
		{
			sharedName = null;
			if (target == null)
			{
				return false;
			}
			try
			{
				object value = _targetValid.GetValue(target, null);
				if (!(value is bool) || !(bool)value)
				{
					return false;
				}
				object? obj = _itemTemplate.Invoke(target, null);
				ItemData val = (ItemData)((obj is ItemData) ? obj : null);
				if (val?.m_shared == null || string.IsNullOrEmpty(val.m_shared.m_name))
				{
					return false;
				}
				if (_externalTryGetReal != null && _externalGetFreeSpace != null && _targetView != null)
				{
					object? value2 = _targetView.GetValue(target, null);
					ZNetView val2 = (ZNetView)((value2 is ZNetView) ? value2 : null);
					if ((Object)(object)val2 != (Object)null)
					{
						object[] array = new object[2] { val2, null };
						object obj2 = _externa