Decompiled source of Shima QoL v0.0.144

BepInEx/plugins/ShimaQoL/ShimaQoL.dll

Decompiled 4 hours ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using I2.Loc;
using MemoryPack;
using Mirror;
using PSS;
using SunHaven.DataSystems;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
using Wish;
using ZeroFormatter;

[assembly: AssemblyTitle("Shima QoL")]
[assembly: AssemblyFileVersion("0.0.144.0")]
[assembly: AssemblyInformationalVersion("0.0.144-early-access")]
[assembly: TargetFramework(".NETFramework,Version=v4.6")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyDescription("World tooltips, quick actions, stack splitting, plot planning and automation chests for Sun Haven.")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.144.0")]
[module: UnverifiableCode]
namespace ShimaQoL;

internal enum HotkeyAction
{
	None,
	Settings,
	Tooltips,
	Mine,
	Axe,
	Hoe,
	WateringCan,
	Scythe,
	Fishing,
	Mount,
	Attack,
	PlannerPoint,
	PlannerClear,
	AutomationLink,
	AutomationUnlink
}
internal static class ActionCatalog
{
	internal const int AllMovementActions = 63;

	internal static readonly HotkeyAction[] All = new HotkeyAction[8]
	{
		HotkeyAction.Mine,
		HotkeyAction.Axe,
		HotkeyAction.Hoe,
		HotkeyAction.WateringCan,
		HotkeyAction.Scythe,
		HotkeyAction.Attack,
		HotkeyAction.Fishing,
		HotkeyAction.Mount
	};

	internal static readonly HotkeyAction[] Planner = new HotkeyAction[2]
	{
		HotkeyAction.PlannerPoint,
		HotkeyAction.PlannerClear
	};

	internal static readonly HotkeyAction[] Automation = new HotkeyAction[2]
	{
		HotkeyAction.AutomationLink,
		HotkeyAction.AutomationUnlink
	};

	internal static readonly HotkeyAction[] Shortcuts = new HotkeyAction[12]
	{
		HotkeyAction.Mine,
		HotkeyAction.Axe,
		HotkeyAction.Hoe,
		HotkeyAction.WateringCan,
		HotkeyAction.Scythe,
		HotkeyAction.Attack,
		HotkeyAction.Fishing,
		HotkeyAction.Mount,
		HotkeyAction.PlannerPoint,
		HotkeyAction.PlannerClear,
		HotkeyAction.AutomationLink,
		HotkeyAction.AutomationUnlink
	};

	internal static bool IsShortcut(HotkeyAction action)
	{
		if (!IsAction(action) && action != HotkeyAction.PlannerPoint && action != HotkeyAction.PlannerClear && action != HotkeyAction.AutomationLink)
		{
			return action == HotkeyAction.AutomationUnlink;
		}
		return true;
	}

	internal static bool IsAction(HotkeyAction action)
	{
		if (action >= HotkeyAction.Mine)
		{
			return action <= HotkeyAction.Attack;
		}
		return false;
	}

	internal static bool Repeats(HotkeyAction action)
	{
		if (IsAction(action) && action != HotkeyAction.Fishing)
		{
			return action != HotkeyAction.Mount;
		}
		return false;
	}

	internal static int MovementBit(HotkeyAction action)
	{
		return action switch
		{
			HotkeyAction.Mine => 1, 
			HotkeyAction.Axe => 2, 
			HotkeyAction.Hoe => 4, 
			HotkeyAction.WateringCan => 8, 
			HotkeyAction.Scythe => 16, 
			HotkeyAction.Attack => 32, 
			_ => 0, 
		};
	}

	internal static string Name(HotkeyAction action)
	{
		return action switch
		{
			HotkeyAction.WateringCan => "Watering Can", 
			HotkeyAction.PlannerClear => "Clear/Reset", 
			HotkeyAction.PlannerPoint => "Start/Add Point", 
			HotkeyAction.AutomationUnlink => "Unlink station", 
			HotkeyAction.AutomationLink => "Link", 
			_ => action.ToString(), 
		};
	}
}
internal sealed class ActionMouseMovement : IDisposable
{
	private readonly Harmony _harmony = new Harmony("local.sakur.shimaqol.actions.movement");

	private static ActionMouseMovement _current;

	private readonly SettingsState _settings;

	private readonly Func<bool> _available;

	private readonly Func<bool> _shortcutHeld;

	private readonly Action<Exception> _report;

	private bool _inside;

	private bool _failed;

	private Vector2 _axes;

	private Type _secondaryType;

	private bool _secondarySupported;

	internal ActionMouseMovement(SettingsState settings, Func<bool> available, Func<bool> shortcutHeld, Action<Exception> report)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Expected O, but got Unknown
		//IL_00ee: 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
		if (_current != null)
		{
			throw new InvalidOperationException("Action movement is already attached.");
		}
		_settings = settings;
		_available = available;
		_shortcutHeld = shortcutHeld;
		_report = report;
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(Player), "HandleInput", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(PlayerInput), "GetAxis", new Type[2]
			{
				typeof(string),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				throw new MissingMethodException("Native player movement bindings differ.");
			}
			_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ActionMouseMovement), "BeforeInput", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ActionMouseMovement), "AfterInput", (Type[])null), (HarmonyMethod)null);
			_harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(ActionMouseMovement), "ReadAxis", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_current = this;
		}
		catch
		{
			_harmony.UnpatchSelf();
			throw;
		}
	}

	private static void BeforeInput(Player __instance)
	{
		ActionMouseMovement current = _current;
		if (current == null)
		{
			return;
		}
		current._inside = false;
		if (current._failed)
		{
			return;
		}
		try
		{
			current._inside = current.TryAxes(__instance, out current._axes);
		}
		catch (Exception obj)
		{
			current._failed = true;
			current._report(obj);
		}
	}

	private static Exception AfterInput(Exception __exception)
	{
		if (_current != null)
		{
			_current._inside = false;
		}
		return __exception;
	}

	private static void ReadAxis(string __0, bool __1, ref float __result)
	{
		ActionMouseMovement current = _current;
		if (current != null && current._inside && !__1)
		{
			if (__0 == "Horizontal")
			{
				__result = current._axes.x;
			}
			else if (__0 == "Vertical")
			{
				__result = current._axes.y;
			}
		}
	}

	private bool TryAxes(Player player, out Vector2 axes)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		axes = default(Vector2);
		if (!_settings.MoveWhileActing || !_settings.ActionsEnabled || !_available() || !GameplayGate.CanControl(player) || !PlayerInput.AllowMovement || player.Pathing || (Object)(object)player.Camera == (Object)null || !player.CanUseUseItem || !_settings.AllowsMovement(ActionFor(player.UseItem, player.Item)))
		{
			return false;
		}
		EventSystem current = EventSystem.current;
		if ((Object)(object)current != (Object)null && current.IsPointerOverGameObject())
		{
			return false;
		}
		if (!_shortcutHeld() && !PlayerInput.GetButton((Button)0, false) && !PlayerInput.GetButton("RightSwing") && (!PlayerInput.GetButton((Button)65, false) || !HasSecondaryAction(player.UseItem)))
		{
			return false;
		}
		if (Math.Abs(PlayerInput.GetAxis("Horizontal", false)) > 0.05f || Math.Abs(PlayerInput.GetAxis("Vertical", false)) > 0.05f)
		{
			return false;
		}
		Vector2 val = Utilities.MousePositionExact(0.75f);
		Vector3 position = ((Component)player).transform.position;
		float num = val.x - position.x;
		float num2 = val.y - position.y;
		if (float.IsNaN(num) || float.IsNaN(num2) || float.IsInfinity(num) || float.IsInfinity(num2))
		{
			return false;
		}
		if (num * num + num2 * num2 <= 0.0484f)
		{
			return true;
		}
		num2 /= 1.3f;
		float num3 = (float)Math.Sqrt(num * num + num2 * num2);
		axes = new Vector2(num / num3, num2 / num3);
		return true;
	}

	internal bool IsFollowing(UseItem item)
	{
		Player instance = Player.Instance;
		Vector2 axes;
		if (!_failed && (Object)(object)instance != (Object)null && object.ReferenceEquals(instance.UseItem, item))
		{
			return TryAxes(instance, out axes);
		}
		return false;
	}

	private bool HasSecondaryAction(UseItem item)
	{
		Type type = ((object)item).GetType();
		if (type == _secondaryType)
		{
			return _secondarySupported;
		}
		_secondaryType = type;
		_secondarySupported = false;
		string[] array = new string[3] { "Use2", "UseDown2", "UseUp2" };
		foreach (string name in array)
		{
			MethodInfo method = type.GetMethod(name, Type.EmptyTypes);
			if (method != null && method.DeclaringType != typeof(UseItem) && method.GetBaseDefinition().DeclaringType == typeof(UseItem))
			{
				_secondarySupported = true;
				break;
			}
		}
		return _secondarySupported;
	}

	private static HotkeyAction ActionFor(UseItem item, int id)
	{
		if (item is Pickaxe)
		{
			return HotkeyAction.Mine;
		}
		if (item is Axe)
		{
			return HotkeyAction.Axe;
		}
		if (item is Hoe)
		{
			return HotkeyAction.Hoe;
		}
		if (item is WateringCan)
		{
			return HotkeyAction.WateringCan;
		}
		if (item is FishingRod)
		{
			return HotkeyAction.None;
		}
		if (item is Weapon && (id == 3000 || id == 30007))
		{
			return HotkeyAction.Scythe;
		}
		if (!(item is Sword) && !(item is CrossBow))
		{
			return HotkeyAction.None;
		}
		return HotkeyAction.Attack;
	}

	public void Dispose()
	{
		if (object.ReferenceEquals(_current, this))
		{
			_inside = false;
			_current = null;
			_harmony.UnpatchSelf();
		}
	}
}
internal interface IInteractiveActionSession
{
	void UpdateInput();
}
internal interface IActionSession
{
	bool IsCurrent { get; }

	bool CanAct { get; }

	int CandidateCount { get; }

	bool Finished { get; }

	void Inspect(int candidate, Action<bool> complete);

	bool Equip(int candidate);

	bool UseOnce();

	void Restore();
}
internal sealed class ActionRunner
{
	private enum Stage
	{
		Idle,
		Searching,
		Loading,
		Prepared,
		Armed,
		Swinging,
		Repeating
	}

	private Stage _stage;

	private IActionSession _session;

	private int _candidate;

	private int _generation;

	private int _equipFrame;

	private float _deadline;

	private string _name;

	private Func<bool> _repeat;

	internal bool Busy => _stage != Stage.Idle;

	internal bool ToolEquipped
	{
		get
		{
			if (_repeat != null && _session != null && _session.IsCurrent)
			{
				if (_stage != Stage.Armed && _stage != Stage.Swinging)
				{
					return _stage == Stage.Repeating;
				}
				return true;
			}
			return false;
		}
	}

	internal string Status { get; private set; }

	internal bool Failed { get; private set; }

	internal Func<bool> WaitForTarget { get; set; }

	internal bool Start(IActionSession session, float now, string name = "Mine", Func<bool> repeat = null)
	{
		if (Busy || session == null || !session.CanAct || !session.IsCurrent)
		{
			return false;
		}
		_session = session;
		_candidate = 0;
		_generation++;
		_name = name;
		_repeat = repeat;
		_deadline = now + 5f;
		_stage = Stage.Searching;
		Failed = false;
		Status = "Finding a tool for " + _name + "...";
		return true;
	}

	internal void Tick(int frame, float now)
	{
		if (!Busy)
		{
			return;
		}
		if (!_session.IsCurrent)
		{
			End("Action cancelled: selection or scene changed.", failed: false);
			return;
		}
		if (_stage == Stage.Swinging)
		{
			if (_session is IInteractiveActionSession interactiveActionSession)
			{
				interactiveActionSession.UpdateInput();
			}
			if (_session.Finished)
			{
				if (_repeat != null && _repeat() && _session.CanAct)
				{
					_equipFrame = frame;
					_stage = Stage.Repeating;
				}
				else
				{
					End(_name + " complete.", failed: false);
				}
			}
			return;
		}
		if (_stage == Stage.Repeating)
		{
			if (_repeat == null || !_repeat() || !_session.CanAct)
			{
				End(_name + " complete.", failed: false);
			}
			else if (frame > _equipFrame)
			{
				Use();
			}
			return;
		}
		if (!_session.CanAct)
		{
			End("Action cancelled.", failed: false);
			return;
		}
		if (now > _deadline)
		{
			End(_name + " timed out while preparing the tool.", failed: true);
			return;
		}
		switch (_stage)
		{
		case Stage.Searching:
		{
			if (_candidate >= _session.CandidateCount)
			{
				End("No usable tool for " + _name + " found in your inventory.", failed: true);
				break;
			}
			int token = _generation;
			_stage = Stage.Loading;
			_session.Inspect(_candidate, delegate(bool matches)
			{
				if (token == _generation && _stage == Stage.Loading)
				{
					if (matches)
					{
						_stage = Stage.Prepared;
					}
					else
					{
						_candidate++;
						_stage = Stage.Searching;
					}
				}
			});
			break;
		}
		case Stage.Prepared:
			if (!_session.Equip(_candidate))
			{
				End(_name + " tool changed or could not be equipped.", failed: true);
				break;
			}
			_equipFrame = frame;
			_stage = Stage.Armed;
			Status = "Preparing " + _name + "...";
			break;
		case Stage.Armed:
			if (frame > _equipFrame)
			{
				Use();
			}
			break;
		case Stage.Loading:
			break;
		}
	}

	private void Use()
	{
		if (_repeat != null && _repeat() && WaitForTarget != null && WaitForTarget())
		{
			_stage = Stage.Repeating;
			Status = "Waiting for a target for " + _name + "...";
		}
		else if (!_session.UseOnce())
		{
			End(_name + " could not start. Check the tool and target.", failed: true);
		}
		else
		{
			_stage = Stage.Swinging;
			Status = _name + " in progress...";
		}
	}

	internal void StopRepeating()
	{
		_repeat = null;
	}

	internal void Cancel(string reason)
	{
		if (Busy)
		{
			End(reason, failed: false);
		}
	}

	private void End(string status, bool failed)
	{
		IActionSession session = _session;
		_session = null;
		_repeat = null;
		_stage = Stage.Idle;
		_generation++;
		Status = status;
		Failed = failed;
		session?.Restore();
	}
}
[DefaultExecutionOrder(10000)]
public sealed class ActionRuntime : MonoBehaviour
{
	internal const string StandaloneGuid = "local.sakur.sunhaven.quickactions";

	internal const string StandaloneMessage = "Remove the standalone Quick Actions DLL\nand restart to use the merged actions.";

	private ManualLogSource _logger;

	private SettingsState _settings;

	private SettingsPanel _panel;

	private MouseActionInput _mouseInput;

	private ActionMouseMovement _movement;

	private FarmToolTargeting _farmTargets;

	private HotkeyAction _activeAction;

	private int _activeBinding;

	private readonly ActionRunner _runner = new ActionRunner();

	private bool _inputActive;

	private bool _disposed;

	private bool _actionErrorLogged;

	private bool _standaloneLoaded;

	internal Func<bool> InputBlocked { get; set; }

	internal void Initialize(SettingsState settings, SettingsPanel panel, ManualLogSource logger, bool standaloneLoaded)
	{
		_settings = settings;
		_panel = panel;
		_logger = logger;
		_standaloneLoaded = standaloneLoaded;
		if (standaloneLoaded)
		{
			panel.SetActionsUnavailable("Remove the standalone Quick Actions DLL\nand restart to use the merged actions.");
			logger.LogWarning((object)"Standalone Quick Actions is installed. Merged actions are inactive to avoid duplicate input. Remove QuickActions.dll from the active plugins and restart.");
			return;
		}
		_inputActive = true;
		try
		{
			_mouseInput = new MouseActionInput(() => _inputActive && MouseActionInput.ShouldReserve(_settings, _panel.BlocksActions));
		}
		catch (Exception ex)
		{
			logger.LogWarning((object)("Mouse shortcuts are unavailable: " + ex.Message));
		}
		try
		{
			_movement = new ActionMouseMovement(settings, () => _inputActive && !_disposed && !_panel.BlocksActions, HeldMovementAction, delegate(Exception error)
			{
				logger.LogWarning((object)("Move toward mouse disabled for this session: " + error.Message));
			});
		}
		catch (Exception ex2)
		{
			logger.LogWarning((object)("Move toward mouse is unavailable: " + ex2.Message));
		}
		if (_movement != null)
		{
			try
			{
				_farmTargets = new FarmToolTargeting(_movement.IsFollowing, delegate(Exception error)
				{
					logger.LogWarning((object)("Farming target assistance disabled for this session: " + error.Message));
				});
				_runner.WaitForTarget = () => _farmTargets.ShouldWait(Player.Instance.UseItem);
			}
			catch (Exception ex3)
			{
				logger.LogWarning((object)("Farming target assistance is unavailable: " + ex3.Message));
			}
		}
		if (!ToolSession.BindingsAvailable)
		{
			logger.LogWarning((object)"Tool actions are unavailable: this game build's tool bindings differ.");
		}
		if (!FishingFlow.BindingsAvailable)
		{
			logger.LogWarning((object)"Fishing is unavailable: this game build's fishing bindings differ.");
		}
		if (!MountSession.BindingsAvailable)
		{
			logger.LogWarning((object)"Mount is unavailable: this game build's mount bindings differ.");
		}
		logger.LogInfo((object)"[Runtime] Quick Actions ready in the Shima QoL settings window.");
	}

	private void Update()
	{
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		if (_settings == null || !_inputActive || _disposed)
		{
			return;
		}
		_panel.SetActionStatus(_runner.Status);
		if (InputBlocked != null && InputBlocked())
		{
			_runner.StopRepeating();
			return;
		}
		if (_panel.BlocksActions || !_settings.ActionsEnabled || !Application.isFocused || GameplayGate.GameUiOpen || GameplayGate.TextInput)
		{
			_runner.StopRepeating();
		}
		if (_panel.BlocksActions || !_settings.ActionsEnabled || _runner.Busy)
		{
			return;
		}
		HotkeyAction[] all = ActionCatalog.All;
		foreach (HotkeyAction hotkeyAction in all)
		{
			int binding = _settings.KeyFor(hotkeyAction);
			KeyCode val = (KeyCode)binding;
			if (binding == 0 || !HotkeyInput.Pressed(binding))
			{
				continue;
			}
			if ((HotkeyInput.IsMouseKey(val) && _mouseInput == null) || !GameplayGate.CanAct(Player.Instance, val, hotkeyAction == HotkeyAction.Fishing))
			{
				break;
			}
			try
			{
				HotkeyAction selectedAction = hotkeyAction;
				Func<bool> func = () => _inputActive && _settings.ActionsEnabled && !_panel.BlocksActions && _settings.KeyFor(selectedAction) == binding;
				if (hotkeyAction == HotkeyAction.Mount)
				{
					if (MountSession.Ready(Player.Instance, val))
					{
						_runner.Start(new MountSession(Player.Instance, val, func), Time.unscaledTime, "Mount");
						_activeAction = hotkeyAction;
						_activeBinding = binding;
						_actionErrorLogged = false;
					}
				}
				else if (ToolSession.Ready(Player.Instance, val, hotkeyAction))
				{
					ToolSession session = new ToolSession(Player.Instance, val, hotkeyAction);
					session.ShortcutEnabled = func;
					Func<bool> repeat = ((!ActionCatalog.Repeats(hotkeyAction)) ? null : ((Func<bool>)(() => session.ShortcutEnabled() && HotkeyInput.Held(binding))));
					if (_runner.Start(session, Time.unscaledTime, ActionCatalog.Name(hotkeyAction), repeat))
					{
						_activeAction = hotkeyAction;
						_activeBinding = binding;
					}
					_actionErrorLogged = false;
				}
				break;
			}
			catch (Exception error)
			{
				Fail(error);
				break;
			}
		}
	}

	private void LateUpdate()
	{
		if (!_inputActive || _disposed || !_runner.Busy)
		{
			return;
		}
		try
		{
			_runner.Tick(Time.frameCount, Time.unscaledTime);
			if (!_runner.Busy && _runner.Failed)
			{
				_logger.LogDebug((object)_runner.Status);
			}
		}
		catch (Exception error)
		{
			Fail(error);
		}
	}

	private bool HeldMovementAction()
	{
		if (_runner.ToolEquipped && _settings.AllowsMovement(_activeAction) && ActionCatalog.Repeats(_activeAction) && _activeBinding != 0 && _settings.KeyFor(_activeAction) == _activeBinding)
		{
			return HotkeyInput.Held(_activeBinding);
		}
		return false;
	}

	private void Fail(Exception error)
	{
		Cancel("Currently unsupported action — cancelled safely. Other actions remain available.");
		if (!_actionErrorLogged)
		{
			_actionErrorLogged = true;
			_logger.LogWarning((object)("Action: " + error));
		}
	}

	internal void Cancel(string reason)
	{
		try
		{
			_runner.Cancel(reason);
		}
		catch (Exception ex)
		{
			if (_logger != null)
			{
				_logger.LogWarning((object)("Could not restore the previous tool: " + ex.Message));
			}
		}
	}

	internal void Suspend()
	{
		_inputActive = false;
		Cancel("Action cancelled because the runtime was disabled.");
	}

	internal void Resume()
	{
		if (!_disposed && !_standaloneLoaded && _settings != null)
		{
			_inputActive = true;
		}
	}

	internal void Shutdown()
	{
		if (_disposed)
		{
			return;
		}
		_disposed = true;
		Suspend();
		_runner.WaitForTarget = null;
		if (_farmTargets != null)
		{
			_farmTargets.Dispose();
			_farmTargets = null;
		}
		if (_movement != null)
		{
			_movement.Dispose();
			_movement = null;
		}
		if (_mouseInput == null)
		{
			return;
		}
		try
		{
			_mouseInput.Dispose();
		}
		catch (Exception ex)
		{
			_logger.LogWarning((object)("Could not remove action input hooks: " + ex.Message));
		}
		finally
		{
			_mouseInput = null;
		}
	}

	private void OnEnable()
	{
		Resume();
	}

	private void OnDisable()
	{
		Suspend();
	}

	private void OnDestroy()
	{
		Shutdown();
	}
}
internal sealed class AutomationCollection : IDisposable
{
	internal sealed class Run
	{
		internal readonly List<ItemAmount> Items = new List<ItemAmount>();

		internal readonly List<int> Entries = new List<int>();

		internal Action Changed;

		internal Action Finished;

		internal bool RoutineDone;

		internal bool Failed;

		internal bool Done;

		internal bool Opening;

		internal bool Started;

		internal int Steps;

		internal string MissedPickup;

		internal float LoadingSince = -1f;

		internal Func<bool> OwnerValid;

		internal CraftingTable Table;

		internal CraftingTableData Before;

		internal IList<ItemAmount> RequiredItems;

		internal IEnumerator Routine;
	}

	[ThreadStatic]
	private static Run _current;

	private static readonly Harmony Hooks = new Harmony("local.sakur.sunhaven.shimaqol.automation.collection");

	private static readonly FieldInfo DatabaseTypes = typeof(Database).GetField("types", BindingFlags.Instance | BindingFlags.NonPublic);

	private static readonly FieldInfo DatabaseCache = typeof(Database).GetField("cache", BindingFlags.Instance | BindingFlags.NonPublic);

	private readonly HashSet<string> _preloading = new HashSet<string>();

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

	private readonly List<Run> _active = new List<Run>();

	private readonly Action<IEnumerator> _schedule;

	private readonly Action<string> _trace;

	private static int _clients;

	private bool _disposed;

	private GameObject _proxyRoot;

	private CraftingTable _proxy;

	internal string SelectionNotice { get; private set; }

	internal AutomationCollection(Action<IEnumerator> schedule, Action<string> trace = null)
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Expected O, but got Unknown
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Expected O, but got Unknown
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Expected O, but got Unknown
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Expected O, but got Unknown
		if (schedule == null)
		{
			throw new ArgumentNullException("schedule");
		}
		_schedule = schedule;
		_trace = trace;
		if (_clients++ != 0)
		{
			return;
		}
		try
		{
			Hooks.Patch((MethodBase)AutomationMethods.SpawnPickup, new HarmonyMethod(typeof(AutomationCollection), "Capture", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StationSendMeta, new HarmonyMethod(typeof(AutomationCollection), "SendMeta", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StationResetBubbles, new HarmonyMethod(typeof(AutomationCollection), "KeepVisuals", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StationQueueImages, new HarmonyMethod(typeof(AutomationCollection), "KeepVisuals", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch
		{
			_clients = 0;
			Hooks.UnpatchSelf();
			throw;
		}
	}

	private static bool Capture(float __0, float __1, float __2, Item __3, int __4)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: 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_01c8: Expected O, but got Unknown
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		if (_current == null)
		{
			return true;
		}
		CraftingTable table = _current.Table;
		Vector3 position = ((Component)table).transform.position;
		float x = position.x;
		Vector2Int size = ((Decoration)table).Size;
		if (!PickupXMatches(__0, x, ((Vector2Int)(ref size)).x) || __1 != position.y || __2 != position.z)
		{
			if (__3 != null)
			{
				foreach (ItemAmount requiredItem in _current.RequiredItems)
				{
					if (requiredItem.item.ID() == __3.ID())
					{
						Run current2 = _current;
						object[] array = new object[18]
						{
							"station ",
							((Decoration)table).id,
							", item ",
							__3.ID(),
							", spawn (",
							__0,
							", ",
							__1,
							", ",
							__2,
							"), origin (",
							position.x,
							", ",
							position.y,
							", ",
							position.z,
							"), width ",
							null
						};
						Vector2Int size2 = ((Decoration)table).Size;
						array[17] = ((Vector2Int)(ref size2)).x;
						current2.MissedPickup = string.Concat(array);
						break;
					}
				}
			}
			return true;
		}
		if (__3 == null || __4 <= 0)
		{
			throw new InvalidOperationException("Invalid native collection output.");
		}
		List<ItemAmount> items = _current.Items;
		ItemAmount val = new ItemAmount();
		val.item = Utilities.DeepCloneItem(__3);
		val.amount = __4;
		items.Add(val);
		_current.Entries.Add(_current.Steps);
		_current.Changed();
		return false;
	}

	internal static bool PickupXMatches(float actual, float origin, int width)
	{
		double num = (double)width / 12.0;
		double num2 = (double)origin + num - 0.125;
		double num3 = Math.Max(0.0001, (Math.Abs((double)origin) + Math.Abs(num) + 0.125) * 1.1920928955078125E-07);
		return Math.Abs((double)actual - num2) <= num3;
	}

	internal static bool Owns(CraftingTable table)
	{
		if (_current != null)
		{
			return object.ReferenceEquals(_current.Table, table);
		}
		return false;
	}

	private static bool SendMeta(CraftingTable __instance)
	{
		if (_current != null)
		{
			return !object.ReferenceEquals(_current.Table, __instance);
		}
		return true;
	}

	private static bool KeepVisuals(CraftingTable __instance)
	{
		if (_current != null)
		{
			return !object.ReferenceEquals(_current.Table, __instance);
		}
		return true;
	}

	private void Trace(string text)
	{
		try
		{
			if (_trace != null)
			{
				_trace(text);
			}
		}
		catch
		{
		}
	}

	private static bool Cached(int id, Type t)
	{
		IDictionary dictionary = (IDictionary)DatabaseCache.GetValue(Database.Instance);
		if (dictionary.Contains(t))
		{
			return ((IDictionary)dictionary[t]).Contains(id);
		}
		return false;
	}

	internal bool Ready(IList<ItemAmount> items)
	{
		Dictionary<int, Type> dictionary = (Dictionary<int, Type>)DatabaseTypes.GetValue(Database.Instance);
		bool result = true;
		foreach (ItemAmount item in items)
		{
			if (!dictionary.TryGetValue(item.item.ID(), out var value))
			{
				return false;
			}
			if (!Cached(item.item.ID(), typeof(ItemData)))
			{
				result = false;
				Prefetch<ItemData>(item.item.ID());
			}
			if (item.item is FoodItem && typeof(FoodData).IsAssignableFrom(value) && !Cached(item.item.ID(), typeof(FoodData)))
			{
				result = false;
				Prefetch<FoodData>(item.item.ID());
			}
			if (typeof(SeedData).IsAssignableFrom(value) && !Cached(item.item.ID(), typeof(SeedData)))
			{
				result = false;
				Prefetch<SeedData>(item.item.ID());
			}
		}
		return result;
	}

	internal string Selection(IList<ItemAmount> items, bool allowPlaceables, Func<ItemAmount, int> fit = null)
	{
		if (items == null || items.Count > 4096)
		{
			throw new AutomationWaitException("Completed backlog exceeds the automation safety limit. Collect some output manually.");
		}
		SelectionNotice = null;
		List<string> list = new List<string>();
		List<ItemAmount> list2 = new List<ItemAmount>(1);
		bool flag = false;
		bool flag2 = false;
		bool flag3 = false;
		string text = null;
		Dictionary<int, Type> dictionary = (Dictionary<int, Type>)DatabaseTypes.GetValue(Database.Instance);
		for (int i = 0; i < items.Count; i++)
		{
			ItemAmount val = items[i];
			int num = ((val != null && val.item != null) ? val.item.ID() : 0);
			string text2 = "Item " + num;
			if (!dictionary.ContainsKey(num) || (_itemRetry.TryGetValue(num, out var value) && Time.unscaledTime < value))
			{
				if (text == null)
				{
					text = text2;
				}
				continue;
			}
			try
			{
				list2.Clear();
				list2.Add(val);
				if (!Ready(list2))
				{
					flag = true;
					continue;
				}
				ItemData data = null;
				Database.GetData<ItemData>(num, (Action<ItemData>)delegate(ItemData loaded)
				{
					data = loaded;
				}, (Action)null);
				if ((Object)(object)data == (Object)null)
				{
					flag = true;
					continue;
				}
				if (!string.IsNullOrEmpty(data.UnformattedDisplayName))
				{
					text2 = data.UnformattedDisplayName.Replace('\n', ' ').Replace('\r', ' ');
				}
				if (text2.Length > 80)
				{
					text2 = text2.Substring(0, 80);
				}
				if (!allowPlaceables && data.useItem is Placeable)
				{
					flag2 = true;
					continue;
				}
				switch (fit?.Invoke(val) ?? 0)
				{
				case 2:
					if (text == null)
					{
						text = text2;
					}
					continue;
				case 1:
					flag3 = true;
					continue;
				}
				list.Add(i.ToString(CultureInfo.InvariantCulture));
				if (list.Count == 32)
				{
					break;
				}
			}
			catch (Exception ex)
			{
				if (text == null)
				{
					text = text2;
				}
				if (_itemRetry.Count >= 4096)
				{
					_itemRetry.Clear();
				}
				_itemRetry[num] = Time.unscaledTime + 3f;
				Trace("Unsupported output " + num + ": " + ex);
			}
		}
		SelectionNotice = ((text != null) ? ("Currently unsupported transfer: " + text + ". Left at station; other items can continue.") : (flag3 ? "Storage full — output waiting for space." : (flag ? "Loading native item data" : (flag2 ? "Placeable output: collect manually" : null))));
		return string.Join(",", list.ToArray());
	}

	private void Prefetch<T>(int id) where T : ScriptableObject, IDatabaseData
	{
		string key = typeof(T).FullName + "|" + id;
		if (!_preloading.Add(key))
		{
			return;
		}
		try
		{
			Database.GetData<T>(id, (Action<T>)delegate
			{
				_preloading.Remove(key);
			}, (Action)delegate
			{
				_preloading.Remove(key);
			});
		}
		catch
		{
			_preloading.Remove(key);
			throw;
		}
	}

	internal CraftingTable Detached(int item)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Expected O, but got Unknown
		if (_active.Count != 0)
		{
			throw new AutomationWaitException("A native collection is finishing.");
		}
		if ((Object)(object)_proxyRoot == (Object)null)
		{
			_proxyRoot = new GameObject("Shima QoL collection context");
			_proxyRoot.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_proxyRoot);
			_proxyRoot.transform.position = new Vector3(0f, -4096f, -4096f);
			_proxy = _proxyRoot.AddComponent<CraftingTable>();
			((Decoration)_proxy).size = new Vector2Int(6, 6);
			CraftingTable proxy = _proxy;
			CraftingTableData val = new CraftingTableData();
			val.items = new List<ItemCraftInfo>();
			val.completeItems = new List<ItemAmount>();
			AutomationNative.SetCraftingData(proxy, val);
		}
		((Decoration)_proxy).id = item;
		return _proxy;
	}

	internal Run Collect(CraftingTable table, CraftingTableData before, Action<Run> changed, Action<Run> finished)
	{
		if (_disposed)
		{
			throw new ObjectDisposedException("AutomationCollection");
		}
		if (before == null || before.completeItems == null || before.completeItems.Count < 1 || before.completeItems.Count > 32)
		{
			throw new InvalidOperationException("Invalid automation collection batch.");
		}
		if (!Ready(before.completeItems))
		{
			throw new InvalidOperationException("Native item data is still loading.");
		}
		Run run = new Run
		{
			Table = table,
			Before = before,
			RequiredItems = new List<ItemAmount>(before.completeItems)
		};
		run.Changed = delegate
		{
			changed(run);
		};
		run.Finished = delegate
		{
			finished(run);
		};
		Player owner = Player.Instance;
		CharacterData character = GameSave.CurrentCharacter;
		GameSave save = SingletonBehaviour<GameSave>.Instance;
		WorldData world = save.CurrentWorld;
		run.OwnerValid = delegate
		{
			if ((Object)(object)owner != (Object)null && owner.IsOwner && object.ReferenceEquals(Player.Instance, owner) && object.ReferenceEquals(GameSave.CurrentCharacter, character) && object.ReferenceEquals(SingletonBehaviour<GameSave>.Instance, save) && object.ReferenceEquals(save.CurrentWorld, world) && (Object)(object)table != (Object)null)
			{
				if (!object.ReferenceEquals(table, _proxy))
				{
					return ObjectPicker.IsUsable((Decoration)(object)table);
				}
				if ((Object)(object)_proxyRoot != (Object)null)
				{
					return !_proxyRoot.activeSelf;
				}
				return false;
			}
			return false;
		};
		_active.Add(run);
		Trace("Collection scheduled: station " + ((Decoration)table).id + ", entries " + run.RequiredItems.Count);
		try
		{
			_schedule(Advance(run));
		}
		catch
		{
			run.Failed = true;
			Complete(run);
			throw;
		}
		return run;
	}

	private IEnumerator Advance(Run run)
	{
		try
		{
			object wait;
			while (!run.Done && Step(run, out wait))
			{
				yield return wait;
			}
		}
		finally
		{
			Complete(run);
		}
	}

	private bool Step(Run run, out object wait)
	{
		wait = null;
		try
		{
			if (_disposed || !run.OwnerValid())
			{
				throw new InvalidOperationException("Native collection context changed.");
			}
			if (!Ready(run.RequiredItems))
			{
				if (run.LoadingSince < 0f)
				{
					run.LoadingSince = Time.unscaledTime;
				}
				if (Time.unscaledTime - run.LoadingSince > 10f)
				{
					throw new InvalidOperationException("Native item data did not become ready.");
				}
				return true;
			}
			run.LoadingSince = -1f;
			if (run.Steps >= 64)
			{
				throw new InvalidOperationException("Native collection step limit exceeded.");
			}
			bool flag = !run.Started;
			CraftingTableData data = AutomationNative.Crafting(run.Table);
			Run current = _current;
			_current = run;
			try
			{
				if (flag)
				{
					run.Opening = AutomationNative.IsOpening(run.Table);
					run.Started = true;
					AutomationNative.SetCraftingData(run.Table, run.Before);
					run.Routine = (IEnumerator)AutomationMethods.StationCollect.Invoke(run.Table, null);
				}
				Trace("Collection step begin: station " + ((Decoration)run.Table).id + ", step " + run.Steps);
				bool flag2 = run.Routine.MoveNext();
				run.Steps++;
				Trace("Collection step end: station " + ((Decoration)run.Table).id + ", step " + run.Steps);
				if (flag2)
				{
					wait = run.Routine.Current;
				}
				return flag2;
			}
			finally
			{
				try
				{
					if (flag)
					{
						Trace("Collection metadata restore begin: station " + ((Decoration)run.Table).id);
						AutomationNative.SetCraftingData(run.Table, data);
						((Decoration)run.Table).SaveMeta();
						Trace("Collection metadata restore end: station " + ((Decoration)run.Table).id);
					}
				}
				finally
				{
					_current = current;
				}
			}
		}
		catch (Exception ex)
		{
			run.Failed = true;
			Trace("Collection interrupted: " + ex.Message);
			return false;
		}
	}

	private void Complete(Run run)
	{
		if (run.Done)
		{
			return;
		}
		run.Done = true;
		run.RoutineDone = true;
		_active.Remove(run);
		try
		{
			if (run.Routine is IDisposable disposable)
			{
				disposable.Dispose();
			}
			if (run.Started && (Object)(object)run.Table != (Object)null)
			{
				AutomationNative.SetOpening(run.Table, run.Opening);
			}
		}
		catch (Exception ex)
		{
			run.Failed = true;
			Trace("Collection cleanup: " + ex.Message);
		}
		finally
		{
			if (run.MissedPickup != null)
			{
				Trace("Collection pickup outside station rounding bounds: " + run.MissedPickup);
			}
			Trace("Collection completed: captured stacks " + run.Items.Count + ", interrupted " + run.Failed);
			run.Finished();
		}
	}

	public void Dispose()
	{
		if (_disposed)
		{
			return;
		}
		_disposed = true;
		try
		{
			Run[] array = _active.ToArray();
			foreach (Run run in array)
			{
				run.Failed = true;
				Complete(run);
			}
		}
		finally
		{
			if ((Object)(object)_proxyRoot != (Object)null)
			{
				Object.Destroy((Object)(object)_proxyRoot);
			}
			_proxyRoot = null;
			_proxy = null;
			if (--_clients == 0)
			{
				Hooks.UnpatchSelf();
			}
		}
	}
}
internal struct AutomationAnchor : IEquatable<AutomationAnchor>
{
	internal int Scene;

	internal int X;

	internal int Y;

	internal int Z;

	internal int Item;

	internal bool SamePlace(AutomationAnchor b)
	{
		if (Scene == b.Scene && X == b.X && Y == b.Y)
		{
			return Z == b.Z;
		}
		return false;
	}

	public bool Equals(AutomationAnchor b)
	{
		if (SamePlace(b))
		{
			return Item == b.Item;
		}
		return false;
	}

	public override bool Equals(object obj)
	{
		if (obj is AutomationAnchor)
		{
			return Equals((AutomationAnchor)obj);
		}
		return false;
	}

	public override int GetHashCode()
	{
		return (Scene * 397) ^ (X * 31) ^ (Y * 17) ^ Z ^ Item;
	}

	internal void Write(BinaryWriter w)
	{
		w.Write(Scene);
		w.Write(X);
		w.Write(Y);
		w.Write(Z);
		w.Write(Item);
	}

	internal static AutomationAnchor Read(BinaryReader r)
	{
		return new AutomationAnchor
		{
			Scene = r.ReadInt32(),
			X = r.ReadInt32(),
			Y = r.ReadInt32(),
			Z = r.ReadInt32(),
			Item = r.ReadInt32()
		};
	}
}
internal sealed class AutomationLink
{
	internal AutomationAnchor Source;

	internal AutomationAnchor Target;

	internal string Owner;

	internal string TargetName;

	internal int Slots;

	internal bool Manual;

	internal byte[] Rules;

	internal void Write(BinaryWriter w)
	{
		Source.Write(w);
		Target.Write(w);
		w.Write(Owner);
		w.Write(TargetName);
		w.Write(Slots);
		w.Write(Manual);
		AutomationData.WriteBytes(w, Rules);
	}

	internal static AutomationLink Read(BinaryReader r, int version)
	{
		AutomationLink automationLink = new AutomationLink();
		automationLink.Source = AutomationAnchor.Read(r);
		automationLink.Target = AutomationAnchor.Read(r);
		automationLink.Owner = r.ReadString();
		automationLink.TargetName = r.ReadString();
		automationLink.Slots = r.ReadInt32();
		AutomationLink automationLink2 = automationLink;
		if (version >= 2)
		{
			automationLink2.Manual = r.ReadBoolean();
		}
		if (version >= 3)
		{
			automationLink2.Rules = AutomationData.ReadBytes(r);
			if (automationLink2.Rules.Length > 8192)
			{
				throw new InvalidDataException("Invalid storage rules.");
			}
		}
		return automationLink2;
	}
}
internal sealed class AutomationJob
{
	internal string Id;

	internal string Owner;

	internal AutomationAnchor Source;

	internal AutomationAnchor Target;

	internal int Slots;

	internal bool Captured;

	internal byte[] Before;

	internal byte[] Pending;

	internal string[] Makers;

	internal void Write(BinaryWriter w, bool full)
	{
		w.Write(Id);
		w.Write(Owner);
		Source.Write(w);
		Target.Write(w);
		w.Write(Slots);
		w.Write(Captured);
		if (full)
		{
			AutomationData.WriteBytes(w, Before);
			AutomationData.WriteBytes(w, Pending);
			w.Write(Makers != null);
			if (Makers != null)
			{
				AutomationOrigin.Strings(w, Makers);
			}
		}
	}

	internal static AutomationJob Read(BinaryReader r, bool full, int version)
	{
		AutomationJob automationJob = new AutomationJob();
		automationJob.Id = r.ReadString();
		automationJob.Owner = r.ReadString();
		automationJob.Source = AutomationAnchor.Read(r);
		automationJob.Target = AutomationAnchor.Read(r);
		automationJob.Slots = r.ReadInt32();
		automationJob.Captured = r.ReadBoolean();
		AutomationJob automationJob2 = automationJob;
		if (full)
		{
			automationJob2.Before = AutomationData.ReadBytes(r);
			automationJob2.Pending = AutomationData.ReadBytes(r);
			if (version >= 4 && r.ReadBoolean())
			{
				automationJob2.Makers = AutomationOrigin.Strings(r, 4096).ToArray();
			}
		}
		return automationJob2;
	}
}
internal sealed class AutomationData
{
	internal const string ProgressKey = "ShimaQoL.AutomationChest.v1";

	internal const int MaxLinks = 128;

	internal const int MaxJobs = 128;

	internal const int MaxBlob = 4194304;

	internal const int MaxCompletedEntries = 4096;

	internal const int MaxCollectionEntries = 32;

	internal string World = Guid.NewGuid().ToString("N");

	internal readonly List<AutomationLink> Links = new List<AutomationLink>();

	internal readonly List<AutomationJob> Jobs = new List<AutomationJob>();

	internal readonly List<AutomationOrigin> Origins = new List<AutomationOrigin>();

	internal AutomationOrigin Origin(AutomationAnchor source)
	{
		AutomationOrigin automationOrigin = Origins.Find((AutomationOrigin o) => o.Source.Equals(source));
		if (automationOrigin == null)
		{
			if (Origins.Count >= 128)
			{
				Origins.RemoveAt(0);
			}
			AutomationOrigin automationOrigin2 = new AutomationOrigin();
			automationOrigin2.Source = source;
			automationOrigin = automationOrigin2;
			Origins.Add(automationOrigin);
		}
		return automationOrigin;
	}

	internal AutomationLink Link(AutomationAnchor source)
	{
		return Links.Find((AutomationLink l) => l.Source.Equals(source));
	}

	internal AutomationJob Job(string id)
	{
		return Jobs.Find((AutomationJob j) => j.Id == id);
	}

	internal AutomationJob Job(AutomationAnchor source)
	{
		return Jobs.Find((AutomationJob j) => j.Source.Equals(source));
	}

	internal bool HasPending(AutomationAnchor a)
	{
		return Jobs.Exists((AutomationJob j) => j.Source.Equals(a) || j.Target.Equals(a));
	}

	internal byte[] Encode(bool full)
	{
		using MemoryStream memoryStream = new MemoryStream();
		using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8);
		binaryWriter.Write(4);
		binaryWriter.Write(World);
		binaryWriter.Write(Links.Count);
		foreach (AutomationLink link in Links)
		{
			link.Write(binaryWriter);
		}
		binaryWriter.Write(Jobs.Count);
		foreach (AutomationJob job in Jobs)
		{
			job.Write(binaryWriter, full);
		}
		long position = memoryStream.Position;
		binaryWriter.Write(0);
		int num = 0;
		if (memoryStream.Length > 4194304)
		{
			throw new InvalidDataException("Automation data is too large.");
		}
		if (full)
		{
			foreach (AutomationOrigin origin in Origins)
			{
				using MemoryStream memoryStream2 = new MemoryStream();
				using BinaryWriter w = new BinaryWriter(memoryStream2, Encoding.UTF8);
				origin.Write(w);
				if (memoryStream.Length + memoryStream2.Length <= 4194304)
				{
					binaryWriter.Write(memoryStream2.ToArray());
					num++;
				}
			}
		}
		long position2 = memoryStream.Position;
		memoryStream.Position = position;
		binaryWriter.Write(num);
		memoryStream.Position = position2;
		return memoryStream.ToArray();
	}

	internal static AutomationData Decode(byte[] bytes, bool full)
	{
		if (bytes == null || bytes.Length > 4194304)
		{
			throw new InvalidDataException("Automation data is too large.");
		}
		using MemoryStream memoryStream = new MemoryStream(bytes);
		using BinaryReader binaryReader = new BinaryReader(memoryStream, Encoding.UTF8);
		int num = binaryReader.ReadInt32();
		if (num < 1 || num > 4)
		{
			throw new InvalidDataException("Unsupported automation data version.");
		}
		AutomationData automationData = new AutomationData();
		automationData.World = binaryReader.ReadString();
		AutomationData automationData2 = automationData;
		int num2 = Count(binaryReader, 128);
		for (int i = 0; i < num2; i++)
		{
			AutomationLink automationLink = AutomationLink.Read(binaryReader, num);
			if (automationLink.Slots < 1 || automationLink.Slots > 512 || automationData2.Link(automationLink.Source) != null)
			{
				throw new InvalidDataException("Invalid storage link.");
			}
			automationData2.Links.Add(automationLink);
		}
		num2 = Count(binaryReader, 128);
		for (int j = 0; j < num2; j++)
		{
			AutomationJob automationJob = AutomationJob.Read(binaryReader, full, num);
			if (automationData2.Job(automationJob.Id) != null || automationJob.Slots < 1 || automationJob.Slots > 512)
			{
				throw new InvalidDataException("Invalid automation job.");
			}
			automationData2.Jobs.Add(automationJob);
		}
		if (num >= 4)
		{
			num2 = Count(binaryReader, 128);
			while (num2-- > 0)
			{
				automationData2.Origins.Add(AutomationOrigin.Read(binaryReader));
			}
		}
		if (memoryStream.Position != memoryStream.Length)
		{
			throw new InvalidDataException("Unexpected automation data.");
		}
		return automationData2;
	}

	private static int Count(BinaryReader r, int limit)
	{
		int num = r.ReadInt32();
		if (num < 0 || num > limit)
		{
			throw new InvalidDataException("Too many automation entries.");
		}
		return num;
	}

	internal static void WriteBytes(BinaryWriter w, byte[] data)
	{
		data = data ?? new byte[0];
		w.Write(data.Length);
		w.Write(data);
	}

	internal static byte[] ReadBytes(BinaryReader r)
	{
		int num = Count(r, 4194304);
		byte[] array = r.ReadBytes(num);
		if (array.Length != num)
		{
			throw new EndOfStreamException();
		}
		return array;
	}
}
[DefaultExecutionOrder(-9500)]
public sealed class AutomationRuntime : MonoBehaviour
{
	private sealed class Operation
	{
		internal string Token;

		internal string Job;

		internal int Actor;

		internal AutomationPacket Request;

		internal readonly HashSet<int> Waiting = new HashSet<int>();

		internal byte[] Before;

		internal byte[] SavedBefore;

		internal byte[] StorageSnapshot;

		internal byte[] SourceBefore;

		internal byte[] SourceSnapshot;

		internal bool Background;

		internal bool StorageLive;

		internal int SourceActor = int.MaxValue;

		internal bool Granted;

		internal float Expires;
	}

	private sealed class TransferFeedback
	{
		internal AutomationPacket Packet;

		internal float Until;
	}

	private const string ExternalRecovery = "ShimaQoL.Automation.ExternalCollection.v1";

	private bool _pendingFirst = true;

	private int _pendingCursor;

	private readonly Dictionary<string, float> _deliveryRetry = new Dictionary<string, float>();

	private readonly Dictionary<string, string> _deliveryStatus = new Dictionary<string, string>();

	private SettingsState _settings;

	private Func<bool> _blocked;

	private Action<Exception> _report;

	private Action<string> _trace;

	private AutomationWire _wire;

	private AutomationCollection _collection;

	private AutomationNotifications _notifications;

	private MouseActionInput _mouse;

	private AutomationData _data = new AutomationData();

	private AutomationData _view = new AutomationData();

	private WorldData _world;

	private Operation _active;

	private readonly Dictionary<string, AutomationPacket> _locks = new Dictionary<string, AutomationPacket>();

	private readonly Dictionary<string, float> _lockUntil = new Dictionary<string, float>();

	private readonly Dictionary<AutomationAnchor, string> _status = new Dictionary<AutomationAnchor, string>();

	private readonly Dictionary<AutomationAnchor, float> _preparationRetry = new Dictionary<AutomationAnchor, float>();

	private readonly Dictionary<string, AutomationCollection.Run> _runs = new Dictionary<string, AutomationCollection.Run>();

	private readonly List<TransferFeedback> _feedback = new List<TransferFeedback>();

	private readonly HashSet<string> _feedbackSeen = new HashSet<string>();

	private readonly Queue<string> _feedbackOrder = new Queue<string>();

	private CraftingTable _selected;

	private CharacterData _selectionCharacter;

	private string _bindId;

	private float _bindUntil;

	private bool _cancelMouse;

	private Decoration _hover;

	private string _message;

	private float _messageUntil;

	private float _nextWork;

	private float _nextView;

	private float _requestUntil;

	private float _nextHover;

	private bool _failed;

	private bool _disposed;

	private bool _show;

	private bool _loaded;

	private string _epoch;

	private bool? _publishedReady;

	private bool? _publishedHostOnlyLinks;

	private bool? _hostOnlyLinks;

	internal static AutomationRuntime Instance;

	private static readonly Harmony Hooks = new Harmony("local.sakur.sunhaven.shimaqol.automation.guards");

	private AutomationQueueHooks _queueHooks;

	private readonly HashSet<string> _originSeen = new HashSet<string>();

	private readonly Queue<string> _originOrder = new Queue<string>();

	internal string Title { get; private set; }

	internal string Details { get; private set; }

	internal bool HasOverlay => _show;

	internal bool HasInteractionOverlay
	{
		get
		{
			if (!((Object)(object)_selected != (Object)null))
			{
				return Time.unscaledTime < _messageUntil;
			}
			return true;
		}
	}

	internal bool CancellingMouse => _cancelMouse;

	private AutomationNative.Destination Destination(AutomationLink link, byte[] before)
	{
		Decoration obj = AutomationNative.Live(link.Target);
		Chest val = (Chest)(object)((obj is Chest) ? obj : null);
		if (!((Object)(object)val != (Object)null))
		{
			return AutomationNative.Placement(link.Rules, before, link.Slots);
		}
		return AutomationNative.Placement(val, before, link.Slots);
	}

	private string SelectOutput(AutomationLink link, CraftingTableData craft, byte[] before, bool allowPlaceables)
	{
		AutomationNative.Destination destination = Destination(link, before);
		string result = _collection.Selection(craft.completeItems, allowPlaceables, destination.Add);
		if (_collection.SelectionNotice == null)
		{
			_status.Remove(link.Source);
		}
		else
		{
			_status[link.Source] = _collection.SelectionNotice;
		}
		return result;
	}

	private static bool Collecting(AutomationData data, AutomationAnchor source)
	{
		return data.Jobs.Exists((AutomationJob job) => job.Source.Equals(source) && !job.Captured);
	}

	private bool CanStartOutput(AutomationAnchor source)
	{
		foreach (AutomationJob job in _view.Jobs)
		{
			if (job.Source.Equals(source) && (!job.Captured || !_deliveryStatus.ContainsKey(job.Id)))
			{
				return false;
			}
		}
		return true;
	}

	private void WaitDelivery(AutomationJob job, string message)
	{
		_deliveryRetry[job.Id] = Time.unscaledTime + 3f;
		_deliveryStatus[job.Id] = message;
	}

	private string WaitingStatus(AutomationLink link)
	{
		_status.TryGetValue(link.Source, out var value);
		foreach (AutomationJob job in _view.Jobs)
		{
			if (job.Source.Equals(link.Source) && _deliveryStatus.TryGetValue(job.Id, out var value2))
			{
				return (string.IsNullOrEmpty(value) || value2 == value) ? value2 : (value2 + "\n" + value);
			}
		}
		return value;
	}

	private bool WorkPending()
	{
		int count = _view.Jobs.Count;
		for (int i = 0; i < count; i++)
		{
			int num = (_pendingCursor + i) % count;
			AutomationJob automationJob = _view.Jobs[num];
			if (automationJob.Owner != _wire.Owner)
			{
				continue;
			}
			AutomationLink automationLink = _view.Link(automationJob.Source);
			if (automationLink != null && (!automationJob.Captured || !_deliveryRetry.TryGetValue(automationJob.Id, out var value) || !(Time.unscaledTime < value)))
			{
				try
				{
					StorageSnapshot(automationLink);
					_pendingCursor = (num + 1) % count;
					Request(new AutomationPacket
					{
						Kind = 5,
						Id = automationJob.Id,
						Source = automationJob.Source,
						Target = automationJob.Target
					});
					return true;
				}
				catch (AutomationWaitException ex)
				{
					WaitDelivery(automationJob, ex.Message);
				}
				catch (Exception error)
				{
					WaitDelivery(automationJob, "Currently unsupported transfer — saved output kept safely.");
					PreparationFailed(automationJob.Source, error);
				}
			}
		}
		return false;
	}

	private void PruneFallback()
	{
		foreach (string item in new List<string>(_deliveryRetry.Keys))
		{
			if (_view.Job(item) == null)
			{
				_deliveryRetry.Remove(item);
				_deliveryStatus.Remove(item);
			}
		}
		foreach (string item2 in new List<string>(_deliveryStatus.Keys))
		{
			if (_view.Job(item2) == null)
			{
				_deliveryStatus.Remove(item2);
			}
		}
	}

	internal void Initialize(SettingsState settings, Func<bool> blocked, Action<Exception> report, Action<string> trace = null)
	{
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Expected O, but got Unknown
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Expected O, but got Unknown
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Expected O, but got Unknown
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Expected O, but got Unknown
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Expected O, but got Unknown
		_settings = settings;
		_blocked = blocked;
		_report = report;
		_trace = trace;
		Instance = this;
		try
		{
			_collection = new AutomationCollection(delegate(IEnumerator routine)
			{
				((MonoBehaviour)this).StartCoroutine(routine);
			}, Trace);
			_wire = new AutomationWire(Server, Client, Error);
			_notifications = new AutomationNotifications(Trace);
			try
			{
				_queueHooks = new AutomationQueueHooks(QueuedCraft, QueueSnapshot);
			}
			catch (Exception ex)
			{
				Trace("Craft notification tracking unavailable: " + ex.Message);
			}
			_mouse = new MouseActionInput(() => CanUse() && ((((Object)(object)_selected != (Object)null || _cancelMouse) && HotkeyInput.MouseHeldOrReleased(324)) || (_settings.AutomationEnabled && HotkeyInput.MouseHeldOrReleased(_settings.KeyFor(HotkeyAction.AutomationLink))) || HotkeyInput.MouseHeldOrReleased(_settings.KeyFor(HotkeyAction.AutomationUnlink))));
			Hooks.Patch((MethodBase)AutomationMethods.StationInteract, new HarmonyMethod(typeof(AutomationRuntime), "GuardStation", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StorageInteract, new HarmonyMethod(typeof(AutomationRuntime), "GuardChest", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StationBreakable, (HarmonyMethod)null, new HarmonyMethod(typeof(AutomationRuntime), "GuardBreak", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.StorageBreakable, (HarmonyMethod)null, new HarmonyMethod(typeof(AutomationRuntime), "GuardBreak", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Hooks.Patch((MethodBase)AutomationMethods.DeleteDecoration, new HarmonyMethod(typeof(AutomationRuntime), "GuardDelete", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception error)
		{
			Error(error);
		}
	}

	private bool CanUse()
	{
		if (!_disposed && !_failed && ((Behaviour)this).isActiveAndEnabled && _settings != null && !_blocked())
		{
			return GameplayGate.CanControl(Player.Instance);
		}
		return false;
	}

	private bool CanCollect()
	{
		if (!CanUse())
		{
			if (!_disposed && !_failed && ((Behaviour)this).isActiveAndEnabled && _settings != null && !_blocked())
			{
				return BedRuntime.CanCollectWhileResting;
			}
			return false;
		}
		return true;
	}

	private static bool GuardStation(CraftingTable __instance)
	{
		if (!((Object)(object)Instance == (Object)null))
		{
			return !Instance.Locked(AutomationNative.Anchor((Decoration)(object)__instance));
		}
		return true;
	}

	private static bool GuardChest(Chest __instance)
	{
		if (!((Object)(object)Instance == (Object)null))
		{
			return !Instance.Locked(AutomationNative.Anchor((Decoration)(object)__instance));
		}
		return true;
	}

	internal static bool StorageInUse(AutomationAnchor a)
	{
		AutomationRuntime instance = Instance;
		if ((Object)(object)instance == (Object)null || !instance._loaded || instance._failed)
		{
			return true;
		}
		if (!instance.Locked(a) && !instance._view.HasPending(a))
		{
			return instance._view.Links.Exists((AutomationLink l) => l.Target.Equals(a) || l.Source.Equals(a));
		}
		return true;
	}

	private static void GuardBreak(Decoration __instance, ref bool __result)
	{
		if ((Object)(object)Instance != (Object)null && (Instance.Locked(AutomationNative.Anchor(__instance)) || Instance._view.HasPending(AutomationNative.Anchor(__instance))))
		{
			__result = false;
		}
	}

	private bool Locked(AutomationAnchor a)
	{
		foreach (AutomationPacket value in _locks.Values)
		{
			AutomationAnchor source = value.Source;
			if (!source.Equals(a))
			{
				AutomationAnchor target = value.Target;
				if (!target.Equals(a))
				{
					continue;
				}
			}
			return true;
		}
		return false;
	}

	private static bool GuardDelete(Vector3Int __0, Vector2Int __1, int __2)
	{
		//IL_000e: 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_0016: 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)
		AutomationRuntime runtime = Instance;
		if ((Object)(object)runtime == (Object)null || runtime._wire == null || !runtime._loaded || runtime._failed)
		{
			return true;
		}
		Predicate<AutomationAnchor> hit = (AutomationAnchor a) => a.Scene == __2 && a.X >= ((Vector3Int)(ref __0)).x && a.X < ((Vector3Int)(ref __0)).x + ((Vector2Int)(ref __1)).x && a.Y >= ((Vector3Int)(ref __0)).y && a.Y < ((Vector3Int)(ref __0)).y + ((Vector2Int)(ref __1)).y;
		foreach (AutomationJob job in runtime._view.Jobs)
		{
			if (hit(job.Source) || hit(job.Target))
			{
				runtime.Tell("Collected output is waiting. Deliver or relink it before removing this object.");
				return false;
			}
		}
		foreach (AutomationPacket value in runtime._locks.Values)
		{
			if (hit(value.Source) || hit(value.Target))
			{
				return false;
			}
		}
		if (runtime._wire.IsHost)
		{
			int num = runtime._data.Links.RemoveAll((AutomationLink l) => hit(l.Source) || hit(l.Target));
			runtime._data.Origins.RemoveAll((AutomationOrigin o) => hit(o.Source) || runtime._data.Link(o.Source) == null);
			if (num > 0)
			{
				runtime.Save();
				runtime.Publish();
			}
		}
		return true;
	}

	private void Update()
	{
		if (_disposed || _wire == null)
		{
			return;
		}
		try
		{
			GameSave instance = SingletonBehaviour<GameSave>.Instance;
			Player instance2 = Player.Instance;
			if ((Object)(object)instance == (Object)null || instance.CurrentWorld == null || GameSave.CurrentCharacter == null || (Object)(object)instance2 == (Object)null || instance2.IsMainMenuPlayer || !instance2.IsOwner)
			{
				Suspend();
				_feedback.Clear();
				return;
			}
			if (!object.ReferenceEquals(_world, instance.CurrentWorld))
			{
				_world = instance.CurrentWorld;
				_loaded = false;
				Suspend();
				ClearFeedback();
				_originSeen.Clear();
				_originOrder.Clear();
				_locks.Clear();
				_lockUntil.Clear();
				_status.Clear();
				_preparationRetry.Clear();
				_deliveryRetry.Clear();
				_deliveryStatus.Clear();
				_active = null;
				_requestUntil = 0f;
				_publishedReady = null;
				_publishedHostOnlyLinks = null;
				_hostOnlyLinks = null;
				string text = instance.GetProgressStringCharacter("ShimaQoL.Automation.Owner");
				if (string.IsNullOrEmpty(text))
				{
					text = Guid.NewGuid().ToString("N");
					instance.SetProgressStringCharacter("ShimaQoL.Automation.Owner", text);
				}
				_wire.Owner = text;
				string progressStringWorld = instance.GetProgressStringWorld("ShimaQoL.AutomationChest.v1");
				_data = (string.IsNullOrEmpty(progressStringWorld) ? new AutomationData() : AutomationData.Decode(Convert.FromBase64String(progressStringWorld), full: true));
				_view = new AutomationData();
				_loaded = true;
			}
			if (!_loaded)
			{
				return;
			}
			_wire.Tick(instance);
			ShowFeedback();
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, float> item in _lockUntil)
			{
				if (Time.unscaledTime > item.Value)
				{
					list.Add(item.Key);
				}
			}
			foreach (string item2 in list)
			{
				_locks.Remove(item2);
				_lockUntil.Remove(item2);
			}
			if (_wire.IsHost)
			{
				if (_active != null && (Time.unscaledTime > _active.Expires || !_wire.AllReady))
				{
					Release();
				}
				if (Time.unscaledTime >= _nextView)
				{
					_nextView = Time.unscaledTime + 1f;
					Publish(force: false);
					if (!_failed)
					{
						PruneLinks();
					}
				}
			}
			_cancelMouse = _cancelMouse && HotkeyInput.MouseHeldOrReleased(324);
			if (!_settings.AutomationEnabled || (_selectionCharacter != null && (!object.ReferenceEquals(_selectionCharacter, GameSave.CurrentCharacter) || (Object)(object)_selected == (Object)null || !ObjectPicker.IsUsable((Decoration)(object)_selected) || AutomationNative.Saved(AutomationNative.Anchor((Decoration)(object)_selected)) == null)))
			{
				ClearSelection();
			}
			if (!CanUse())
			{
				_show = false;
				_hover = null;
				_nextHover = 0f;
				if (CanCollect() && Time.unscaledTime >= _nextWork && Time.unscaledTime >= _requestUntil && _wire.Ready)
				{
					_nextWork = Time.unscaledTime + 0.75f;
					Work();
				}
				return;
			}
			if (_bindId != null && Time.unscaledTime > _bindUntil)
			{
				_bindId = null;
				Tell("Link confirmation timed out. Try again.", notify: true);
			}
			bool flag = Input.GetKeyDown((KeyCode)27) && (Object)(object)_selected != (Object)null && _bindId == null;
			bool flag2 = _settings.AutomationEnabled && HotkeyInput.Pressed(_settings.KeyFor(HotkeyAction.AutomationLink));
			bool flag3 = HotkeyInput.Pressed(_settings.KeyFor(HotkeyAction.AutomationUnlink));
			bool flag4 = HotkeyInput.Pressed(324);
			if (flag2 || flag3 || (Object)(object)_selected != (Object)null || _view.Links.Count > 0 || Time.unscaledTime < _messageUntil)
			{
				if (flag2 || flag3 || flag4 || Time.unscaledTime >= _nextHover)
				{
					_hover = null;
					_nextHover = Time.unscaledTime + 0.08f;
					ObjectReader.UpdateTargets();
					GameManager instance3 = SingletonBehaviour<GameManager>.Instance;
					if ((Object)(object)instance3 != (Object)null && (Object)(object)instance2.Camera != (Object)null)
					{
						ScreenHover.BeginRead(instance2.Camera);
						if (!NpcReader.TryRead(instance2.Camera, out var _))
						{
							_hover = ObjectPicker.Find(instance3, instance2.Camera);
						}
					}
				}
				else if ((Object)(object)_hover != (Object)null && !ObjectPicker.IsUsable(_hover))
				{
					_hover = null;
				}
			}
			else
			{
				_hover = null;
				_nextHover = 0f;
			}
			if (flag4 && (Object)(object)_selected != (Object)null && _bindId == null && (!flag2 || !UsableStorage((Chest)/*isinst with value type is only supported in some contexts*/)))
			{
				flag = true;
				_cancelMouse = true;
			}
			if (flag)
			{
				ClearSelection();
				Tell("Linking cancelled.", notify: true);
			}
			else if (flag2)
			{
				LinkHover();
			}
			else if (flag3)
			{
				UnlinkHover();
			}
			else if ((Object)(object)_selected == (Object)null && _bindId == null && flag4 && _hover is CraftingTable && _view.Link(AutomationNative.Anchor(_hover)) != null)
			{
				_cancelMouse = true;
				ToggleMode();
			}
			if (Time.unscaledTime >= _nextWork && Time.unscaledTime >= _requestUntil && _wire.Ready && !_failed)
			{
				_nextWork = Time.unscaledTime + 0.75f;
				Work();
			}
			Overlay();
		}
		catch (Exception error)
		{
			Error(error);
		}
	}

	private void Tell(string text, bool notify = false, int item = 0, Chest appearance = null)
	{
		_message = text;
		_messageUntil = Time.unscaledTime + 4f;
		_requestUntil = 0f;
		if (!notify)
		{
			return;
		}
		try
		{
			NotificationStack instance = SingletonBehaviour<NotificationStack>.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				_notifications.Send(instance, "Automation: " + text, item, appearance);
			}
		}
		catch
		{
		}
	}

	private void Error(Exception error)
	{
		bool flag = !_failed;
		_failed = true;
		ClearSelection();
		_show = false;
		if (_wire != null)
		{
			_wire.Healthy = false;
		}
		if (flag && _report != null)
		{
			_report(error);
		}
	}

	private void Trace(string message)
	{
		try
		{
			if (_trace != null)
			{
				_trace(message);
			}
		}
		catch
		{
		}
	}

	private void LinkHover()
	{
		if (!_wire.IsHost && _hostOnlyLinks == true)
		{
			ClearSelection();
			Tell("Host can only Link Automation.", notify: true);
		}
		else if (!_wire.Ready)
		{
			Tell("Waiting for the same Shima QoL on every player.", notify: true);
		}
		else if (!_wire.IsHost && !_hostOnlyLinks.HasValue)
		{
			ClearSelection();
			Tell("Waiting for host link permission.", notify: true);
		}
		else
		{
			if (_bindId != null)
			{
				return;
			}
			if ((Object)(object)_selected == (Object)null)
			{
				Decoration hover = _hover;
				CraftingTable val = (CraftingTable)(object)((hover is CraftingTable) ? hover : null);
				if ((Object)(object)val == (Object)null || !((Decoration)val).Placed || ((Decoration)val).IsPrePlaced || AutomationNative.Saved(AutomationNative.Anchor((Decoration)(object)val)) == null)
				{
					Tell("Hover a placed crafting/cooking station first.", notify: true);
					return;
				}
				_selected = val;
				_selectionCharacter = GameSave.CurrentCharacter;
				Tell("Station selected: " + ObjectNames.Get((Decoration)(object)val), notify: true, ((Decoration)val).id);
				return;
			}
			if (!ObjectPicker.IsUsable((Decoration)(object)_selected))
			{
				ClearSelection();
				Tell("Station unavailable. Select it again.", notify: true);
				return;
			}
			Decoration hover2 = _hover;
			Chest val2 = (Chest)(object)((hover2 is Chest) ? hover2 : null);
			if (!UsableStorage(val2))
			{
				Tell("Hover a placed chest, closet or fridge.", notify: true);
				return;
			}
			_bindId = Guid.NewGuid().ToString("N");
			_bindUntil = Time.unscaledTime + 5f;
			_wire.Request(new AutomationPacket
			{
				Kind = 3,
				Id = _bindId,
				World = _view.World,
				Source = AutomationNative.Anchor((Decoration)(object)_selected),
				Target = AutomationNative.Anchor((Decoration)(object)val2),
				Name = ObjectNames.Get((Decoration)(object)val2),
				Slots = Math.Min(val2.sellingInventory.maxSlots, val2.sellingInventory.Items.Count),
				Data = AutomationSlots.Capture(val2, Math.Min(val2.sellingInventory.maxSlots, val2.sellingInventory.Items.Count))
			});
		}
	}

	private static bool UsableStorage(Chest chest)
	{
		if (AutomationNative.Supported(chest) && ((Decoration)chest).Placed && !((Decoration)chest).IsPrePlaced && (Object)(object)chest.sellingInventory != (Object)null)
		{
			return AutomationNative.Saved(AutomationNative.Anchor((Decoration)(object)chest)) != null;
		}
		return false;
	}

	private void UnlinkHover()
	{
		if (!_wire.Ready)
		{
			Tell("Waiting for the same Shima QoL on every player.", notify: true);
			return;
		}
		if (!(_hover is CraftingTable))
		{
			Tell("Hover a linked station to unlink it.", notify: true);
			return;
		}
		_wire.Request(new AutomationPacket
		{
			Kind = 4,
			World = _view.World,
			Source = AutomationNative.Anchor(_hover)
		});
	}

	private void ToggleMode()
	{
		if (!_wire.Ready)
		{
			Tell("Waiting for the same Shima QoL on every player.", notify: true);
			return;
		}
		AutomationAnchor source = AutomationNative.Anchor(_hover);
		AutomationLink automationLink = _view.Link(source);
		if (automationLink != null)
		{
			_wire.Request(new AutomationPacket
			{
				Kind = 16,
				World = _view.World,
				Source = source,
				Flag = !automationLink.Manual
			});
		}
	}

	private static string LinkId(AutomationAnchor a)
	{
		return a.Scene + ":" + a.X + ":" + a.Y + ":" + a.Z + ":" + a.Item;
	}

	private bool CanManage(bool inspectFailed = false)
	{
		GameSave instance = SingletonBehaviour<GameSave>.Instance;
		Player instance2 = Player.Instance;
		if (!_disposed && (!_failed || inspectFailed) && _loaded && _wire != null && (Object)(object)instance != (Object)null && object.ReferenceEquals(_world, instance.CurrentWorld) && GameSave.CurrentCharacter != null && (Object)(object)instance2 != (Object)null && instance2.IsOwner)
		{
			return !instance2.IsMainMenuPlayer;
		}
		return false;
	}

	internal AutomationPermission GetLinkPermission()
	{
		bool flag = _wire != null && _wire.IsHost;
		AutomationPermission automationPermission = new AutomationPermission();
		automationPermission.CanEdit = flag;
		automationPermission.Known = flag || (CanManage(inspectFailed: true) && _hostOnlyLinks.HasValue);
		automationPermission.HostOnly = (flag ? _settings.AutomationHostOnlyLinks : (_hostOnlyLinks == true));
		return automationPermission;
	}

	internal AutomationLinkRow[] GetLinks()
	{
		if (!CanManage(inspectFailed: true))
		{
			return null;
		}
		List<AutomationLinkRow> list = new List<AutomationLinkRow>();
		foreach (AutomationLink link in _view.Links)
		{
			Decoration val = AutomationNative.Live(link.Source);
			Decoration val2 = AutomationNative.Live(link.Target);
			AutomationJob automationJob = _view.Job(link.Source);
			string text = (_failed ? "Automation unavailable this session" : ((link.Owner != _wire.Owner) ? "Managed by linking player" : ((automationJob != null) ? (Collecting(_view, link.Source) ? "Collection pending / recovery" : "Output waiting; deliver or relink first") : (Locked(link.Source) ? "Transfer in progress" : ((!_wire.Ready) ? "Waiting for compatible players" : null)))));
			string text2 = WaitingStatus(link);
			list.Add(new AutomationLinkRow
			{
				Id = LinkId(link.Source),
				Station = (((Object)(object)val != (Object)null) ? ObjectNames.Get(val) : ObjectNames.ItemLabel(link.Source.Item)),
				Storage = (((Object)(object)val2 != (Object)null) ? ObjectNames.Get(val2) : link.TargetName),
				Details = (link.Manual ? "Manual" : "Auto") + " | Area " + link.Source.Scene + " (" + link.Source.X + ", " + link.Source.Y + ")" + ((text == null) ? ((text2 == null) ? "" : (" | " + text2)) : (" | " + text + ((text2 == null) ? "" : (" | " + text2)))),
				CanUnlink = (text == null)
			});
		}
		list.Sort(delegate(AutomationLinkRow a, AutomationLinkRow b)
		{
			int num = string.Compare(a.Station, b.Station, StringComparison.CurrentCulture);
			return (num == 0) ? string.CompareOrdinal(a.Id, b.Id) : num;
		});
		return list.ToArray();
	}

	internal void UnlinkFromMenu(string id)
	{
		if (!CanManage())
		{
			return;
		}
		foreach (AutomationLink link in _view.Links)
		{
			if (LinkId(link.Source) == id)
			{
				_wire.Request(new AutomationPacket
				{
					Kind = 4,
					World = _view.World,
					Source = link.Source
				});
				break;
			}
		}
	}

	private byte[] StorageSnapshot(AutomationLink link)
	{
		Decoration obj = AutomationNative.Live(link.Target);
		Chest val = (Chest)(object)((obj is Chest) ? obj : null);
		if ((Object)(object)val != (Object)null)
		{
			return AutomationNative.StorageSnapshot(val);
		}
		if (link.Target.Scene == ScenePortalManager.ActiveSceneIndex)
		{
			throw new AutomationWaitException("Waiting for storage to load.");
		}
		AutomationSlots.Read(link.Rules, link.Slots);
		DecorationPositionData val2 = AutomationNative.Saved(link.Target);
		if (val2 == null || val2.meta == null)
		{
			throw new AutomationWaitException("Storage unavailable.");
		}
		ChestData val3 = AutomationNative.ChestBytes(val2.meta);
		if (val3 == null || val3.inUse)
		{
			throw new AutomationWaitException("Storage is in use or synchronizing.");
		}
		return (byte[])val2.meta.Clone();
	}

	private byte[] Plan(AutomationLink link, byte[] before, IList<ItemAmount> items)
	{
		Decoration obj = AutomationNative.Live(link.Target);
		Chest val = (Chest)(object)((obj is Chest) ? obj : null);
		if (!((Object)(object)val != (Object)null))
		{
			return AutomationNative.Plan(link.Rules, before, items, link.Slots);
		}
		return AutomationNative.Plan(val, before, items, link.Slots);
	}

	private CraftingTableData Output(AutomationLink link)
	{
		Decoration obj = AutomationNative.Live(link.Source);
		CraftingTable val = (CraftingTable)(object)((obj is CraftingTable) ? obj : null);
		if ((Object)(object)val != (Object)null)
		{
			if (AutomationNative.IsOpening(val))
			{
				throw new AutomationWaitException("Station is in use.");
			}
			return AutomationNative.Crafting(val);
		}
		if (link.Source.Scene == ScenePortalManager.ActiveSceneIndex)
		{
			throw new AutomationWaitException("Waiting for station to load.");
		}
		AutomationSlots.Read(link.Rules, link.Slots);
		DecorationPositionData val2 = AutomationNative.Saved(link.Source);
		if (val2 == null || val2.meta == null)
		{
			throw new AutomationWaitException("Station unavailable.");
		}
		return AutomationNative.Advance(val2.meta, AutomationNative.CraftClock());
	}

	private void Work()
	{
		if (_locks.Count != 0)
		{
			return;
		}
		foreach (AutomationLink link in _view.Links)
		{
			if (!(link.Owner == _wire.Owner) || link.Target.Scene != ScenePortalManager.ActiveSceneIndex)
			{
				continue;
			}
			try
			{
				Decoration obj = AutomationNative.Live(link.Target);
				Chest val = (Chest)(object)((obj is Chest) ? obj : null);
				if (!((Object)(object)val == (Object)null) && AutomationNative.Storage(val) != null && !AutomationNative.Storage(val).inUse)
				{
					byte[] array = AutomationSlots.Capture(val, link.Slots);
					if (!AutomationNative.Equal(array, link.Rules))
					{
						_wire.Request(new AutomationPacket
						{
							Kind = 17,
							World = _view.World,
							Source = link.Source,
							Target = link.Target,
							Data = array
						});
						return;
					}
				}
			}
			catch (AutomationWaitException)
			{
			}
		}
		bool pendingFirst = _pendingFirst;
		_pendingFirst = !_pendingFirst;
		if (pendingFirst && WorkPending())
		{
			return;
		}
		if (!_settings.AutomationEnabled)
		{
			if (!pendingFirst)
			{
				WorkPending();
			}
			return;
		}
		foreach (AutomationLink link2 in _view.Links)
		{
			if (link2.Manual || !(link2.Owner == _wire.Owner) || !CanStartOutput(link2.Source) || (_preparationRetry.TryGetValue(link2.Source, out var value) && Time.unscaledTime < value))
			{
				continue;
			}
			AutomationPacket? automationPacket = null;
			try
			{
				CraftingTableData val2 = Output(link2);
				if (val2 == null || val2.completeItems == null)
				{
					continue;
				}
				if (val2.completeItems.Count == 0)
				{
					_status.Remove(link2.Source);
					_preparationRetry.Remove(link2.Source);
					continue;
				}
				if (val2.completeItems.Count > 4096)
				{
					_status[link2.Source] = "Completed backlog exceeds the automation safety limit. Collect some output manually.";
					continue;
				}
				byte[] array2 = StorageSnapshot(link2);
				string text = SelectOutput(link2, val2, array2, _settings.AutomationAllowStations);
				if (text.Length == 0)
				{
					_preparationRetry.Remove(link2.Source);
					continue;
				}
				CraftingTableData remaining;
				CraftingTableData val3 = AutomationNative.Select(val2, text, out remaining);
				byte[] data = AutomationNative.CraftBytes(val2);
				byte[] a = Plan(link2, array2, val3.completeItems);
				if (AutomationNative.Equal(a, array2))
				{
					_status[link2.Source] = "Storage full or item not accepted — output waiting";
					continue;
				}
				_preparationRetry.Remove(link2.Source);
				AutomationPacket value2 = new AutomationPacket
				{
					Kind = 5,
					World = _view.World,
					Source = link2.Source,
					Target = link2.Target,
					Data = data,
					Extra = array2
				};
				value2.Encode();
				automationPacket = value2;
				goto IL_03a0;
			}
			catch (AutomationWaitException ex2)
			{
				_status[link2.Source] = ex2.Message;
				goto IL_03a0;
			}
			catch (Exception error)
			{
				PreparationFailed(link2.Source, error);
				goto IL_03a0;
			}
			IL_03a0:
			if (automationPacket.HasValue)
			{
				Request(automationPacket.Value);
				return;
			}
		}
		if (!pendingFirst)
		{
			WorkPending();
		}
	}

	private void PreparationFailed(AutomationAnchor source, Exception error)
	{
		string text = "Currently unsupported transfer — output kept safely. Other stations can continue.";
		if (!_status.TryGetValue(source, out var value) || value != text)
		{
			Trace("Output preparation paused for station " + source.Item + " at " + LinkId(source) + ": " + error);
		}
		_status[source] = text;
		_preparationRetry[source] = Time.unscaledTime + 3f;
	}

	private void Request(AutomationPacket p)
	{
		p.World = _view.World;
		_requestUntil = Time.unscaledTime + 5f;
		_wire.Request(p);
	}

	private void Overlay()
	{
		_show = false;
		Title = "Automation Chest";
		Details = null;
		if ((Object)(object)_selected != (Object)null)
		{
			_show = true;
			Details = "Station: " + ObjectNames.Get((Decoration)(object)_selected) + ((_bindId != null) ? "\nWaiting for link confirmation." : ("\nHover storage and press " + HotkeyInput.Label(_settings.KeyFor(HotkeyAction.AutomationLink)) + ".\nRight-click or Esc to cancel."));
			return;
		}
		if (Time.unscaledTime < _messageUntil)
		{
			_show = true;
			Details = _message;
			return;
		}
		if (_hover is CraftingTable)
		{
			AutomationAnchor source = AutomationNative.Anchor(_hover);
			AutomationLink automationLink = _view.Link(source);
			if (automationLink != null)
			{
				_show = true;
				Title = ObjectNames.Get(_hover);
				Decoration obj = AutomationNative.Live(automationLink.Target);
				Chest val = (Chest)(object)((obj is Chest) ? obj : null);
				Details = "Output storage: " + (((Object)(object)val != (Object)null) ? ObjectNames.Get((Decoration)(object)val) : automationLink.TargetName) + "\nAutomation: " + LinkStatus(automationLink);
			}
			return;
		}
		Decoration hover = _hover;
		if (!AutomationNative.Supported((Chest)(object)((hover is Chest) ? hover : null)))
		{
			return;
		}
		AutomationAnchor b = AutomationNative.Anchor(_hover);
		SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>(StringComparer.CurrentCulture);
		int num = 0;
		string text = null;
		foreach (AutomationLink link in _view.Links)
		{
			if (link.Target.Equals(b))
			{
				Decoration val2 = AutomationNative.Live(link.Source);
				string text2 = (((Object)(object)val2 != (Object)null) ? ObjectNames.Get(val2) : null);
				if (string.IsNullOrWhiteSpace(text2))
				{
					text2 = ObjectNames.ItemLabel(link.Source.Item);
				}
				sortedDictionary.TryGetValue(text2, out var value);
				sortedDictionary[text2] = value + 1;
				num++;
				string text3 = LinkStatus(link);
				text = ((text == null) ? text3 : ((text == text3) ? text : "Mixed (see Automation Chest)"));
			}
		}
		if (num <= 0)
		{
			return;
		}
		List<string> list = new List<string>();
		int num2 = 0;
		foreach (KeyValuePair<string, int> item in sortedDictionary)
		{
			if (list.Count != 8)
			{
				list.Add(item.Key + ((item.Value > 1) ? (" (" + item.Value + ")") : ""));
				num2 += item.Value;
				continue;
			}
			break;
		}
		_show = true;
		Title = ObjectNames.Get(_hover);
		Details = "Linked to: " + string.Join(", ", list.ToArray()) + ((num2 < num) ? ("\n+" + (num - num2) + " more in Automation Chest") : "") + "\nAutomation: " + text;
	}

	private string LinkStatus(AutomationLink link)
	{
		AutomationJob automationJob = _view.Job(link.Source);
		Decoration obj = AutomationNative.Live(link.Target);
		Chest val = (Chest)(object)((obj is Chest) ? obj : null);
		if (link.Manual)
		{
			if (automationJob != null)
			{
				return "Manual after current transfer";
			}
			return "Manual collection (right-click for Auto)";
		}
		if ((Object)(object)val == (Object)null)
		{
			return "Storage unavailable";
		}
		if (AutomationNative.Storage(val) != null && AutomationNative.Storage(val).inUse)
		{
			return "Storage in use";
		}
		string text = ((!_wire.Ready) ? "Waiting for compatible players" : ((!_settings.AutomationEnabled) ? "Paused" : ((link.Owner != _wire.Owner) ? "Managed by linking player" : ((automationJob == null) ? "Active" : (automationJob.Captured ? "Stored output waiting for delivery" : "Collection pending — bonuses will not reroll")))));
		string text2 = WaitingStatus(link);
		return text2 ?? text;
	}

	private void Save()
	{
		SingletonBehaviour<GameSave>.Instance.SetProgressStringWorld("ShimaQoL.AutomationChest.v1", Convert.ToBase64String(_data.Encode(full: true)), false);
	}

	private AutomationPacket State()
	{
		return new AutomationPacket
		{
			Kind = 2,
			World = _data.World,
			Id = _wire.Session,
			Data = _data.Encode(full: false),
			Flag = (_wire.AllReady && !_failed),
			Slots = (_settings.AutomationHostOnlyLinks ? 1 : 0)
		};
	}

	private void Publish(bool force = true)
	{
		bool flag = _wire.AllReady && !_failed;
		bool automationHostOnlyLinks = _settings.AutomationHostOnlyLinks;
		if (!force)
		{
			bool? publishedReady = _publishedReady;
			bool flag2 = flag;
			if (publishedReady == true == flag2 && publishedReady.HasValue && _publishedHostOnlyLinks == automationHostOnlyLinks)
			{
				return;
			}
		}
		_publishedReady = flag;
		_publishedHostOnlyLinks = automationHostOnlyLinks;
		_wire.Broadcast(State());
	}

	private void Notice(int actor, string text, bool notify = false, AutomationAnchor source = default(AutomationAnchor), string request = null, int completed = 0, AutomationAnchor target = default(AutomationAnchor))
	{
		_wire.Send(actor, new AutomationPacket
		{
			Kind = 13,
			World = _data.World,
			Name = text,
			Flag = notify,
			Source = source,
			Id = request,
			Slots = completed,
			Target = target
		});
	}

	private void Apply(AutomationAnchor a, byte[] bytes)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		AutomationPacket p = new AutomationPacket
		{
			Kind = 14,
			World = _data.World,
			Source = a,
			Data = bytes
		};
		p.Encode();
		Trace("Metadata apply begin: scene " + a.Scene + ", item " + a.Item);
		SingletonBehaviour<GameManager>.Instance.UpdateDecorationMetaFromRPC(AutomationNative.Position(a), a.Scene, bytes);
		Trace("Metadata apply end: scene " + a.Scene + ", item " + a.Item);
		_wire.Broadcast(p);
	}

	private void PruneLinks()
	{
		if (_active == null)
		{
			int num = _data.Links.RemoveAll((AutomationLink l) => !_data.HasPending(l.Source) && (AutomationNative.Saved(l.Source) == null || AutomationNative.Saved(l.Target) == null));
			_data.Origins.RemoveAll((AutomationOrigin o) => _data.Link(o.Source) == null && _data.Job(o.Source) == null);
			if (num > 0)
			{
				Save();
				Publish();
			}
		}
	}

	private void Release()
	{
		if (_active != null)
		{
			string token = _active.Token;
			_active = null;
			_wire.Broadcast(new AutomationPacket
			{
				Kind = 12,
				World = _data.World,
				Id = token
			});
		}
	}

	private void Server(int actor, AutomationPacket p)
	{
		if (!_wire.IsHost || !_loaded)
		{
			return;
		}
		try
		{
			if (p.Kind == 1)
			{
				AutomationPacket p2 = State();
				if (p.World == _data.World)
				{
					p2.Data = new byte[0];
				}
				_wire.Send(actor, p2);
			}
			else
			{
				if (_failed || p.World != _data.World)
				{
					return;
				}
				string text = _wire.PeerOwner(actor);
				if (text == null)
				{
					return;
				}
				if (p.Kind == 18)
				{
					RecordOrigin(actor, text, p);
					return;
				}
				if (p.Kind == 9)
				{
					CaptureResult(actor, text, p);
					return;
				}
				if (p.Kind == 10)
				{
					Delivery(actor, text, p);
					return;
				}
				if (p.Kind == 7)
				{
					if (_active == null || _active.Token != p.Id)
					{
						return;
					}
					if (_active.Granted && actor == _active.Actor && !p.Flag)
					{
						Release();
					}
					else
					{
						if (!_active.Waiting.Contains(actor))
						{
							return;
						}
						bool flag = p.Extra != null && p.Extra.Length > 0;
						if (!p.Flag || (actor == _active.Actor && !flag))
						{
							Notice(_active.Actor, "Station or storage is busy. Automation will retry.");
							Release();
							return;
						}
						if (flag)
						{
							bool flag2 = (p.Slots & 2) != 0 && _wire.InArea(actor, _active.Request.Target.Scene);
							if (!flag2 && actor != _active.Actor)
							{
								flag = false;
							}
							if (flag && !flag2 && _active.Background && !AutomationNative.Equal(p.Extra, _active.SavedBefore))
							{
								Notice(_active.Actor, "Storage changed during background preparation. Retrying.");
								Release();
								return;
							}
							if (flag && _active.StorageSnapshot != null && _active.StorageLive && flag2 && !AutomationNative.Equal(_active.StorageSnapshot, p.Extra))
							{
								Notice(_active.Actor, "Storage is synchronizing. Automation will retry.");
								Release();
								return;
							}
							if (flag && (_active.StorageSnapshot == null || flag2 || !_active.StorageLive))
							{
								_active.StorageSnapshot = p.Extra;
								_active.StorageLive = flag2;
							}
						}
						if ((p.Slots & 1) != 0 && _wire.InArea(actor, _active.Request.Source.Scene) && p.Data != null && p.Data.Length > 0 && actor < _active.SourceActor)
						{
							_active.SourceSnapshot = p.Data;
							_active.SourceActor = actor;
						}
						if (actor == _active.Actor && _active.Job == null)
						{
							AutomationPacket request = _active.Request;
							request.Data = p.Data;
							request.Name = p.Name;
							_active.Request = request;
						}
						_active.Waiting.Remove(actor);
						if (_active.Waiting.Count == 0)
						{
							Grant();
						}
					}
					return;
				}
				if (p.Kind == 3 && _settings.AutomationHostOnlyLinks && !_wire.IsHostActor(actor))
				{
					throw new InvalidOperationException("Host can only Link Automation.");
				}
				if (!_wire.AllReady)
				{
					Notice(actor, "Waiting for the same Shima QoL on every player.", p.Kind == 3 || p.Kind == 4, p.Source, p.Id);
					return;
				}
				if ((p.Kind == 3 || p.Kind == 16 || p.Kind == 17) && !_wire.InArea(actor, p.Source.Scene))
				{
					NetworkGamePlayer val = _wire.PlayerFor(actor);
					Trace("Area check rejected kind " + p.Kind + ", actor " + actor + ", station area " + p.Source.Scene + ", native area " + (((Object)(object)val == (Object)null) ? (-1) : val.scene) + "; waiting for a matching loaded-area report.");
					throw new InvalidOperationException("Stay in the station's area to manage automation.");
				}
				if (p.Kind == 17)
				{
					AutomationLink automationLink = _data.Link(p.Source);
					if (_active != null || automationLink == null || automationLink.Owner != text || !automationLink.Target.Equals(p.Target))
					{
						return;
					}
					AutomationSlots.Read(p.Data, automationLink.Slots);
					if (!AutomationNative.Equal(automationLink.Rules, p.Data))
					{
						byte[] rules = automationLink.Rules;
						automationLink.Rules = p.Data;
						try
						{
							Save();
						}
						catch
						{
							automationLink.Rules = rules;
							throw;
						}
						Publish();
					}
				}
				else if (p.Kind == 16)
				{
					AutomationLink automationLink2 = _data.Link(p.Source);
					if (automationLink2 != null)
					{
						bool manual = automationLink2.Manual;
						automationLink2.Manual = p.Flag;
						try
						{
							Save();
						}
						catch
						{
							automationLink2.Manual = manual;
							throw;
						}
						if (automationLink2.Manual && _active != null && !_active.Granted && _active.Request.Source.Equals(automationLink2.Source))
						{
							Release();
						}
						Publish();
						Notice(actor, automationLink2.Manual ? "Manual collection. Chest link kept." : "Auto collection enabled.", notify: true, p.Source);
					}
				}
				else if (p.Kind == 3)
				{
					if (_active != null)
					{
						throw new InvalidOperationException("A collection is finishing. Try linking again shortly.");
					}
					if (p.Source.Scene != p.Target.Scene || p.Slots < 1 || p.Slots > 512 || AutomationNative.Saved(p.Source) == null || AutomationNative.Saved(p.Target) == null)
					{
						throw new InvalidOperationException("Station and storage must be placed in the same area.");
					}
					AutomationLink automationLink3 = _data.Link(p.Source);
					if (automationLink3 != null && automationLink3.Owner != text)
					{
						throw new InvalidOperationException("Only the linking player can change this station's destination.");
					}
					if (Collecting(_data, p.Source))
					{
						throw new InvalidOperationException("Collection is pending or recovering. Let the linking player resume automation before relinking.");
					}
					if (automationLink3 == null)
					{
						if (_data.Links.Count >= 128)
						{
							throw new InvalidOperationException("Automation link limit reached (128).");
						}
						AutomationLink automationLink4 = new AutomationLink();
						automationLink4.Source = p.Source;
						automationLink4.Owner = text;
						automationLink3 = automationLink4;
						_data.Links.Add(automationLink3);
					}
					if (p.Data != null && p.Data.Length > 0)
					{
						AutomationSlots.Read(p.Data, p.Slots);
					}
					automationLink3.Rules = p.Data;
					automationLink3.Target = p.Target;
					automationLink3.TargetName = (p.Name ?? "Storage").Replace('\n', ' ').Replace('\r', ' ');
					automationLink3.Slots = p.Slots;
					foreach (AutomationJob job in _data.Jobs)
					{
						if (job.Source.Equals(p.Source))
						{
							job.Target = p.Target;
							job.Slots = p.Slots;
						}
					}
					Save();
					Publish();
					Notice(actor, "Linked to: " + automationLink3.TargetName, notify: true, p.Source, p.Id, 3, automationLink3.Target);
				}
				else if (p.Kind == 4)
				{
					AutomationLink link = _data.Link(p.Source);
					if (link == null)
					{
						Notice(actor, "This station is not linked.", notify: true, p.Source);
						return;
					}
					if (link.Owner != text)
					{
						throw new InvalidOperationException("Only the linking player can unlink this station.");
					}
					AutomationJob automationJob = _data.Job(p.Source);
					if (Collecting(_data, p.Source))
					{
						throw new InvalidOperationException("Collection is pending or recovering. Let the linking player resume automation before unlinking.");
					}
					if (automationJob != null || Locked(p.Source))
					{
						throw new InvalidOperationException("Output is waiting. Free storage space or relink to another container first.");
					}
					_data.Links.Remove(link);
					_data.Origins.RemoveAll((AutomationOrigin o) => o.Source.Equals(link.Source));
					Save();
					Publish();
					Notice(actor, "Station unlinked.", notify: true, p.Source);
				}
				else
				{
					if (p.Kind != 5 || _active != null)
					{
						return;
					}
					AutomationLink automationLink5 = _data.Link(p.Source);
					if (automationLink5 == null || automationLink5.Owner != text || !automationLink5.Target.Equals(p.Target))
					{
						return;
					}
					AutomationJob automationJob2 = (string.IsNullOrEmpty(p.Id) ? null : _data.Job(p.Id));
					if ((automationJob2 != null && (automationJob2.Owner != text || !automationJob2.Source.Equals(p.Source))) || (!string.IsNullOrEmpty(p.Id) && automationJob2 == null) || (automationJob2 == null && Collecting(_data, p.Source)) || (automationJob2 == null && automationLink5.Manual) || AutomationNative.Saved(p.Source) == null || AutomationNative.Saved(p.Target) == null)
					{
						return;
					}
					DecorationPositionData val2 = AutomationNative.Saved(p.Target);
					bool flag3 = !_wire.InArea(actor, p.Source.Scene);
					if (flag3)
					{
						AutomationSlots.Read(automationLink5.Rules, automationLink5.Slots);
					}
					_active = new Operation
					{
						Background = flag3,
						SourceBefore = ((AutomationNative.Saved(p.Source).meta == null) ? null : ((byte[])AutomationNative.Saved(p.Source).meta.Clone())),
						Token = Guid.NewGuid().ToString("N"),
						Job = automationJob2?.Id,
						Actor = actor,
						Request = p,
						SavedBefore = ((val2.meta == null) ? null : ((byte[])val2.meta.Clone())),
						Expires = Time.unscaledTime + 15f
					};
					foreach (int item in _wire.Actors())
					{
						_active.Waiting.Add(item);
					}
					_wire.Broadcast(new AutomationPacket
					{
						Kind = 6,
						World = _data.World,
						Id = _active.Token,
						Name = text,
						Source = p.Source,
						Target = p.Target,
						Slots = automationLink5.Slots,
						Flag = (automationJob2 != null),
						Data = (flag3 ? _active.SourceBefore : null),
						Extra = val2.meta
					});
				}
			}
		}
		catch (Exception ex)
		{
			Notice(actor, ex.Message, p.Kind == 3 || p.Kind == 4, p.Source, p.Id);
			if (_active != null && (_active.Actor == actor || p.Kind == 7))
			{
				Release();
			}
		}
	}

	private void Grant()
	{
		Operation active = _active;
		if (active == null || !_wire.AllReady)
		{
			return;
		}
		DecorationPositionData val = AutomationNative.Saved(active.Request.Target);
		if (val == null || active.StorageSnapshot == null || !AutomationNative.Equal(val.meta, active.SavedBefore))
		{
			Release();
			return;
		}
		Decoration obj = AutomationNative.Live(active.Request.Target);
		Chest val2 = (Chest)(object)((obj is Chest) ? obj : null);
		if ((Object)(object)val2 != (Object)null && !AutomationNative.Equal(AutomationNative.StorageSnapshot(val2), active.StorageSnapshot))
		{
			Release();
			return;
		}
		if (!AutomationNative.Equal(val.meta, active.StorageSnapshot))
		{
			Apply(active.Request.Target, active.StorageSnapshot);
		}
		val = AutomationNative.Saved(active.Request.Target);
		AutomationJob automationJob = ((active.Job == null) ? null : _data.Job(active.Job));
		if (automationJob == null)
		{
			if (_data.Jobs.Count >= 128)
			{
				throw new InvalidOperationException("Too many pending automation collections.");
			}
			AutomationLink automationLink = _data.Link(active.Request.Source);
			if (automationLink == null || automationLink.Manual || !AutomationNative.Equal(AutomationNative.Saved(automationLink.Source).meta, active.SourceBefore))
			{
				Release();
				return;
			}
			CraftingTableData val3 = ((!active.Background) ? AutomationNative.CraftBytes(active.Request.Data) : ((active.SourceSnapshot != null) ? AutomationNative.CraftBytes(active.SourceSnapshot) : AutomationNative.Advance(active.SourceBefore, AutomationNative.CraftClock())));
			string text = active.Request.Name;
			if (active.Background)
			{
				if (text != "P0" && text != "P1")
				{
					throw new InvalidOperationException("Missing background collection policy.");
				}
				text = SelectOutput(automationLink, val3, val.meta, text == "P1");
			}
			if (val3 == null || val3.completeItems == null || val3.completeItems.Count == 0 || val3.completeItems.Count > 4096)
			{
				throw new InvalidOperationException("Station output changed. Retrying.");
			}
			CraftingTableData remaining;
			CraftingTableData val4 = AutomationNative.Select(val3, text, out remaining);
			byte[] array = AutomationNative.Items(val4.completeItems);
			AutomationNative.Items(array);
			AutomationJob automationJob2 = new AutomationJob();
			automationJob2.Id = Guid.NewGuid().ToString("N");
			automationJob2.Owner = automationLink.Owner;
			automationJob2.Source = automationLink.Source;
			automationJob2.Target = automationLink.Target;
			automationJob2.Slots = automationLink.Slots;
			automationJob2.Before = AutomationNative.CraftBytes(val4);
			automationJob2.Pending = array;
			automationJob = automationJob2;
			byte[] bytes = AutomationNative.CraftBytes(remaining);
			AutomationPacket automationPacket = default(AutomationPacket);
			automationPacket.Kind = 8;
			automationPacket.World = _data.World;
			automationPacket.Id = active.Token;
			automationPacket.Name = automationJob.Id;
			automationPacket.Source = automationJob.Source;
			automationPacket.Target = automationJob.Target;
			automationPacket.Slots = automationJob.Slots;
			automationPacket.Data = automationJob.Before;
			automationPacket.Extra = automationJob.Pending;
			automationPacket.Encode();
			AutomationOrigin automationOrigin = _data.Origin(automationLink.Source);
			AutomationOrigin automationOrigin2 = automationOrigin.Clone();
			string[] array2;
			try
			{
				array2 = automationOrigin.Claim(val3, text, remaining);
			}
			catch
			{
				_data.Origins.Remove(automationOrigin);
				automationOrigin = automationOrigin2;
				_data.Origins.Add(automationOrigin);
				array2 = new string[val4.completeItems.Count];
			}
			if (!GameManager.Multiplayer)
			{
				for (int i = 0; i < array2.Length; i++)
				{
					if (string.IsNullOrEmpty(array2[i]))
					{
						array2[i] = automationLink.Owner;
					}
				}
			}
			automationJob.Makers = array2;
			byte[] meta = AutomationNative.Saved(automationJob.Source).meta;
			try
			{
				Apply(automationJob.Source, bytes);
				_data.Jobs.Add(automationJob);
				Trace("Claim state save begin: " + automationJob.Id);
				Save();
				Trace("Claim state save end: " + automationJob.Id);
			}
			catch
			{
				_data.Jobs.Remove(automationJob);
				_data.Origins.Remove(automationOrigin);
				_data.Origins.Add(automationOrigin2);
				Apply(automationJob.Source, meta);
				throw;
			}
			active.Job = automationJob.Id;
			Publish();
		}
		active.Before = (byte[])val.meta.Clone();
		active.Granted = true;
		active.Expires = Time.unscaledTime + 30f;
		_wire.Send(active.Actor, new AutomationPacket
		{
			Kind = 8,
			World = _data.World,
			Id = active.Token,
			Name = automationJob.Id,
			Source = automationJob.Source,
			Target = automationJob.Target,
			Slots = automationJob.Slots,
			Flag = automationJob.Captured,
			Data = (automationJob.Captured ? val.meta : automationJob.Before),
			Extra = automationJob.Pending
		});
	}

	private void CaptureResult(int actor, string owner, AutomationPacket p)
	{
		AutomationJob automationJob = _data.Job(p.Id);
		if (automationJob == null || automationJob.Captured)
		{
			_wire.Send(actor, new AutomationPacket
			{
				Kind = 11,
				World = _data.World,
				Id = p.Id
			});
		}
		else
		{
			if (automationJob.Owner != owner)
			{
				return;
			}
			if (p.Name == "ShimaQoL.Automation.ExternalCollection.v1")
			{
				if (!p.Flag || AutomationNative.Items(p.Data).Count != 0 || !AutomationNative.Equal(p.Extra, automationJob.Pending))
				{
					throw new InvalidOperationException("Collection recovery does not match the pending output.");
				}
				if (_active != null && _active.Actor == actor && !(_active.Job != automationJob.Id) && _active.Granted)
				{
					int index = _data.Jobs.IndexOf(automationJob);
					_data.Jobs.RemoveAt(index);
					try
					{
						Save();
					}
					catch
					{
						_data.Jobs.Insert(index, automationJob);
						throw;
					}
					_wire.Send(actor, new AutomationPacket
					{
						Kind = 11,
						World = _data.World,
						Id = automationJob.Id
					});
					Release();
					Publish();
					Notice(actor, "Earlier output is already in your inventory. Automation resumed.", notify: true, automationJob.Source);
				}
				return;
			}
			string[] makers;
			byte[] pending = AutomationNative.Items(AutomationProvenance.Capture(automationJob, p,