Decompiled source of ChestNetwork v1.0.2

plugins/ChestNetwork.Plugin.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ChestNetwork.Core;
using ChestNetwork.Core.Actions;
using ChestNetwork.Core.Armor;
using ChestNetwork.Core.Credit;
using ChestNetwork.Core.Deposit;
using ChestNetwork.Core.Filling;
using ChestNetwork.Core.Internal;
using ChestNetwork.Core.Keeping;
using ChestNetwork.Core.Multiplayer;
using ChestNetwork.Core.Panel;
using ChestNetwork.Core.Repair;
using ChestNetwork.Core.Serving;
using ChestNetwork.Plugin.Adapters;
using ChestNetwork.Plugin.Armor;
using ChestNetwork.Plugin.Consumption;
using ChestNetwork.Plugin.Interaction;
using ChestNetwork.Plugin.Keeping;
using ChestNetwork.Plugin.Machines;
using ChestNetwork.Plugin.Net;
using ChestNetwork.Plugin.Ownership;
using ChestNetwork.Plugin.Panel;
using ChestNetwork.Plugin.Patches;
using ChestNetwork.Plugin.Serving;
using ChestNetwork.Plugin.Storage;
using ChestNetwork.Plugin.Telemetry;
using ChestNetwork.Plugin.Texts;
using ChestNetwork.Telemetry;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Roims.ConfigurationParasite;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChestNetwork.Plugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2+62fdcf3d2084b41ec9a10e4e7b2c8ce48e5480d7")]
[assembly: AssemblyProduct("ChestNetwork.Plugin")]
[assembly: AssemblyTitle("ChestNetwork.Plugin")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChestNetwork.Plugin
{
	internal static class BuildDistribution
	{
		public static readonly bool IsNexus;
	}
	[BepInPlugin("jordan.chestnetwork", "ChestNetwork", "1.0.2")]
	public sealed class ChestNetworkPlugin : BaseUnityPlugin
	{
		public const string Guid = "jordan.chestnetwork";

		public const string Name = "ChestNetwork";

		public const string Version = "1.0.2";

		private Harmony? _harmony;

		internal static ManualLogSource Log { get; private set; }

		internal static PluginSettings Settings { get; private set; }

		private void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ParasiteMod val = Parasite.Register((BaseUnityPlugin)(object)this, "ChestNetwork", "chestnetwork_cfg");
			val.AddTexts(ModTexts.ByLanguage);
			val.AddTexts(SettingsTexts.ByLanguage);
			Settings = new PluginSettings(((BaseUnityPlugin)this).Config, val);
			_harmony = new Harmony("jordan.chestnetwork");
			_harmony.PatchAll(typeof(ChestNetworkPlugin).Assembly);
			AltInteraction.Register(MachinePatches.TryFillHovered);
			AltInteraction.RegisterSwitch(MachinePatches.TryFillSwitch, MachinePatches.SwitchHover);
			AltInteraction.RegisterSwitch(ArmorStandPatches.TrySwitch, AltInteraction.AltHover(ArmorStandCoordinator.HoverAction));
			AltInteraction.Register(ArmorStandPatches.TryHovered);
			AltInteraction.RegisterSwitchUse(ArmorStandPanel.TryOpen, ArmorStandPanel.Hover);
			ContainerPanels.Register(ArmorStandPanel.Panel);
			ContainerPanels.Register(NetworkPanel.Panel);
			AltInteraction.Register(ContainerPatches.TryStoreHovered);
			ModTelemetry.Apply(Settings.TelemetryEnabled, ((BaseUnityPlugin)this).Config);
			Application.quitting += ModTelemetry.Shutdown;
			Log.LogInfo((object)(("".Length > 0) ? "ChestNetwork 1.0.2 () loaded." : "ChestNetwork 1.0.2 loaded."));
			if (BuildDistribution.IsNexus)
			{
				Log.LogInfo((object)"Nexus Mods build: the telemetry question is never asked.");
			}
		}

		private void Update()
		{
			OwnershipCoordinator.Tick();
			NetworkTransaction.Tick();
			ChestKeeper.Tick();
			CreditRpc.Tick();
			DebtJournal.Tick();
			CreditServer.Tick();
			ServerRefuel.Tick();
			CreditSession.Tick();
			IdleChestReturn.Tick();
			AltInteraction.Tick();
			FillAllInput.Tick();
		}

		private void OnDestroy()
		{
			Application.quitting -= ModTelemetry.Shutdown;
			ModTelemetry.Shutdown();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal sealed class PluginSettings
	{
		public const string TelemetrySection = "Telemetry";

		private readonly ConfigEntry<bool> _enabled;

		private readonly ConfigEntry<ConnectionRule> _connectionRule;

		private readonly ConfigEntry<bool> _inclusiveBoundaries;

		private readonly ConfigEntry<string> _allowedStationTypes;

		private readonly ConfigEntry<bool> _useCarts;

		private readonly ConfigEntry<bool> _useShips;

		private readonly ConfigEntry<bool> _allowEquippedItems;

		private readonly ConfigEntry<int> _chestReserve;

		private readonly ConfigEntry<int> _openingSafetyDelay;

		private readonly ConfigEntry<int> _actionCreditMinimum;

		private readonly ConfigEntry<int> _actionCreditMaximum;

		private readonly ConfigEntry<bool> _keepOnePerChest;

		private readonly ConfigEntry<float> _refreshInterval;

		private readonly ConfigEntry<bool> _showAvailableAmount;

		private readonly ConfigEntry<string> _availableAmountFormat;

		private readonly ConfigEntry<bool> _fillEnabled;

		private readonly ConfigEntry<bool> _useAltInteract;

		private readonly ConfigEntry<KeyboardShortcut> _altShortcut;

		private readonly ConfigEntry<bool> _fillAll;

		private readonly ConfigEntry<bool> _repairAll;

		private readonly ConfigEntry<FillOrigin> _fillOrigin;

		private readonly ConfigEntry<InventoryUse> _fillInventoryUse;

		private readonly ConfigEntry<int> _fillMinimumReserve;

		private readonly ConfigEntry<ReserveScope> _fillReserveScope;

		private readonly ConfigEntry<int> _fillMaxPerAction;

		private readonly ConfigEntry<string> _fillForbiddenItems;

		private readonly ConfigEntry<OrePriority> _fillOrePriority;

		private readonly ConfigEntry<bool> _autoRefuelEnabled;

		private readonly ConfigEntry<int> _autoRefuelMinimumReserve;

		private readonly ConfigEntry<ReserveScope> _autoRefuelReserveScope;

		private readonly ConfigEntry<int> _autoRefuelMaxPerAction;

		private readonly ConfigEntry<string> _autoRefuelForbiddenItems;

		private readonly ConfigEntry<bool> _quickStackEnabled;

		private readonly ConfigEntry<string> _quickStackCategories;

		private readonly ConfigEntry<string> _quickStackForcedItems;

		private readonly ConfigEntry<string> _quickStackExcludedItems;

		private readonly ConfigEntry<bool> _armorEnabled;

		private readonly ConfigEntry<bool> _armorTakeFromHotbar;

		private readonly ConfigEntry<bool> _armorOpenOnUse;

		private readonly ConfigEntry<bool> _networkPanelEnabled;

		private readonly ConfigEntry<bool> _networkPanelWide;

		private readonly ConfigEntry<float> _armorSetWeight;

		private readonly ConfigEntry<float> _armorTierWeight;

		private readonly ConfigEntry<float> _armorQualityWeight;

		private readonly ConfigEntry<string> _armorSets;

		private readonly ConfigEntry<bool> _telemetryEnabled;

		private readonly ConfigFile _config;

		public bool Enabled => _enabled.Value;

		public bool KeepOnePerChest => _keepOnePerChest.Value;

		public bool TelemetryEnabled => _telemetryEnabled.Value;

		public float RefreshInterval => Math.Max(0f, _refreshInterval.Value);

		public ActionCreditCap ActionCreditCap => new ActionCreditCap(_actionCreditMinimum.Value, _actionCreditMaximum.Value);

		public bool ShowAvailableAmount => _showAvailableAmount.Value;

		public bool FillEnabled => _fillEnabled.Value;

		public bool UseAltInteract => _useAltInteract.Value;

		public KeyboardShortcut AltShortcut => _altShortcut.Value;

		public bool FillAll => _fillAll.Value;

		public bool RepairAll => _repairAll.Value;

		public FillOrigin FillOrigin => _fillOrigin.Value;

		public OrePriority FillOrePriority => _fillOrePriority.Value;

		public FillSettings FillSettings { get; private set; }

		public bool QuickStackEnabled => _quickStackEnabled.Value;

		public bool ArmorStandEnabled => _armorEnabled.Value;

		public bool ArmorStandOpenOnUse => _armorOpenOnUse.Value;

		public bool NetworkPanelEnabled => _networkPanelEnabled.Value;

		public bool NetworkPanelWide
		{
			get
			{
				return _networkPanelWide.Value;
			}
			set
			{
				_networkPanelWide.Value = value;
			}
		}

		public ArmorFillSettings ArmorFillSettings { get; private set; } = ArmorFillSettings.Default;

		public ArmorSetCatalog ArmorSets { get; private set; } = ArmorSetCatalog.Vanilla;

		public DepositSettings DepositSettings { get; private set; }

		public string AvailableAmountFormat => _availableAmountFormat.Value;

		public ModConfig LocalModConfig { get; private set; }

		public PluginSettings(ConfigFile config, ParasiteMod parasite)
		{
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Expected O, but got Unknown
			//IL_039c: Unknown result type (might be due to invalid IL or missing references)
			PluginSettings pluginSettings = this;
			_config = config;
			string[] array = new string[9] { "General", "Containers", "Interaction", "Filling", "AutoRefuel", "QuickStack", "ArmorStand", "NetworkPanel", "Telemetry" };
			foreach (string text in array)
			{
				parasite.Section(text);
			}
			_enabled = parasite.Section("General").Bool("Enabled", true, "Use the resources of containers in the crafting station network.", (SettingScope)0);
			_keepOnePerChest = parasite.Section("General").Bool("KeepOnePerChest", true, "Building, crafting and filling machines leave one unit of each item in every chest of the network as long as the other chests can provide it, so that quick stack still finds that chest. The last units are only taken when needed.", (SettingScope)0);
			_connectionRule = parasite.Section("Network").FileOnly<ConnectionRule>("ConnectionRule", (ConnectionRule)0, "OverlappingZones: two stations are connected when their zones overlap. StationInsideZone: when one stands inside the other's zone.", (AcceptableValueBase)null);
			_inclusiveBoundaries = parasite.Section("Network").FileOnly<bool>("InclusiveBoundaries", true, "Whether a point exactly on a zone border is inside the zone.", (AcceptableValueBase)null);
			_allowedStationTypes = parasite.Section("Network").FileOnly<string>("AllowedStationTypes", string.Empty, "Comma-separated station names (e.g. $piece_workbench,$piece_forge). Empty: every station type.", (AcceptableValueBase)null);
			_useCarts = parasite.Section("Containers").Bool("UseCarts", false, "No effect since 1.0: only chests are part of the network.", (SettingScope)1);
			_useShips = parasite.Section("Containers").Bool("UseShips", false, "No effect since 1.0: only chests are part of the network.", (SettingScope)1);
			_allowEquippedItems = parasite.Section("Containers").Bool("AllowEquippedItems", false, "Allow consuming items the player wears.", (SettingScope)1);
			_chestReserve = parasite.Section("Containers").Int("ChestReserve", 1, 0, 100000, "Units of each item every chest always keeps, never used for building or crafting, so that quick stack still finds the chest. Machine fills also follow KeepOnePerChest.", (SettingScope)1);
			_openingSafetyDelay = parasite.Section("Containers").Int("OpeningSafetyDelay", 5000, 0, 60000, "Milliseconds a player's menu waits at most for the players whose credits stand on the chest to give them back (one round trip), against a player who stopped answering. Past it, the chest opens anyway.", (SettingScope)1);
			ActionCreditCap val = new ActionCreditCap(50, 1000);
			_actionCreditMinimum = parasite.Section("Containers").FileOnly<int>("ActionCreditMinimum", val.Minimum, "Read on the server: an action that takes from the chests (machine fill, Shift + A) may get half the network's stock of an item, but never less than this, nor less than what its nearest machine needs, nor more than the stock.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000));
			_actionCreditMaximum = parasite.Section("Containers").FileOnly<int>("ActionCreditMaximum", val.Maximum, "Read on the server: the most an action may get of an item at once, whatever half the network's stock is (never less than ActionCreditMinimum, nor than what its nearest machine needs).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000));
			_refreshInterval = parasite.Section("Performance").FileOnly<float>("RefreshInterval", 0.5f, "Seconds between two scans of the network for the build and craft menus. Consumption always rescans.", (AcceptableValueBase)null);
			_showAvailableAmount = parasite.Section("Display").FileOnly<bool>("ShowAvailableAmount", true, "Show the available amount (inventory + network containers) next to each required amount.", (AcceptableValueBase)null);
			_availableAmountFormat = parasite.Section("Display").FileOnly<string>("AvailableAmountFormat", "{0}/{1}", "Requirement text. {0} = required amount, {1} = available amount.", (AcceptableValueBase)null);
			_fillEnabled = parasite.Section("Filling").Bool("Enabled", true, "Fill smelters and fires from the network containers.", (SettingScope)0);
			_useAltInteract = parasite.Section("Interaction").Bool("UseAltInteract", true, "Act on the aimed object (fill a machine...) with the vanilla alternate use: AltPlace + Use (Shift + E by default; gamepad: its alt keys + use). Rebind them in the game settings.", (SettingScope)0);
			_altShortcut = parasite.Section("Interaction").Shortcut("Shortcut", KeyboardShortcut.Empty, "Additional key doing the same on the object under the crosshair. Empty: none.");
			_fillAll = parasite.Section("Interaction").Bool("FillAll", true, "On a machine: AltPlace (Shift by default, rebound in the game settings) + the key typing A, whatever the keyboard layout, fills every machine of the network using the same fuel (smelters, fires, torches...), nearest first, as the alternate use does on one. That key does nothing else meanwhile.", (SettingScope)0);
			_repairAll = parasite.Section("Interaction").Bool("RepairAll", true, "At a crafting station: AltPlace (Shift by default, rebound in the game settings) + click on the repair button repairs every repairable item of your inventory at once. Mouse only.", (SettingScope)0);
			_fillOrigin = parasite.Section("Filling").FileOnly<FillOrigin>("NetworkOrigin", FillOrigin.Player, "Where the station network is resolved from: the player (as for building) or the machine.", (AcceptableValueBase)null);
			_fillInventoryUse = parasite.Section("Filling").Enum<InventoryUse>("InventoryUse", (InventoryUse)1, "Whether the player's inventory is used: Never, First (before containers) or Last (after containers).");
			_fillMinimumReserve = parasite.Section("Filling").Int("MinimumReserve", 0, 0, 100000, "Units of each item always left in the containers.", (SettingScope)0);
			_fillReserveScope = parasite.Section("Filling").FileOnly<ReserveScope>("ReserveScope", (ReserveScope)0, "Network: the containers together keep the reserve. PerContainer: each container keeps it.", (AcceptableValueBase)null);
			_fillMaxPerAction = parasite.Section("Filling").FileOnly<int>("MaxPerAction", 0, "Most units inserted by one action. 0: no limit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100000));
			_fillForbiddenItems = parasite.Section("Filling").FileOnly<string>("ForbiddenItems", string.Empty, "Comma-separated item names never used for filling (e.g. $item_finewood).", (AcceptableValueBase)null);
			_fillOrePriority = parasite.Section("Filling").FileOnly<OrePriority>("OrePriority", OrePriority.QueuedFirst, "When a machine (smelter, stone oven) accepts several items: QueuedFirst (what it is already processing) or MachineOrder.", (AcceptableValueBase)null);
			_autoRefuelEnabled = parasite.Section("AutoRefuel").Bool("Enabled", true, "Fires, torches, smelters and stone ovens refill their fuel by themselves from the chests of their own network each time they burn a unit. Never from a player's inventory.", (SettingScope)1);
			_autoRefuelMinimumReserve = parasite.Section("AutoRefuel").Int("MinimumReserve", 0, 0, 100000, "Units of each fuel always left in the chests by the automatic refill.", (SettingScope)1);
			_autoRefuelReserveScope = parasite.Section("AutoRefuel").FileOnly<ReserveScope>("ReserveScope", (ReserveScope)0, "Network: the containers together keep the reserve. PerContainer: each container keeps it.", (AcceptableValueBase)null);
			_autoRefuelMaxPerAction = parasite.Section("AutoRefuel").FileOnly<int>("MaxPerAction", 0, "Most units added by one refill. 0: up to the machine's capacity.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100000));
			_autoRefuelForbiddenItems = parasite.Section("AutoRefuel").FileOnly<string>("ForbiddenItems", string.Empty, "Comma-separated item names never used by the automatic refill (e.g. $item_finewood).", (AcceptableValueBase)null);
			_quickStackEnabled = parasite.Section("QuickStack").Bool("Enabled", true, "Alternate use on a chest of the network stores your items into the network chests that already hold them, instead of opening it.", (SettingScope)0);
			_quickStackCategories = parasite.Section("QuickStack").Choices("IncludedCategories", "Material,Trophy", SettingsTexts.Categories, "Comma-separated item types stored (game names: Material, Trophy, Consumable, Ammo, Fish...). The hotbar row and equipped items are never stored.");
			_quickStackForcedItems = parasite.Section("QuickStack").FileOnly<string>("ForcedItems", string.Empty, "Comma-separated items always stored, whatever their type (e.g. $item_raspberries).", (AcceptableValueBase)null);
			_quickStackExcludedItems = parasite.Section("QuickStack").FileOnly<string>("ExcludedItems", string.Empty, "Comma-separated items never stored, whatever their type (e.g. $item_finewood). Wins over ForcedItems.", (AcceptableValueBase)null);
			_armorEnabled = parasite.Section("ArmorStand").Bool("Enabled", true, "Alternate use on an armor stand: dress it from your inventory and the network when it holds no armor, else swap armor with it.", (SettingScope)0);
			_armorTakeFromHotbar = parasite.Section("ArmorStand").Bool("TakeFromHotbar", false, "Dressing a stand may take armor from the hotbar row.", (SettingScope)0);
			_armorOpenOnUse = parasite.Section("ArmorStand").Bool("OpenOnUse", true, "Use (E) on an armor stand opens a panel with one cell per slot, like a chest, instead of dropping the piece on the ground.", (SettingScope)0);
			_armorSetWeight = parasite.Section("ArmorStand").FileOnly<float>("SetWeight", 100f, "Dressing: cost of a piece outside the chosen set (dominant).", (AcceptableValueBase)null);
			_armorTierWeight = parasite.Section("ArmorStand").FileOnly<float>("TierWeight", 10f, "Dressing: cost per tier of difference with the chosen set.", (AcceptableValueBase)null);
			_armorQualityWeight = parasite.Section("ArmorStand").FileOnly<float>("QualityWeight", 1f, "Dressing: cost per quality level of difference with the chosen set.", (AcceptableValueBase)null);
			_armorSets = parasite.Section("ArmorStand").FileOnly<string>("Sets", "rags:1:ArmorRagsChest,ArmorRagsLegs;leather:1:ArmorLeatherChest,ArmorLeatherLegs,HelmetLeather,CapeDeerHide;troll:2:ArmorTrollLeatherChest,ArmorTrollLeatherLegs,HelmetTrollLeather,CapeTrollHide;bronze:2:ArmorBronzeChest,ArmorBronzeLegs,HelmetBronze;root:3:ArmorRootChest,ArmorRootLegs,HelmetRoot;iron:3:ArmorIronChest,ArmorIronLegs,HelmetIron;wolf:4:ArmorWolfChest,ArmorWolfLegs,HelmetDrake,CapeWolf;fenris:4:ArmorFenringChest,ArmorFenringLegs,HelmetFenring;padded:5:ArmorPaddedCuirass,ArmorPaddedGreaves,HelmetPadded;carapace:6:ArmorCarapaceChest,ArmorCarapaceLegs,HelmetCarapace,CapeFeather;mage:6:ArmorMageChest,ArmorMageLegs,HelmetMage;flametal:7:ArmorFlametalChest,ArmorFlametalLegs;askvin:7:ArmorAshlandsMediumChest,ArmorAshlandsMediumlegs,HelmetAshlandsMediumHood,CapeAsksvin;deepnorthheavy:8:ArmorDeepNorthHeavyChest,ArmorDeepNorthHeavylegs,HelmetDNHeavy;deepnorthmedium:8:ArmorDeepNorthMediumChest,ArmorDeepNorthMediumlegs,HelmetDNMedium;deepnorthmage:8:ArmorDeepNorthMageChest,ArmorDeepNorthMagelegs,HelmetDNMage", "Armor sets, used for items without a game set name: set:tier:prefab,prefab;... Tiers follow the biomes (1 = Meadows). Add armors of other mods here.", (AcceptableValueBase)null);
			_networkPanelEnabled = parasite.Section("NetworkPanel").Bool("Enabled", true, "The inventory key, in the chest network, also opens a panel with everything the network's chests hold, to take or store items.", (SettingScope)0);
			_networkPanelWide = parasite.Section("NetworkPanel").FileOnly<bool>("Wide", false, "The panel is widened up to the crafting menu. Set by the button in the panel's header, kept between sessions.", (AcceptableValueBase)null);
			_telemetryEnabled = parasite.Section("Telemetry").Bool("Enabled", false, BuildDistribution.IsNexus ? "Share anonymous usage statistics to help improve the mod (no personal data). Off unless you turn it on; see the README." : "Share anonymous usage statistics to help improve the mod (no personal data). Asked once at the main menu; see the README.", (SettingScope)0);
			if (!BuildDistribution.IsNexus)
			{
				ConfigEntry<bool> val2 = parasite.Section("Telemetry").FileOnly<bool>("ConsentAsked", false, "Set by the mod once the telemetry question was answered at the main menu. Set it to false to be asked again.", (AcceptableValueBase)null);
				parasite.AskConsent(_telemetryEnabled, val2, "$chestnetwork_cfg_telemetry_consent_title", "$chestnetwork_cfg_telemetry_consent_text");
			}
			MigrateProtectHotbar(config);
			LocalModConfig = Build();
			FillSettings = BuildFillSettings();
			DepositSettings = BuildDepositSettings();
			BuildArmorSettings();
			config.SettingChanged += delegate
			{
				if (!parasite.IsApplying)
				{
					pluginSettings.Rebuild();
				}
			};
			parasite.Applied += Rebuild;
		}

		private void Rebuild()
		{
			LocalModConfig = Build();
			FillSettings = BuildFillSettings();
			DepositSettings = BuildDepositSettings();
			BuildArmorSettings();
			HandshakePatches.BroadcastConfig();
			ModTelemetry.Apply(TelemetryEnabled, _config);
		}

		private FillSettings BuildFillSettings()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			FillSettings obj = FillSettings.Default.<Clone>$();
			obj.set_InventoryUse(_fillInventoryUse.Value);
			obj.set_MinimumReserve(Math.Max(0, _fillMinimumReserve.Value));
			obj.set_ReserveScope(_fillReserveScope.Value);
			obj.set_MaxPerAction((_fillMaxPerAction.Value > 0) ? new int?(_fillMaxPerAction.Value) : ((int?)null));
			obj.set_ForbiddenItems((IReadOnlyCollection<string>)(object)ListValue.Split(_fillForbiddenItems.Value));
			return obj;
		}

		private DepositSettings BuildDepositSettings()
		{
			DepositSettings obj = DepositSettings.Default.<Clone>$();
			obj.set_IncludedCategories((IReadOnlyCollection<string>)(object)ListValue.Split(_quickStackCategories.Value));
			obj.set_ForcedItems((IReadOnlyCollection<string>)(object)ListValue.Split(_quickStackForcedItems.Value));
			obj.set_ExcludedItems((IReadOnlyCollection<string>)(object)ListValue.Split(_quickStackExcludedItems.Value));
			return obj;
		}

		private void BuildArmorSettings()
		{
			ArmorFillSettings obj = ArmorFillSettings.Default.<Clone>$();
			obj.set_SetWeight(Weight(_armorSetWeight.Value, ArmorFillSettings.Default.SetWeight));
			obj.set_TierWeight(Weight(_armorTierWeight.Value, ArmorFillSettings.Default.TierWeight));
			obj.set_QualityWeight(Weight(_armorQualityWeight.Value, ArmorFillSettings.Default.QualityWeight));
			obj.set_ProtectHotbar(!_armorTakeFromHotbar.Value);
			ArmorFillSettings = obj;
			ArmorSetCatalog armorSets = default(ArmorSetCatalog);
			string text = default(string);
			if (ArmorSetCatalog.TryParse(_armorSets.Value, ref armorSets, ref text))
			{
				ArmorSets = armorSets;
				return;
			}
			ChestNetworkPlugin.Log.LogWarning((object)("[ArmorStand] Sets: " + text + " Using the vanilla table."));
			ArmorSets = ArmorSetCatalog.Vanilla;
		}

		private void MigrateProtectHotbar(ConfigFile config)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			ConfigDefinition val = new ConfigDefinition("ArmorStand", "ProtectHotbar");
			if (!config.Bind<bool>(val, true, (ConfigDescription)null).Value)
			{
				_armorTakeFromHotbar.Value = true;
			}
			config.Remove(val);
			config.Save();
		}

		private static double Weight(float value, double fallback)
		{
			if (!(value >= 0f) || float.IsNaN(value) || float.IsInfinity(value))
			{
				return fallback;
			}
			return value;
		}

		private ModConfig Build()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			string[] array = ListValue.Split(_allowedStationTypes.Value);
			List<ContainerKind> list = new List<ContainerKind>();
			if (!_useCarts.Value)
			{
				list.Add((ContainerKind)1);
			}
			if (!_useShips.Value)
			{
				list.Add((ContainerKind)2);
			}
			ModConfig obj = ModConfig.Default.<Clone>$();
			obj.set_ConnectionRule(_connectionRule.Value);
			obj.set_InclusiveBoundaries(_inclusiveBoundaries.Value);
			obj.set_AllowedStationTypes((IReadOnlyCollection<string>)(object)((array.Length == 0) ? null : array));
			obj.set_ExcludedContainerKinds((IReadOnlyCollection<ContainerKind>)list);
			obj.set_AllowEquippedItems(_allowEquippedItems.Value);
			obj.set_ChestReserve(_chestReserve.Value);
			obj.set_OpeningSafetyDelay(_openingSafetyDelay.Value);
			obj.set_AutoRefuel(_autoRefuelEnabled.Value);
			FillSettings obj2 = FillSettings.Default.<Clone>$();
			obj2.set_InventoryUse((InventoryUse)0);
			obj2.set_MinimumReserve(Math.Max(0, _autoRefuelMinimumReserve.Value));
			obj2.set_ReserveScope(_autoRefuelReserveScope.Value);
			obj2.set_MaxPerAction((_autoRefuelMaxPerAction.Value > 0) ? new int?(_autoRefuelMaxPerAction.Value) : ((int?)null));
			obj2.set_ForbiddenItems((IReadOnlyCollection<string>)(object)ListValue.Split(_autoRefuelForbiddenItems.Value));
			obj.set_AutoRefuelSettings(obj2);
			obj.set_QualityMatching((QualityMatching)1);
			return obj;
		}
	}
	internal static class PluginVersion
	{
		public const string Value = "1.0.2";

		public const string Label = "";

		public const string Distribution = "thunderstore";
	}
}
namespace ChestNetwork.Plugin.Texts
{
	internal static class ModTexts
	{
		public const string FillPreparing = "$chestnetwork_fill_preparing";

		public const string FillMachineBusy = "$chestnetwork_fill_machine_busy";

		public const string FillAlreadyFull = "$chestnetwork_fill_already_full";

		public const string FillNothingToAdd = "$chestnetwork_fill_nothing_to_add";

		public const string FillHoverAction = "$chestnetwork_fill_hover";

		public const string WaitingForContainers = "$chestnetwork_waiting_for_containers";

		public const string FillAllHoverAction = "$chestnetwork_fill_all_hover";

		public const string FillAllDone = "$chestnetwork_fill_all_done";

		public const string FillAllShort = "$chestnetwork_fill_all_short";

		public const string FillAllBusy = "$chestnetwork_fill_all_busy";

		public const string RepairAllDone = "$chestnetwork_repair_all_done";

		public const string RepairAllHint = "$chestnetwork_repair_all_hint";

		public const string StoreHoverAction = "$chestnetwork_store_hover";

		public const string StoreNotInNetwork = "$chestnetwork_store_not_in_network";

		public const string StorePreparing = "$chestnetwork_store_preparing";

		public const string StoreNothing = "$chestnetwork_store_nothing";

		public const string StoreFull = "$chestnetwork_store_full";

		public const string StoreDone = "$chestnetwork_store_done";

		public const string ArmorFillHover = "$chestnetwork_armor_fill_hover";

		public const string ArmorSwapHover = "$chestnetwork_armor_swap_hover";

		public const string ArmorNothing = "$chestnetwork_armor_nothing";

		public const string ArmorPreparing = "$chestnetwork_armor_preparing";

		public const string ArmorBusy = "$chestnetwork_armor_busy";

		public const string SlotHelmet = "$chestnetwork_slot_helmet";

		public const string SlotCape = "$chestnetwork_slot_cape";

		public const string SlotChest = "$chestnetwork_slot_chest";

		public const string SlotLegs = "$chestnetwork_slot_legs";

		public const string SlotHandRight = "$chestnetwork_slot_hand_right";

		public const string SlotHandLeft = "$chestnetwork_slot_hand_left";

		public const string SlotBackRight = "$chestnetwork_slot_back_right";

		public const string SlotBackLeft = "$chestnetwork_slot_back_left";

		public const string PanelChests = "$chestnetwork_panel_chests";

		public const string PanelEmpty = "$chestnetwork_panel_empty";

		public const string PanelWiden = "$chestnetwork_panel_widen";

		public const string PanelNarrow = "$chestnetwork_panel_narrow";

		public const string PanelNoTarget = "$chestnetwork_panel_no_target";

		public const string PanelProtected = "$chestnetwork_panel_protected";

		public const string CategoryMaterials = "$chestnetwork_category_materials";

		public const string CategoryToPrepare = "$chestnetwork_category_to_prepare";

		public const string CategoryFood = "$chestnetwork_category_food";

		public const string CategoryMeads = "$chestnetwork_category_meads";

		public const string CategoryAmmo = "$chestnetwork_category_ammo";

		public const string CategoryWeapons = "$chestnetwork_category_weapons";

		public const string CategoryArmor = "$chestnetwork_category_armor";

		public const string CategoryTools = "$chestnetwork_category_tools";

		public const string CategoryTrophies = "$chestnetwork_category_trophies";

		public const string CategoryFish = "$chestnetwork_category_fish";

		public const string CategoryMisc = "$chestnetwork_category_misc";

		private const string Fallback = "English";

		private static readonly Dictionary<string, Dictionary<string, string>> Texts = new Dictionary<string, Dictionary<string, string>>
		{
			["English"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Preparing to fill...",
				["$chestnetwork_fill_machine_busy"] = "Machine used by another player, try again",
				["$chestnetwork_fill_already_full"] = "Already full",
				["$chestnetwork_fill_nothing_to_add"] = "Nothing to add",
				["$chestnetwork_fill_hover"] = "Fill from chests",
				["$chestnetwork_waiting_for_containers"] = "Chest network: waiting for containers held by other players...",
				["$chestnetwork_fill_all_hover"] = "Fill every machine like this one",
				["$chestnetwork_fill_all_done"] = "$1 machine(s) filled: $2",
				["$chestnetwork_fill_all_short"] = "Not enough in the chests for $1 machine(s)",
				["$chestnetwork_fill_all_busy"] = "$1 machine(s) used by another player, skipped",
				["$chestnetwork_repair_all_done"] = "$1 item(s) repaired",
				["$chestnetwork_repair_all_hint"] = "$1 + click: repair every item",
				["$chestnetwork_store_hover"] = "Store in network (items already there)",
				["$chestnetwork_store_not_in_network"] = "This chest is not in a crafting station network",
				["$chestnetwork_store_preparing"] = "Preparing to store...",
				["$chestnetwork_store_nothing"] = "Nothing to store",
				["$chestnetwork_store_full"] = "$1 chest full",
				["$chestnetwork_store_done"] = "Stored $1 item(s) in $2 chest(s)",
				["$chestnetwork_armor_fill_hover"] = "Dress the stand",
				["$chestnetwork_armor_swap_hover"] = "Swap armor",
				["$chestnetwork_armor_nothing"] = "No armor found",
				["$chestnetwork_armor_preparing"] = "Preparing the armor stand...",
				["$chestnetwork_armor_busy"] = "Armor stand used by another player, try again",
				["$chestnetwork_slot_helmet"] = "Helmet",
				["$chestnetwork_slot_cape"] = "Cape",
				["$chestnetwork_slot_chest"] = "Chest",
				["$chestnetwork_slot_legs"] = "Legs",
				["$chestnetwork_slot_hand_right"] = "Right hand",
				["$chestnetwork_slot_hand_left"] = "Left hand",
				["$chestnetwork_slot_back_right"] = "Back right",
				["$chestnetwork_slot_back_left"] = "Back left",
				["$chestnetwork_panel_chests"] = "Network chests",
				["$chestnetwork_panel_empty"] = "No item in the network",
				["$chestnetwork_panel_widen"] = "Widen the panel",
				["$chestnetwork_panel_narrow"] = "Narrow the panel",
				["$chestnetwork_panel_no_target"] = "No chest of the network holds $1",
				["$chestnetwork_panel_protected"] = "Hotbar and equipped items are never stored",
				["$chestnetwork_category_materials"] = "Materials",
				["$chestnetwork_category_to_prepare"] = "To cook and ferment",
				["$chestnetwork_category_food"] = "Food",
				["$chestnetwork_category_meads"] = "Meads and potions",
				["$chestnetwork_category_ammo"] = "Ammunition",
				["$chestnetwork_category_weapons"] = "Weapons and shields",
				["$chestnetwork_category_armor"] = "Armor and accessories",
				["$chestnetwork_category_tools"] = "Tools and torches",
				["$chestnetwork_category_trophies"] = "Trophies",
				["$chestnetwork_category_fish"] = "Fish",
				["$chestnetwork_category_misc"] = "Miscellaneous"
			},
			["French"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Préparation du remplissage...",
				["$chestnetwork_fill_machine_busy"] = "Machine utilisée par un autre joueur, réessayez",
				["$chestnetwork_fill_already_full"] = "Déjà plein",
				["$chestnetwork_fill_nothing_to_add"] = "Rien à ajouter",
				["$chestnetwork_fill_hover"] = "Remplir depuis les coffres",
				["$chestnetwork_waiting_for_containers"] = "Réseau de coffres : attente des coffres détenus par d'autres joueurs...",
				["$chestnetwork_fill_all_hover"] = "Remplir toutes les machines de ce type",
				["$chestnetwork_fill_all_done"] = "$1 machine(s) remplie(s) : $2",
				["$chestnetwork_fill_all_short"] = "Pas assez dans les coffres pour $1 machine(s)",
				["$chestnetwork_fill_all_busy"] = "$1 machine(s) utilisée(s) par un autre joueur, ignorée(s)",
				["$chestnetwork_repair_all_done"] = "$1 objet(s) réparé(s)",
				["$chestnetwork_repair_all_hint"] = "$1 + clic : réparer tous les objets",
				["$chestnetwork_store_hover"] = "Ranger dans le réseau (items déjà présents)",
				["$chestnetwork_store_not_in_network"] = "Ce coffre n'est pas dans un réseau d'établis",
				["$chestnetwork_store_preparing"] = "Préparation du rangement...",
				["$chestnetwork_store_nothing"] = "Rien à ranger",
				["$chestnetwork_store_full"] = "Coffre de $1 plein",
				["$chestnetwork_store_done"] = "$1 objet(s) rangé(s) dans $2 coffre(s)",
				["$chestnetwork_armor_fill_hover"] = "Garnir",
				["$chestnetwork_armor_swap_hover"] = "Échanger l'armure",
				["$chestnetwork_armor_nothing"] = "Aucune armure trouvée",
				["$chestnetwork_armor_preparing"] = "Préparation du porte-armure...",
				["$chestnetwork_armor_busy"] = "Porte-armure utilisé par un autre joueur, réessayez",
				["$chestnetwork_slot_helmet"] = "Casque",
				["$chestnetwork_slot_cape"] = "Cape",
				["$chestnetwork_slot_chest"] = "Torse",
				["$chestnetwork_slot_legs"] = "Pantalon",
				["$chestnetwork_slot_hand_right"] = "Main droite",
				["$chestnetwork_slot_hand_left"] = "Main gauche",
				["$chestnetwork_slot_back_right"] = "Dos droit",
				["$chestnetwork_slot_back_left"] = "Dos gauche",
				["$chestnetwork_panel_chests"] = "Coffres du réseau",
				["$chestnetwork_panel_empty"] = "Aucun objet dans le réseau",
				["$chestnetwork_panel_widen"] = "Élargir le panneau",
				["$chestnetwork_panel_narrow"] = "Réduire le panneau",
				["$chestnetwork_panel_no_target"] = "Aucun coffre du réseau ne contient $1",
				["$chestnetwork_panel_protected"] = "La barre rapide et les objets équipés ne sont jamais rangés",
				["$chestnetwork_category_materials"] = "Matériaux",
				["$chestnetwork_category_to_prepare"] = "À cuisiner et à fermenter",
				["$chestnetwork_category_food"] = "Nourriture",
				["$chestnetwork_category_meads"] = "Hydromels et potions",
				["$chestnetwork_category_ammo"] = "Munitions",
				["$chestnetwork_category_weapons"] = "Armes et boucliers",
				["$chestnetwork_category_armor"] = "Armures et accessoires",
				["$chestnetwork_category_tools"] = "Outils et torches",
				["$chestnetwork_category_trophies"] = "Trophées",
				["$chestnetwork_category_fish"] = "Poissons",
				["$chestnetwork_category_misc"] = "Divers"
			},
			["German"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Befüllung wird vorbereitet...",
				["$chestnetwork_fill_machine_busy"] = "Maschine wird von einem anderen Spieler benutzt, versuche es erneut",
				["$chestnetwork_fill_already_full"] = "Bereits voll",
				["$chestnetwork_fill_nothing_to_add"] = "Nichts hinzuzufügen",
				["$chestnetwork_fill_hover"] = "Aus Truhen befüllen",
				["$chestnetwork_waiting_for_containers"] = "Truhennetzwerk: warte auf Truhen anderer Spieler...",
				["$chestnetwork_fill_all_hover"] = "Alle Maschinen dieser Art befüllen",
				["$chestnetwork_fill_all_done"] = "$1 Maschine(n) befüllt: $2",
				["$chestnetwork_fill_all_short"] = "Nicht genug in den Truhen für $1 Maschine(n)",
				["$chestnetwork_fill_all_busy"] = "$1 Maschine(n) von einem anderen Spieler benutzt, übersprungen",
				["$chestnetwork_repair_all_done"] = "$1 Gegenstand/Gegenstände repariert",
				["$chestnetwork_repair_all_hint"] = "$1 + Klick: alle Gegenstände reparieren",
				["$chestnetwork_store_hover"] = "Im Netzwerk einlagern (bereits vorhandene Gegenstände)",
				["$chestnetwork_store_not_in_network"] = "Diese Truhe gehört zu keinem Werkbanknetzwerk",
				["$chestnetwork_store_preparing"] = "Einlagerung wird vorbereitet...",
				["$chestnetwork_store_nothing"] = "Nichts einzulagern",
				["$chestnetwork_store_full"] = "Truhe für $1 voll",
				["$chestnetwork_store_done"] = "$1 Gegenstände in $2 Truhe(n) eingelagert",
				["$chestnetwork_armor_fill_hover"] = "Ständer ausstatten",
				["$chestnetwork_armor_swap_hover"] = "Rüstung tauschen",
				["$chestnetwork_armor_nothing"] = "Keine Rüstung gefunden",
				["$chestnetwork_armor_preparing"] = "Rüstungsständer wird vorbereitet...",
				["$chestnetwork_armor_busy"] = "Rüstungsständer wird von einem anderen Spieler benutzt, versuche es erneut",
				["$chestnetwork_slot_helmet"] = "Helm",
				["$chestnetwork_slot_cape"] = "Umhang",
				["$chestnetwork_slot_chest"] = "Brust",
				["$chestnetwork_slot_legs"] = "Beine",
				["$chestnetwork_slot_hand_right"] = "Rechte Hand",
				["$chestnetwork_slot_hand_left"] = "Linke Hand",
				["$chestnetwork_slot_back_right"] = "Rücken rechts",
				["$chestnetwork_slot_back_left"] = "Rücken links",
				["$chestnetwork_panel_chests"] = "Truhen im Netzwerk",
				["$chestnetwork_panel_empty"] = "Keine Gegenstände im Netzwerk",
				["$chestnetwork_panel_widen"] = "Panel verbreitern",
				["$chestnetwork_panel_narrow"] = "Panel verschmälern",
				["$chestnetwork_panel_no_target"] = "Keine Truhe des Netzwerks enthält $1",
				["$chestnetwork_panel_protected"] = "Schnellleiste und ausgerüstete Gegenstände werden nie eingelagert",
				["$chestnetwork_category_materials"] = "Materialien",
				["$chestnetwork_category_to_prepare"] = "Zum Kochen und Gären",
				["$chestnetwork_category_food"] = "Nahrung",
				["$chestnetwork_category_meads"] = "Met und Tränke",
				["$chestnetwork_category_ammo"] = "Munition",
				["$chestnetwork_category_weapons"] = "Waffen und Schilde",
				["$chestnetwork_category_armor"] = "Rüstung und Zubehör",
				["$chestnetwork_category_tools"] = "Werkzeuge und Fackeln",
				["$chestnetwork_category_trophies"] = "Trophäen",
				["$chestnetwork_category_fish"] = "Fische",
				["$chestnetwork_category_misc"] = "Verschiedenes"
			},
			["Spanish"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Preparando el llenado...",
				["$chestnetwork_fill_machine_busy"] = "Máquina en uso por otro jugador, inténtalo de nuevo",
				["$chestnetwork_fill_already_full"] = "Ya está lleno",
				["$chestnetwork_fill_nothing_to_add"] = "Nada que añadir",
				["$chestnetwork_fill_hover"] = "Llenar desde los cofres",
				["$chestnetwork_waiting_for_containers"] = "Red de cofres: esperando cofres de otros jugadores...",
				["$chestnetwork_fill_all_hover"] = "Llenar todas las máquinas de este tipo",
				["$chestnetwork_fill_all_done"] = "$1 máquina(s) llenada(s): $2",
				["$chestnetwork_fill_all_short"] = "No hay suficiente en los cofres para $1 máquina(s)",
				["$chestnetwork_fill_all_busy"] = "$1 máquina(s) usada(s) por otro jugador, omitida(s)",
				["$chestnetwork_repair_all_done"] = "$1 objeto(s) reparado(s)",
				["$chestnetwork_repair_all_hint"] = "$1 + clic: reparar todos los objetos",
				["$chestnetwork_store_hover"] = "Guardar en la red (objetos ya presentes)",
				["$chestnetwork_store_not_in_network"] = "Este cofre no está en una red de mesas de trabajo",
				["$chestnetwork_store_preparing"] = "Preparando el almacenamiento...",
				["$chestnetwork_store_nothing"] = "Nada que guardar",
				["$chestnetwork_store_full"] = "Cofre de $1 lleno",
				["$chestnetwork_store_done"] = "$1 objeto(s) guardado(s) en $2 cofre(s)",
				["$chestnetwork_armor_fill_hover"] = "Equipar el soporte",
				["$chestnetwork_armor_swap_hover"] = "Intercambiar armadura",
				["$chestnetwork_armor_nothing"] = "No se encontró armadura",
				["$chestnetwork_armor_preparing"] = "Preparando el soporte de armadura...",
				["$chestnetwork_armor_busy"] = "Soporte de armadura en uso por otro jugador, inténtalo de nuevo",
				["$chestnetwork_slot_helmet"] = "Casco",
				["$chestnetwork_slot_cape"] = "Capa",
				["$chestnetwork_slot_chest"] = "Torso",
				["$chestnetwork_slot_legs"] = "Piernas",
				["$chestnetwork_slot_hand_right"] = "Mano derecha",
				["$chestnetwork_slot_hand_left"] = "Mano izquierda",
				["$chestnetwork_slot_back_right"] = "Espalda derecha",
				["$chestnetwork_slot_back_left"] = "Espalda izquierda",
				["$chestnetwork_panel_chests"] = "Cofres de la red",
				["$chestnetwork_panel_empty"] = "Ningún objeto en la red",
				["$chestnetwork_panel_widen"] = "Ensanchar el panel",
				["$chestnetwork_panel_narrow"] = "Estrechar el panel",
				["$chestnetwork_panel_no_target"] = "Ningún cofre de la red contiene $1",
				["$chestnetwork_panel_protected"] = "La barra rápida y los objetos equipados nunca se guardan",
				["$chestnetwork_category_materials"] = "Materiales",
				["$chestnetwork_category_to_prepare"] = "Para cocinar y fermentar",
				["$chestnetwork_category_food"] = "Comida",
				["$chestnetwork_category_meads"] = "Hidromieles y pociones",
				["$chestnetwork_category_ammo"] = "Munición",
				["$chestnetwork_category_weapons"] = "Armas y escudos",
				["$chestnetwork_category_armor"] = "Armaduras y accesorios",
				["$chestnetwork_category_tools"] = "Herramientas y antorchas",
				["$chestnetwork_category_trophies"] = "Trofeos",
				["$chestnetwork_category_fish"] = "Peces",
				["$chestnetwork_category_misc"] = "Varios"
			},
			["Portuguese_Brazilian"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Preparando o abastecimento...",
				["$chestnetwork_fill_machine_busy"] = "Máquina em uso por outro jogador, tente novamente",
				["$chestnetwork_fill_already_full"] = "Já está cheio",
				["$chestnetwork_fill_nothing_to_add"] = "Nada para adicionar",
				["$chestnetwork_fill_hover"] = "Abastecer a partir dos baús",
				["$chestnetwork_waiting_for_containers"] = "Rede de baús: aguardando baús de outros jogadores...",
				["$chestnetwork_fill_all_hover"] = "Abastecer todas as máquinas deste tipo",
				["$chestnetwork_fill_all_done"] = "$1 máquina(s) abastecida(s): $2",
				["$chestnetwork_fill_all_short"] = "Não há o suficiente nos baús para $1 máquina(s)",
				["$chestnetwork_fill_all_busy"] = "$1 máquina(s) usada(s) por outro jogador, ignorada(s)",
				["$chestnetwork_repair_all_done"] = "$1 item(ns) reparado(s)",
				["$chestnetwork_repair_all_hint"] = "$1 + clique: reparar todos os itens",
				["$chestnetwork_store_hover"] = "Guardar na rede (itens já presentes)",
				["$chestnetwork_store_not_in_network"] = "Este baú não está em uma rede de bancadas",
				["$chestnetwork_store_preparing"] = "Preparando o armazenamento...",
				["$chestnetwork_store_nothing"] = "Nada para guardar",
				["$chestnetwork_store_full"] = "Baú de $1 cheio",
				["$chestnetwork_store_done"] = "$1 item(ns) guardado(s) em $2 baú(s)",
				["$chestnetwork_armor_fill_hover"] = "Equipar o suporte",
				["$chestnetwork_armor_swap_hover"] = "Trocar armadura",
				["$chestnetwork_armor_nothing"] = "Nenhuma armadura encontrada",
				["$chestnetwork_armor_preparing"] = "Preparando o suporte de armadura...",
				["$chestnetwork_armor_busy"] = "Suporte de armadura em uso por outro jogador, tente novamente",
				["$chestnetwork_slot_helmet"] = "Elmo",
				["$chestnetwork_slot_cape"] = "Capa",
				["$chestnetwork_slot_chest"] = "Peitoral",
				["$chestnetwork_slot_legs"] = "Pernas",
				["$chestnetwork_slot_hand_right"] = "Mão direita",
				["$chestnetwork_slot_hand_left"] = "Mão esquerda",
				["$chestnetwork_slot_back_right"] = "Costas direita",
				["$chestnetwork_slot_back_left"] = "Costas esquerda",
				["$chestnetwork_panel_chests"] = "Baús da rede",
				["$chestnetwork_panel_empty"] = "Nenhum item na rede",
				["$chestnetwork_panel_widen"] = "Alargar o painel",
				["$chestnetwork_panel_narrow"] = "Estreitar o painel",
				["$chestnetwork_panel_no_target"] = "Nenhum baú da rede contém $1",
				["$chestnetwork_panel_protected"] = "A barra rápida e os itens equipados nunca são guardados",
				["$chestnetwork_category_materials"] = "Materiais",
				["$chestnetwork_category_to_prepare"] = "Para cozinhar e fermentar",
				["$chestnetwork_category_food"] = "Comida",
				["$chestnetwork_category_meads"] = "Hidroméis e poções",
				["$chestnetwork_category_ammo"] = "Munição",
				["$chestnetwork_category_weapons"] = "Armas e escudos",
				["$chestnetwork_category_armor"] = "Armaduras e acessórios",
				["$chestnetwork_category_tools"] = "Ferramentas e tochas",
				["$chestnetwork_category_trophies"] = "Troféus",
				["$chestnetwork_category_fish"] = "Peixes",
				["$chestnetwork_category_misc"] = "Diversos"
			},
			["Polish"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Przygotowywanie napełniania...",
				["$chestnetwork_fill_machine_busy"] = "Maszyna jest używana przez innego gracza, spróbuj ponownie",
				["$chestnetwork_fill_already_full"] = "Już pełne",
				["$chestnetwork_fill_nothing_to_add"] = "Nie ma czego dodać",
				["$chestnetwork_fill_hover"] = "Napełnij ze skrzyń",
				["$chestnetwork_waiting_for_containers"] = "Sieć skrzyń: oczekiwanie na skrzynie innych graczy...",
				["$chestnetwork_fill_all_hover"] = "Napełnij wszystkie maszyny tego typu",
				["$chestnetwork_fill_all_done"] = "Napełniono maszyny: $1 ($2)",
				["$chestnetwork_fill_all_short"] = "Za mało w skrzyniach dla maszyn: $1",
				["$chestnetwork_fill_all_busy"] = "Maszyny używane przez innego gracza, pominięte: $1",
				["$chestnetwork_repair_all_done"] = "Naprawiono przedmiotów: $1",
				["$chestnetwork_repair_all_hint"] = "$1 + klik: napraw wszystkie przedmioty",
				["$chestnetwork_store_hover"] = "Odłóż do sieci (przedmioty już obecne)",
				["$chestnetwork_store_not_in_network"] = "Ta skrzynia nie należy do sieci stołów warsztatowych",
				["$chestnetwork_store_preparing"] = "Przygotowywanie odkładania...",
				["$chestnetwork_store_nothing"] = "Nic do odłożenia",
				["$chestnetwork_store_full"] = "Skrzynia na $1 pełna",
				["$chestnetwork_store_done"] = "Odłożono przedmioty: $1, skrzynie: $2",
				["$chestnetwork_armor_fill_hover"] = "Ubierz stojak",
				["$chestnetwork_armor_swap_hover"] = "Zamień zbroję",
				["$chestnetwork_armor_nothing"] = "Nie znaleziono zbroi",
				["$chestnetwork_armor_preparing"] = "Przygotowywanie stojaka na zbroję...",
				["$chestnetwork_armor_busy"] = "Stojak na zbroję jest używany przez innego gracza, spróbuj ponownie",
				["$chestnetwork_slot_helmet"] = "Hełm",
				["$chestnetwork_slot_cape"] = "Peleryna",
				["$chestnetwork_slot_chest"] = "Tors",
				["$chestnetwork_slot_legs"] = "Nogi",
				["$chestnetwork_slot_hand_right"] = "Prawa ręka",
				["$chestnetwork_slot_hand_left"] = "Lewa ręka",
				["$chestnetwork_slot_back_right"] = "Plecy prawe",
				["$chestnetwork_slot_back_left"] = "Plecy lewe",
				["$chestnetwork_panel_chests"] = "Skrzynie w sieci",
				["$chestnetwork_panel_empty"] = "Brak przedmiotów w sieci",
				["$chestnetwork_panel_widen"] = "Poszerz panel",
				["$chestnetwork_panel_narrow"] = "Zwęź panel",
				["$chestnetwork_panel_no_target"] = "Żadna skrzynia sieci nie zawiera $1",
				["$chestnetwork_panel_protected"] = "Pasek szybkiego dostępu i założone przedmioty nigdy nie są odkładane",
				["$chestnetwork_category_materials"] = "Materiały",
				["$chestnetwork_category_to_prepare"] = "Do gotowania i fermentacji",
				["$chestnetwork_category_food"] = "Jedzenie",
				["$chestnetwork_category_meads"] = "Miody pitne i mikstury",
				["$chestnetwork_category_ammo"] = "Amunicja",
				["$chestnetwork_category_weapons"] = "Broń i tarcze",
				["$chestnetwork_category_armor"] = "Pancerze i akcesoria",
				["$chestnetwork_category_tools"] = "Narzędzia i pochodnie",
				["$chestnetwork_category_trophies"] = "Trofea",
				["$chestnetwork_category_fish"] = "Ryby",
				["$chestnetwork_category_misc"] = "Różne"
			},
			["Russian"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "Подготовка к заполнению...",
				["$chestnetwork_fill_machine_busy"] = "Машина используется другим игроком, попробуйте ещё раз",
				["$chestnetwork_fill_already_full"] = "Уже заполнено",
				["$chestnetwork_fill_nothing_to_add"] = "Нечего добавить",
				["$chestnetwork_fill_hover"] = "Заполнить из сундуков",
				["$chestnetwork_waiting_for_containers"] = "Сеть сундуков: ожидание сундуков других игроков...",
				["$chestnetwork_fill_all_hover"] = "Заполнить все такие машины",
				["$chestnetwork_fill_all_done"] = "Заполнено машин: $1 ($2)",
				["$chestnetwork_fill_all_short"] = "В сундуках не хватает для машин: $1",
				["$chestnetwork_fill_all_busy"] = "Машин занято другим игроком, пропущено: $1",
				["$chestnetwork_repair_all_done"] = "Починено предметов: $1",
				["$chestnetwork_repair_all_hint"] = "$1 + щелчок: починить все предметы",
				["$chestnetwork_store_hover"] = "Сложить в сеть (уже имеющиеся предметы)",
				["$chestnetwork_store_not_in_network"] = "Этот сундук не входит в сеть верстаков",
				["$chestnetwork_store_preparing"] = "Подготовка к размещению...",
				["$chestnetwork_store_nothing"] = "Нечего сложить",
				["$chestnetwork_store_full"] = "Сундук для $1 заполнен",
				["$chestnetwork_store_done"] = "Сложено предметов: $1, сундуков: $2",
				["$chestnetwork_armor_fill_hover"] = "Одеть стойку",
				["$chestnetwork_armor_swap_hover"] = "Обменяться бронёй",
				["$chestnetwork_armor_nothing"] = "Броня не найдена",
				["$chestnetwork_armor_preparing"] = "Подготовка стойки для брони...",
				["$chestnetwork_armor_busy"] = "Стойка для брони используется другим игроком, попробуйте ещё раз",
				["$chestnetwork_slot_helmet"] = "Шлем",
				["$chestnetwork_slot_cape"] = "Плащ",
				["$chestnetwork_slot_chest"] = "Торс",
				["$chestnetwork_slot_legs"] = "Ноги",
				["$chestnetwork_slot_hand_right"] = "Правая рука",
				["$chestnetwork_slot_hand_left"] = "Левая рука",
				["$chestnetwork_slot_back_right"] = "Спина справа",
				["$chestnetwork_slot_back_left"] = "Спина слева",
				["$chestnetwork_panel_chests"] = "Сундуки сети",
				["$chestnetwork_panel_empty"] = "В сети нет предметов",
				["$chestnetwork_panel_widen"] = "Расширить панель",
				["$chestnetwork_panel_narrow"] = "Сузить панель",
				["$chestnetwork_panel_no_target"] = "Ни один сундук сети не содержит $1",
				["$chestnetwork_panel_protected"] = "Панель быстрого доступа и надетые предметы никогда не убираются",
				["$chestnetwork_category_materials"] = "Материалы",
				["$chestnetwork_category_to_prepare"] = "Для готовки и брожения",
				["$chestnetwork_category_food"] = "Еда",
				["$chestnetwork_category_meads"] = "Медовуха и зелья",
				["$chestnetwork_category_ammo"] = "Боеприпасы",
				["$chestnetwork_category_weapons"] = "Оружие и щиты",
				["$chestnetwork_category_armor"] = "Броня и аксессуары",
				["$chestnetwork_category_tools"] = "Инструменты и факелы",
				["$chestnetwork_category_trophies"] = "Трофеи",
				["$chestnetwork_category_fish"] = "Рыба",
				["$chestnetwork_category_misc"] = "Разное"
			},
			["Chinese"] = new Dictionary<string, string>
			{
				["$chestnetwork_fill_preparing"] = "正在准备填充...",
				["$chestnetwork_fill_machine_busy"] = "机器正被其他玩家使用,请重试",
				["$chestnetwork_fill_already_full"] = "已满",
				["$chestnetwork_fill_nothing_to_add"] = "没有可添加的物品",
				["$chestnetwork_fill_hover"] = "从箱子中填充",
				["$chestnetwork_waiting_for_containers"] = "箱子网络:正在等待其他玩家持有的箱子...",
				["$chestnetwork_fill_all_hover"] = "填充所有同类机器",
				["$chestnetwork_fill_all_done"] = "已填充$1台机器:$2",
				["$chestnetwork_fill_all_short"] = "箱子中的物品不足以填充$1台机器",
				["$chestnetwork_fill_all_busy"] = "$1台机器正被其他玩家使用,已跳过",
				["$chestnetwork_repair_all_done"] = "已修复$1件物品",
				["$chestnetwork_repair_all_hint"] = "$1 + 点击:修复所有物品",
				["$chestnetwork_store_hover"] = "存入网络(已有的物品)",
				["$chestnetwork_store_not_in_network"] = "这个箱子不在工作台网络中",
				["$chestnetwork_store_preparing"] = "正在准备存放...",
				["$chestnetwork_store_nothing"] = "没有可存放的物品",
				["$chestnetwork_store_full"] = "$1箱子已满",
				["$chestnetwork_store_done"] = "已将$1件物品存入$2个箱子",
				["$chestnetwork_armor_fill_hover"] = "装备盔甲架",
				["$chestnetwork_armor_swap_hover"] = "交换盔甲",
				["$chestnetwork_armor_nothing"] = "未找到盔甲",
				["$chestnetwork_armor_preparing"] = "正在准备盔甲架...",
				["$chestnetwork_armor_busy"] = "盔甲架正被其他玩家使用,请重试",
				["$chestnetwork_slot_helmet"] = "头盔",
				["$chestnetwork_slot_cape"] = "披风",
				["$chestnetwork_slot_chest"] = "胸甲",
				["$chestnetwork_slot_legs"] = "腿甲",
				["$chestnetwork_slot_hand_right"] = "右手",
				["$chestnetwork_slot_hand_left"] = "左手",
				["$chestnetwork_slot_back_right"] = "背部右侧",
				["$chestnetwork_slot_back_left"] = "背部左侧",
				["$chestnetwork_panel_chests"] = "网络中的箱子",
				["$chestnetwork_panel_empty"] = "网络中没有物品",
				["$chestnetwork_panel_widen"] = "加宽面板",
				["$chestnetwork_panel_narrow"] = "缩窄面板",
				["$chestnetwork_panel_no_target"] = "网络中没有箱子存放$1",
				["$chestnetwork_panel_protected"] = "快捷栏和已装备的物品永远不会被存放",
				["$chestnetwork_category_materials"] = "材料",
				["$chestnetwork_category_to_prepare"] = "待烹饪和发酵",
				["$chestnetwork_category_food"] = "食物",
				["$chestnetwork_category_meads"] = "蜂蜜酒和药水",
				["$chestnetwork_category_ammo"] = "弹药",
				["$chestnetwork_category_weapons"] = "武器和盾牌",
				["$chestnetwork_category_armor"] = "盔甲和饰品",
				["$chestnetwork_category_tools"] = "工具和火把",
				["$chestnetwork_category_trophies"] = "战利品",
				["$chestnetwork_category_fish"] = "鱼",
				["$chestnetwork_category_misc"] = "杂项"
			}
		};

		public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> ByLanguage { get; } = Texts.ToDictionary<KeyValuePair<string, Dictionary<string, string>>, string, IReadOnlyDictionary<string, string>>((KeyValuePair<string, Dictionary<string, string>> language) => language.Key, (KeyValuePair<string, Dictionary<string, string>> language) => language.Value);
	}
	internal static class SettingsTexts
	{
		public const string Prefix = "chestnetwork_cfg";

		public static readonly IReadOnlyList<string> Categories = new string[6] { "Material", "Trophy", "Consumable", "Fish", "Ammo", "Misc" };

		public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> ByLanguage { get; } = new Dictionary<string, IReadOnlyDictionary<string, string>>
		{
			["English"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Network panel",
				["chestnetwork_cfg_networkpanel_enabled"] = "Network panel with the inventory",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "In the chest network, the inventory key also opens a panel with everything the network's chests hold: click an item to take a whole stack, Shift + click to choose the amount, Ctrl + click to take it straight to your inventory; drop an item of your inventory on it to store it in the chests that already hold it.",
				["chestnetwork_cfg_section_general"] = "General",
				["chestnetwork_cfg_section_containers"] = "Network chests",
				["chestnetwork_cfg_section_interaction"] = "Interaction",
				["chestnetwork_cfg_section_filling"] = "Filling machines",
				["chestnetwork_cfg_section_autorefuel"] = "Automatic refuel",
				["chestnetwork_cfg_section_quickstack"] = "Quick stack",
				["chestnetwork_cfg_section_armorstand"] = "Armor stand",
				["chestnetwork_cfg_general_enabled"] = "Use the chest network",
				["chestnetwork_cfg_general_enabled_desc"] = "Build and craft with the resources of the chests in the crafting station network.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Keep one of each item per chest",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Building, crafting and filling machines leave one unit of each item in every chest while other chests can provide it, so quick stack still finds that chest.",
				["chestnetwork_cfg_containers_usecarts"] = "Take from carts",
				["chestnetwork_cfg_containers_usecarts_desc"] = "Carts in the network count as chests: their content can be used. Ignored when the server keeps the chests.",
				["chestnetwork_cfg_containers_useships"] = "Take from ships",
				["chestnetwork_cfg_containers_useships_desc"] = "Ships in the network count as chests: their content can be used. Ignored when the server keeps the chests.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Consume equipped items",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Items you wear can be spent when building or crafting.",
				["chestnetwork_cfg_containers_chestreserve"] = "Units kept in each chest",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "With the chests kept by the server: units of each item every chest always keeps, never used for building or crafting, so quick stack still finds the chest. Imposed by the server; replaces \"Keep one of each item per chest\" there.",
				["chestnetwork_cfg_containers_openingsafetydelay"] = "Opening wait limit (ms)",
				["chestnetwork_cfg_containers_openingsafetydelay_desc"] = "With the chests kept by the server: when a player opens a chest that other players' credits stand on, the menu waits for those players to give the credits back (one round trip), at most this long for a player who stopped answering. Imposed by the server.",
				["chestnetwork_cfg_interaction_usealtinteract"] = "Shift + E actions",
				["chestnetwork_cfg_interaction_usealtinteract_desc"] = "The alternate use (Shift + E, gamepad included) fills machines, stores items and dresses armor stands.",
				["chestnetwork_cfg_interaction_shortcut"] = "Extra shortcut",
				["chestnetwork_cfg_interaction_shortcut_desc"] = "Additional key doing the same as Shift + E on the object under the crosshair.",
				["chestnetwork_cfg_interaction_fillall"] = "Fill all machines of a kind",
				["chestnetwork_cfg_interaction_fillall_desc"] = "On a machine, Shift + A (the key typing A, whatever the keyboard layout) fills every machine of the network using the same fuel (smelters, fires, torches...), nearest first. That key does nothing else meanwhile. Keyboard only.",
				["chestnetwork_cfg_interaction_repairall"] = "Repair everything at once",
				["chestnetwork_cfg_interaction_repairall_desc"] = "At a crafting station, Shift + click on the repair button repairs every repairable item of your inventory at once, with one message. Mouse only.",
				["chestnetwork_cfg_filling_enabled"] = "Fill machines",
				["chestnetwork_cfg_filling_enabled_desc"] = "Fill smelters and fires from the chests of the network.",
				["chestnetwork_cfg_filling_inventoryuse"] = "Use my inventory",
				["chestnetwork_cfg_filling_inventoryuse_desc"] = "Whether your inventory is used when filling machines: never, before or after the chests.",
				["chestnetwork_cfg_filling_minimumreserve"] = "Minimum reserve",
				["chestnetwork_cfg_filling_minimumreserve_desc"] = "Units of each item always left in the chests when filling machines.",
				["chestnetwork_cfg_autorefuel_enabled"] = "Refuel machines by themselves",
				["chestnetwork_cfg_autorefuel_enabled_desc"] = "Fires, torches, smelters and stone ovens take fuel from the chests of their own network each time they burn a unit. Never from a player's inventory. Imposed by the server.",
				["chestnetwork_cfg_autorefuel_minimumreserve"] = "Minimum reserve (refuel)",
				["chestnetwork_cfg_autorefuel_minimumreserve_desc"] = "Units of each fuel always left in the chests by the automatic refuel.",
				["chestnetwork_cfg_quickstack_enabled"] = "Quick stack",
				["chestnetwork_cfg_quickstack_enabled_desc"] = "Shift + E on a chest stores your items into the network chests that already hold them.",
				["chestnetwork_cfg_quickstack_includedcategories"] = "Stored categories",
				["chestnetwork_cfg_quickstack_includedcategories_desc"] = "Item types stored by quick stack. The hotbar row and equipped items are never stored.",
				["chestnetwork_cfg_armorstand_enabled"] = "Dress armor stands",
				["chestnetwork_cfg_armorstand_enabled_desc"] = "Shift + E on an armor stand dresses it, or swaps your armor with it.",
				["chestnetwork_cfg_armorstand_takefromhotbar"] = "Take from the hotbar",
				["chestnetwork_cfg_armorstand_takefromhotbar_desc"] = "Dressing an armor stand may take armor placed in the hotbar row.",
				["chestnetwork_cfg_armorstand_openonuse"] = "Open with E",
				["chestnetwork_cfg_armorstand_openonuse_desc"] = "E on an armor stand opens a panel with one cell per slot, instead of dropping the piece on the ground.",
				["chestnetwork_cfg_inventoryuse_never"] = "Never",
				["chestnetwork_cfg_inventoryuse_first"] = "Before the chests",
				["chestnetwork_cfg_inventoryuse_last"] = "After the chests",
				["chestnetwork_cfg_quickstack_includedcategories_material"] = "Materials",
				["chestnetwork_cfg_quickstack_includedcategories_trophy"] = "Trophies",
				["chestnetwork_cfg_quickstack_includedcategories_consumable"] = "Consumables",
				["chestnetwork_cfg_quickstack_includedcategories_fish"] = "Fish",
				["chestnetwork_cfg_quickstack_includedcategories_ammo"] = "Ammunition",
				["chestnetwork_cfg_quickstack_includedcategories_misc"] = "Miscellaneous",
				["chestnetwork_cfg_section_telemetry"] = "Telemetry",
				["chestnetwork_cfg_telemetry_enabled"] = "Share anonymous usage statistics",
				["chestnetwork_cfg_telemetry_enabled_desc"] = "Help improve ChestNetwork by sending anonymous usage statistics: features used and errors met. No personal data.",
				["chestnetwork_cfg_telemetry_consent_title"] = "Help improve ChestNetwork?",
				["chestnetwork_cfg_telemetry_consent_text"] = "ChestNetwork would like to collect anonymous usage statistics to improve the mod: which features are used, how often, and the errors met. No personal data is collected (no Steam ID, player name, world or position). You can change your choice at any time in Settings > Mods. Details on the mod page (Privacy and telemetry). Do you agree?"
			},
			["French"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Panneau Réseau",
				["chestnetwork_cfg_networkpanel_enabled"] = "Panneau Réseau avec l'inventaire",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "Dans le réseau de coffres, la touche de l'inventaire ouvre aussi un panneau avec tout le contenu des coffres du réseau : cliquez sur un objet pour prendre une pile entière, Maj + clic pour choisir la quantité, Ctrl + clic pour la prendre directement dans votre inventaire ; déposez-y un objet de votre inventaire pour le ranger dans les coffres qui en contiennent déjà.",
				["chestnetwork_cfg_section_general"] = "Général",
				["chestnetwork_cfg_section_containers"] = "Coffres du réseau",
				["chestnetwork_cfg_section_interaction"] = "Interaction",
				["chestnetwork_cfg_section_filling"] = "Remplissage des machines",
				["chestnetwork_cfg_section_autorefuel"] = "Recharge automatique",
				["chestnetwork_cfg_section_quickstack"] = "Rangement rapide",
				["chestnetwork_cfg_section_armorstand"] = "Porte-armure",
				["chestnetwork_cfg_general_enabled"] = "Utiliser le réseau de coffres",
				["chestnetwork_cfg_general_enabled_desc"] = "Construire et fabriquer avec les ressources des coffres du réseau d'établis.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Garder 1 exemplaire par coffre",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Construire, fabriquer et remplir les machines laisse 1 exemplaire de chaque objet dans chaque coffre tant que les autres coffres suffisent : le rangement rapide retrouve ainsi ce coffre.",
				["chestnetwork_cfg_containers_usecarts"] = "Puiser dans les chariots",
				["chestnetwork_cfg_containers_usecarts_desc"] = "Les chariots du réseau comptent comme des coffres : leur contenu peut être utilisé. Sans effet quand le serveur garde les coffres.",
				["chestnetwork_cfg_containers_useships"] = "Puiser dans les bateaux",
				["chestnetwork_cfg_containers_useships_desc"] = "Les bateaux du réseau comptent comme des coffres : leur contenu peut être utilisé. Sans effet quand le serveur garde les coffres.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Consommer les objets équipés",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Les objets que vous portez peuvent être dépensés pour construire ou fabriquer.",
				["chestnetwork_cfg_containers_chestreserve"] = "Unités gardées par coffre",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "Avec les coffres gardés par le serveur : unités de chaque objet que chaque coffre garde toujours, jamais utilisées pour construire ou fabriquer, pour que le rangement retrouve le coffre. Imposé par le serveur ; y remplace « Garder un exemplaire par coffre ».",
				["chestnetwork_cfg_containers_openingsafetydelay"] = "Attente maximale à l'ouverture (ms)",
				["chestnetwork_cfg_containers_openingsafetydelay_desc"] = "Avec les coffres gardés par le serveur : quand un joueur ouvre un coffre sur lequel reposent les crédits d'autres joueurs, le menu attend que ces joueurs les rendent (un aller-retour), au plus ce délai pour un joueur qui ne répond plus. Imposé par le serveur.",
				["chestnetwork_cfg_interaction_usealtinteract"] = "Actions Maj + E",
				["chestnetwork_cfg_interaction_usealtinteract_desc"] = "L'utilisation alternative (Maj + E, manette comprise) remplit les machines, range les objets et garnit les porte-armures.",
				["chestnetwork_cfg_interaction_shortcut"] = "Raccourci supplémentaire",
				["chestnetwork_cfg_interaction_shortcut_desc"] = "Touche supplémentaire qui fait la même chose que Maj + E sur l'objet visé.",
				["chestnetwork_cfg_interaction_fillall"] = "Remplir toutes les machines d'un type",
				["chestnetwork_cfg_interaction_fillall_desc"] = "Sur une machine, Maj + A (la touche qui tape A, quelle que soit la disposition du clavier) remplit toutes les machines du réseau qui utilisent le même combustible (fours, feux, torches...), de la plus proche à la plus éloignée. Cette touche ne fait rien d'autre pendant ce temps. Clavier seulement.",
				["chestnetwork_cfg_interaction_repairall"] = "Tout réparer d'un coup",
				["chestnetwork_cfg_interaction_repairall_desc"] = "À un établi, Maj + clic sur le bouton de réparation répare d'un coup tous les objets réparables de votre inventaire, avec un seul message. Souris seulement.",
				["chestnetwork_cfg_filling_enabled"] = "Remplir les machines",
				["chestnetwork_cfg_filling_enabled_desc"] = "Remplit les fours et les feux depuis les coffres du réseau.",
				["chestnetwork_cfg_filling_inventoryuse"] = "Utiliser mon inventaire",
				["chestnetwork_cfg_filling_inventoryuse_desc"] = "Si votre inventaire sert à remplir les machines : jamais, avant ou après les coffres.",
				["chestnetwork_cfg_filling_minimumreserve"] = "Réserve minimale",
				["chestnetwork_cfg_filling_minimumreserve_desc"] = "Unités de chaque objet toujours laissées dans les coffres lors du remplissage.",
				["chestnetwork_cfg_autorefuel_enabled"] = "Recharge automatique des machines",
				["chestnetwork_cfg_autorefuel_enabled_desc"] = "Feux, torches, fours et fours en pierre puisent leur combustible dans les coffres de leur réseau à chaque unité brûlée. Jamais dans l'inventaire d'un joueur. Imposé par le serveur.",
				["chestnetwork_cfg_autorefuel_minimumreserve"] = "Réserve minimale (recharge)",
				["chestnetwork_cfg_autorefuel_minimumreserve_desc"] = "Unités de chaque combustible toujours laissées dans les coffres par la recharge automatique.",
				["chestnetwork_cfg_quickstack_enabled"] = "Rangement rapide",
				["chestnetwork_cfg_quickstack_enabled_desc"] = "Maj + E sur un coffre range vos objets dans les coffres du réseau qui en contiennent déjà.",
				["chestnetwork_cfg_quickstack_includedcategories"] = "Catégories rangées",
				["chestnetwork_cfg_quickstack_includedcategories_desc"] = "Types d'objets rangés. La barre rapide et les objets équipés ne sont jamais rangés.",
				["chestnetwork_cfg_armorstand_enabled"] = "Garnir les porte-armures",
				["chestnetwork_cfg_armorstand_enabled_desc"] = "Maj + E sur un porte-armure le garnit, ou échange votre armure avec lui.",
				["chestnetwork_cfg_armorstand_takefromhotbar"] = "Prendre depuis la barre d'équipement",
				["chestnetwork_cfg_armorstand_takefromhotbar_desc"] = "Garnir un porte-armure peut prendre l'armure placée dans la barre d'équipement.",
				["chestnetwork_cfg_armorstand_openonuse"] = "Ouvrir avec E",
				["chestnetwork_cfg_armorstand_openonuse_desc"] = "E sur un porte-armure ouvre un panneau avec une case par emplacement, au lieu de faire tomber la pièce au sol.",
				["chestnetwork_cfg_inventoryuse_never"] = "Jamais",
				["chestnetwork_cfg_inventoryuse_first"] = "Avant les coffres",
				["chestnetwork_cfg_inventoryuse_last"] = "Après les coffres",
				["chestnetwork_cfg_quickstack_includedcategories_material"] = "Matériaux",
				["chestnetwork_cfg_quickstack_includedcategories_trophy"] = "Trophées",
				["chestnetwork_cfg_quickstack_includedcategories_consumable"] = "Consommables",
				["chestnetwork_cfg_quickstack_includedcategories_fish"] = "Poissons",
				["chestnetwork_cfg_quickstack_includedcategories_ammo"] = "Munitions",
				["chestnetwork_cfg_quickstack_includedcategories_misc"] = "Divers",
				["chestnetwork_cfg_section_telemetry"] = "Télémétrie",
				["chestnetwork_cfg_telemetry_enabled"] = "Partager des statistiques d'utilisation anonymes",
				["chestnetwork_cfg_telemetry_enabled_desc"] = "Aide à améliorer ChestNetwork en envoyant des statistiques d'utilisation anonymes : fonctions utilisées et erreurs rencontrées. Aucune donnée personnelle.",
				["chestnetwork_cfg_telemetry_consent_title"] = "Aider à améliorer ChestNetwork ?",
				["chestnetwork_cfg_telemetry_consent_text"] = "ChestNetwork souhaite collecter des statistiques d'utilisation anonymes pour améliorer le mod : fonctions utilisées, fréquence d'utilisation et erreurs rencontrées. Aucune donnée personnelle n'est collectée (ni identifiant Steam, ni nom de joueur, ni monde, ni position). Vous pouvez changer d'avis à tout moment dans Paramètres > Mods. Détails sur la page du mod (Privacy and telemetry). Acceptez-vous ?"
			},
			["German"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Netzwerk-Fenster",
				["chestnetwork_cfg_networkpanel_enabled"] = "Netzwerk-Fenster mit dem Inventar",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "Im Truhennetzwerk öffnet die Inventartaste auch ein Fenster mit allem, was die Truhen des Netzwerks enthalten: Klicke auf einen Gegenstand, um einen ganzen Stapel zu nehmen, Umschalt + Klick, um die Menge zu wählen, Strg + Klick, um ihn direkt ins Inventar zu nehmen; lege einen Gegenstand aus deinem Inventar darauf, um ihn in die Truhen zu legen, die ihn bereits enthalten.",
				["chestnetwork_cfg_section_general"] = "Allgemein",
				["chestnetwork_cfg_section_containers"] = "Truhen im Netz",
				["chestnetwork_cfg_section_interaction"] = "Interaktion",
				["chestnetwork_cfg_section_filling"] = "Maschinen befüllen",
				["chestnetwork_cfg_section_autorefuel"] = "Automatisches Nachfüllen",
				["chestnetwork_cfg_section_quickstack"] = "Schnell verstauen",
				["chestnetwork_cfg_section_armorstand"] = "Rüstungsständer",
				["chestnetwork_cfg_general_enabled"] = "Truhennetz verwenden",
				["chestnetwork_cfg_general_enabled_desc"] = "Mit den Ressourcen der Truhen im Werkbanknetz bauen und herstellen.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Ein Exemplar pro Truhe behalten",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Bauen, Herstellen und Befüllen lassen von jedem Gegenstand ein Exemplar in jeder Truhe, solange andere Truhen genug liefern, damit „Schnell verstauen“ diese Truhe weiterhin findet.",
				["chestnetwork_cfg_containers_usecarts"] = "Aus Karren nehmen",
				["chestnetwork_cfg_containers_usecarts_desc"] = "Karren im Netz zählen als Truhen: ihr Inhalt kann verwendet werden. Ohne Wirkung, wenn der Server die Truhen verwaltet.",
				["chestnetwork_cfg_containers_useships"] = "Aus Schiffen nehmen",
				["chestnetwork_cfg_containers_useships_desc"] = "Schiffe im Netz zählen als Truhen: ihr Inhalt kann verwendet werden. Ohne Wirkung, wenn der Server die Truhen verwaltet.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Ausgerüstete Gegenstände verbrauchen",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Getragene Gegenstände können beim Bauen oder Herstellen verbraucht werden.",
				["chestnetwork_cfg_containers_chestreserve"] = "Behaltene Einheiten pro Truhe",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "Wenn der Server die Truhen hält: Einheiten jedes Gegenstands, die jede Truhe immer behält und die nie zum Bauen oder Herstellen verwendet werden, damit das Einsortieren die Truhe weiterhin findet. Vom Server vorgegeben; ersetzt dort „Eins pro Truhe behalten“.",
				["chestnetwork_cfg_containers_openingsafetydelay"] = "Maximale Wartezeit beim Öffnen (ms)",
				["chestnetwork_cfg_containers_openingsafetydelay_desc"] = "Wenn der Server die Truhen hält: Öffnet ein Spieler eine Truhe, auf der Guthaben anderer Spieler beruhen, wartet das Menü, bis diese Spieler sie zurückgeben (ein Hin und Zurück), höchstens so lange bei einem Spieler, der nicht mehr antwortet. Vom Server vorgegeben.",
				["chestnetwork_cfg_interaction_usealtinteract"] = "Umschalt + E Aktionen",
				["chestnetwork_cfg_interaction_usealtinteract_desc"] = "Die alternative Benutzung (Umschalt + E, auch Gamepad) befüllt Maschinen, verstaut Gegenstände und bestückt Rüstungsständer.",
				["chestnetwork_cfg_interaction_shortcut"] = "Zusätzliche Taste",
				["chestnetwork_cfg_interaction_shortcut_desc"] = "Zusätzliche Taste, die auf das anvisierte Objekt dasselbe wie Umschalt + E bewirkt.",
				["chestnetwork_cfg_interaction_fillall"] = "Alle Maschinen einer Art befüllen",
				["chestnetwork_cfg_interaction_fillall_desc"] = "Befüllt auf einer Maschine mit Umschalt + A (die Taste, die A schreibt, unabhängig vom Tastaturlayout) alle Maschinen des Netzwerks mit demselben Brennstoff (Öfen, Feuer, Fackeln...), die nächste zuerst. Diese Taste bewirkt dabei nichts anderes. Nur Tastatur.",
				["chestnetwork_cfg_interaction_repairall"] = "Alles auf einmal reparieren",
				["chestnetwork_cfg_interaction_repairall_desc"] = "An einer Werkbank repariert Umschalt + Klick auf die Reparaturschaltfläche alle reparierbaren Gegenstände deines Inventars auf einmal, mit einer einzigen Meldung. Nur Maus.",
				["chestnetwork_cfg_filling_enabled"] = "Maschinen befüllen",
				["chestnetwork_cfg_filling_enabled_desc"] = "Befüllt Öfen und Feuer aus den Truhen des Netzes.",
				["chestnetwork_cfg_filling_inventoryuse"] = "Mein Inventar verwenden",
				["chestnetwork_cfg_filling_inventoryuse_desc"] = "Ob dein Inventar beim Befüllen von Maschinen genutzt wird: nie, vor oder nach den Truhen.",
				["chestnetwork_cfg_filling_minimumreserve"] = "Mindestreserve",
				["chestnetwork_cfg_filling_minimumreserve_desc"] = "Einheiten jedes Gegenstands, die beim Befüllen immer in den Truhen bleiben.",
				["chestnetwork_cfg_autorefuel_enabled"] = "Maschinen selbst nachfüllen",
				["chestnetwork_cfg_autorefuel_enabled_desc"] = "Feuer, Fackeln, Öfen und Steinöfen nehmen bei jeder verbrannten Einheit Brennstoff aus den Truhen ihres Netzes. Nie aus dem Inventar eines Spielers. Vom Server vorgegeben.",
				["chestnetwork_cfg_autorefuel_minimumreserve"] = "Mindestreserve (Nachfüllen)",
				["chestnetwork_cfg_autorefuel_minimumreserve_desc"] = "Einheiten jedes Brennstoffs, die das automatische Nachfüllen immer in den Truhen lässt.",
				["chestnetwork_cfg_quickstack_enabled"] = "Schnell verstauen",
				["chestnetwork_cfg_quickstack_enabled_desc"] = "Umschalt + E auf eine Truhe verstaut deine Gegenstände in den Netztruhen, die sie bereits enthalten.",
				["chestnetwork_cfg_quickstack_includedcategories"] = "Verstaute Kategorien",
				["chestnetwork_cfg_quickstack_includedcategories_desc"] = "Verstaute Gegenstandstypen. Schnellleiste und ausgerüstete Gegenstände werden nie verstaut.",
				["chestnetwork_cfg_armorstand_enabled"] = "Rüstungsständer bestücken",
				["chestnetwork_cfg_armorstand_enabled_desc"] = "Umschalt + E auf einen Rüstungsständer bestückt ihn oder tauscht deine Rüstung mit ihm.",
				["chestnetwork_cfg_armorstand_takefromhotbar"] = "Aus der Schnellleiste nehmen",
				["chestnetwork_cfg_armorstand_takefromhotbar_desc"] = "Beim Bestücken eines Rüstungsständers darf Rüstung aus der Schnellleiste genommen werden.",
				["chestnetwork_cfg_armorstand_openonuse"] = "Mit E öffnen",
				["chestnetwork_cfg_armorstand_openonuse_desc"] = "E auf einen Rüstungsständer öffnet ein Fenster mit einem Feld pro Platz, statt das Teil auf den Boden fallen zu lassen.",
				["chestnetwork_cfg_inventoryuse_never"] = "Nie",
				["chestnetwork_cfg_inventoryuse_first"] = "Vor den Truhen",
				["chestnetwork_cfg_inventoryuse_last"] = "Nach den Truhen",
				["chestnetwork_cfg_quickstack_includedcategories_material"] = "Materialien",
				["chestnetwork_cfg_quickstack_includedcategories_trophy"] = "Trophäen",
				["chestnetwork_cfg_quickstack_includedcategories_consumable"] = "Verbrauchsgüter",
				["chestnetwork_cfg_quickstack_includedcategories_fish"] = "Fische",
				["chestnetwork_cfg_quickstack_includedcategories_ammo"] = "Munition",
				["chestnetwork_cfg_quickstack_includedcategories_misc"] = "Sonstiges",
				["chestnetwork_cfg_section_telemetry"] = "Telemetrie",
				["chestnetwork_cfg_telemetry_enabled"] = "Anonyme Nutzungsstatistiken teilen",
				["chestnetwork_cfg_telemetry_enabled_desc"] = "Hilf, ChestNetwork zu verbessern, indem anonyme Nutzungsstatistiken gesendet werden: genutzte Funktionen und aufgetretene Fehler. Keine persönlichen Daten.",
				["chestnetwork_cfg_telemetry_consent_title"] = "ChestNetwork verbessern helfen?",
				["chestnetwork_cfg_telemetry_consent_text"] = "ChestNetwork möchte anonyme Nutzungsstatistiken sammeln, um den Mod zu verbessern: genutzte Funktionen, wie oft, und aufgetretene Fehler. Es werden keine persönlichen Daten gesammelt (keine Steam-ID, kein Spielername, keine Welt, keine Position). Du kannst deine Wahl jederzeit unter Einstellungen > Mods ändern. Details auf der Seite des Mods (Privacy and telemetry). Bist du einverstanden?"
			},
			["Spanish"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Panel de la red",
				["chestnetwork_cfg_networkpanel_enabled"] = "Panel de la red con el inventario",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "En la red de cofres, la tecla del inventario también abre un panel con todo lo que contienen los cofres de la red: haz clic en un objeto para tomar una pila entera, Mayús + clic para elegir la cantidad, Ctrl + clic para tomarlo directamente en tu inventario; suelta en él un objeto de tu inventario para guardarlo en los cofres que ya lo contienen.",
				["chestnetwork_cfg_section_general"] = "General",
				["chestnetwork_cfg_section_containers"] = "Cofres de la red",
				["chestnetwork_cfg_section_interaction"] = "Interacción",
				["chestnetwork_cfg_section_filling"] = "Rellenar máquinas",
				["chestnetwork_cfg_section_autorefuel"] = "Recarga automática",
				["chestnetwork_cfg_section_quickstack"] = "Guardado rápido",
				["chestnetwork_cfg_section_armorstand"] = "Soporte de armadura",
				["chestnetwork_cfg_general_enabled"] = "Usar la red de cofres",
				["chestnetwork_cfg_general_enabled_desc"] = "Construir y fabricar con los recursos de los cofres de la red de mesas de trabajo.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Dejar 1 unidad por cofre",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Construir, fabricar y rellenar máquinas deja 1 unidad de cada objeto en cada cofre mientras otros cofres basten, para que el guardado rápido siga encontrando ese cofre.",
				["chestnetwork_cfg_containers_usecarts"] = "Tomar de los carros",
				["chestnetwork_cfg_containers_usecarts_desc"] = "Los carros de la red cuentan como cofres: su contenido se puede usar. Sin efecto cuando el servidor guarda los cofres.",
				["chestnetwork_cfg_containers_useships"] = "Tomar de los barcos",
				["chestnetwork_cfg_containers_useships_desc"] = "Los barcos de la red cuentan como cofres: su contenido se puede usar. Sin efecto cuando el servidor guarda los cofres.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Consumir objetos equipados",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Los objetos que llevas puestos se pueden gastar al construir o fabricar.",
				["chestnetwork_cfg_containers_chestreserve"] = "Unidades guardadas por cofre",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "Con los cofres guardados por el servidor: unidades de cada objeto que cada cofre conserva siempre, nunca usadas para construir o fabricar, para que el guardado rápido siga encontrando el cofre. Impuesto por el servidor; ahí sustituye a «Guardar uno de cada objeto por cofre».",
				["chestnetwork_cfg_containers_openingsafetydelay"] = "Espera máxima al abrir (ms)",
				["chestnetwork_cfg_containers_openingsafetydelay_desc"] = "Con los cofres guardados por el servidor: cuando un jugador abre un cofre en el que se apoyan créditos de otros jugadores, el menú espera a que esos jugadores los devuelvan (una ida y vuelta), como máximo este tiempo para un jugador que ya no responde. Impuesto por el servidor.",
				["chestnetwork_cfg_interaction_usealtinteract"] = "Acciones Mayús + E",
				["chestnetwork_cfg_interaction_usealtinteract_desc"] = "El uso alternativo (Mayús + E, mando incluido) rellena máquinas, guarda objetos y equipa soportes de armadura.",
				["chestnetwork_cfg_interaction_shortcut"] = "Atajo adicional",
				["chestnetwork_cfg_interaction_shortcut_desc"] = "Tecla adicional que hace lo mismo que Mayús + E sobre el objeto apuntado.",
				["chestnetwork_cfg_interaction_fillall"] = "Llenar todas las máquinas de un tipo",
				["chestnetwork_cfg_interaction_fillall_desc"] = "Sobre una máquina, Mayús + A (la tecla que escribe A, sea cual sea la distribución del teclado) llena todas las máquinas de la red que usan el mismo combustible (hornos, fuegos, antorchas...), de la más cercana a la más lejana. Mientras tanto esa tecla no hace nada más. Solo teclado.",
				["chestnetwork_cfg_interaction_repairall"] = "Reparar todo de una vez",
				["chestnetwork_cfg_interaction_repairall_desc"] = "En una estación de trabajo, Mayús + clic en el botón de reparar repara de una vez todos los objetos reparables de tu inventario, con un solo mensaje. Solo ratón.",
				["chestnetwork_cfg_filling_enabled"] = "Rellenar máquinas",
				["chestnetwork_cfg_filling_enabled_desc"] = "Rellena hornos y fuegos desde los cofres de la red.",
				["chestnetwork_cfg_filling_inventoryuse"] = "Usar mi inventario",
				["chestnetwork_cfg_filling_inventoryuse_desc"] = "Si tu inventario se usa al rellenar máquinas: nunca, antes o después de los cofres.",
				["chestnetwork_cfg_filling_minimumreserve"] = "Reserva mínima",
				["chestnetwork_cfg_filling_minimumreserve_desc"] = "Unidades de cada objeto que siempre se dejan en los cofres al rellenar.",
				["chestnetwork_cfg_autorefuel_enabled"] = "Recargar las máquinas solas",
				["chestnetwork_cfg_autorefuel_enabled_desc"] = "Hogueras, antorchas, hornos y hornos de piedra toman combustible de los cofres de su red cada vez que queman una unidad. Nunca del inventario de un jugador. Impuesto por el servidor.",
				["chestnetwork_cfg_autorefuel_minimumreserve"] = "Reserva mínima (recarga)",
				["chestnetwork_cfg_autorefuel_minimumreserve_desc"] = "Unidades de cada combustible que la recarga automática deja siempre en los cofres.",
				["chestnetwork_cfg_quickstack_enabled"] = "Guardado rápido",
				["chestnetwork_cfg_quickstack_enabled_desc"] = "Mayús + E sobre un cofre guarda tus objetos en los cofres de la red que ya los contienen.",
				["chestnetwork_cfg_quickstack_includedcategories"] = "Categorías guardadas",
				["chestnetwork_cfg_quickstack_includedcategories_desc"] = "Tipos de objetos guardados. La barra rápida y los objetos equipados nunca se guardan.",
				["chestnetwork_cfg_armorstand_enabled"] = "Equipar soportes de armadura",
				["chestnetwork_cfg_armorstand_enabled_desc"] = "Mayús + E sobre un soporte de armadura lo equipa o intercambia tu armadura con él.",
				["chestnetwork_cfg_armorstand_takefromhotbar"] = "Tomar de la barra rápida",
				["chestnetwork_cfg_armorstand_takefromhotbar_desc"] = "Equipar un soporte de armadura puede tomar armadura de la barra rápida.",
				["chestnetwork_cfg_armorstand_openonuse"] = "Abrir con E",
				["chestnetwork_cfg_armorstand_openonuse_desc"] = "E sobre un soporte de armadura abre un panel con una casilla por ranura, en lugar de dejar caer la pieza al suelo.",
				["chestnetwork_cfg_inventoryuse_never"] = "Nunca",
				["chestnetwork_cfg_inventoryuse_first"] = "Antes de los cofres",
				["chestnetwork_cfg_inventoryuse_last"] = "Después de los cofres",
				["chestnetwork_cfg_quickstack_includedcategories_material"] = "Materiales",
				["chestnetwork_cfg_quickstack_includedcategories_trophy"] = "Trofeos",
				["chestnetwork_cfg_quickstack_includedcategories_consumable"] = "Consumibles",
				["chestnetwork_cfg_quickstack_includedcategories_fish"] = "Peces",
				["chestnetwork_cfg_quickstack_includedcategories_ammo"] = "Munición",
				["chestnetwork_cfg_quickstack_includedcategories_misc"] = "Varios",
				["chestnetwork_cfg_section_telemetry"] = "Telemetría",
				["chestnetwork_cfg_telemetry_enabled"] = "Compartir estadísticas de uso anónimas",
				["chestnetwork_cfg_telemetry_enabled_desc"] = "Ayuda a mejorar ChestNetwork enviando estadísticas de uso anónimas: funciones usadas y errores encontrados. Sin datos personales.",
				["chestnetwork_cfg_telemetry_consent_title"] = "¿Ayudar a mejorar ChestNetwork?",
				["chestnetwork_cfg_telemetry_consent_text"] = "ChestNetwork quiere recopilar estadísticas de uso anónimas para mejorar el mod: qué funciones se usan, con qué frecuencia y los errores encontrados. No se recopila ningún dato personal (ni ID de Steam, ni nombre de jugador, ni mundo, ni posición). Puedes cambiar tu elección en cualquier momento en Ajustes > Mods. Detalles en la página del mod (Privacy and telemetry). ¿Aceptas?"
			},
			["Portuguese_Brazilian"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Painel da rede",
				["chestnetwork_cfg_networkpanel_enabled"] = "Painel da rede com o inventário",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "Na rede de baús, a tecla do inventário também abre um painel com tudo o que os baús da rede contêm: clique em um item para pegar uma pilha inteira, Shift + clique para escolher a quantidade, Ctrl + clique para pegá-lo direto no inventário; solte nele um item do seu inventário para guardá-lo nos baús que já o contêm.",
				["chestnetwork_cfg_section_general"] = "Geral",
				["chestnetwork_cfg_section_containers"] = "Baús da rede",
				["chestnetwork_cfg_section_interaction"] = "Interação",
				["chestnetwork_cfg_section_filling"] = "Abastecer máquinas",
				["chestnetwork_cfg_section_autorefuel"] = "Recarga automática",
				["chestnetwork_cfg_section_quickstack"] = "Guardar rápido",
				["chestnetwork_cfg_section_armorstand"] = "Suporte de armadura",
				["chestnetwork_cfg_general_enabled"] = "Usar a rede de baús",
				["chestnetwork_cfg_general_enabled_desc"] = "Construir e fabricar com os recursos dos baús da rede de bancadas.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Manter 1 unidade por baú",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Construir, fabricar e abastecer máquinas deixa 1 unidade de cada item em cada baú enquanto outros baús bastarem, para que o \"Guardar rápido\" continue encontrando esse baú.",
				["chestnetwork_cfg_containers_usecarts"] = "Pegar das carroças",
				["chestnetwork_cfg_containers_usecarts_desc"] = "As carroças da rede contam como baús: seu conteúdo pode ser usado. Sem efeito quando o servidor guarda os baús.",
				["chestnetwork_cfg_containers_useships"] = "Pegar dos barcos",
				["chestnetwork_cfg_containers_useships_desc"] = "Os barcos da rede contam como baús: seu conteúdo pode ser usado. Sem efeito quando o servidor guarda os baús.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Consumir itens equipados",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Os itens que você veste podem ser gastos ao construir ou fabricar.",
				["chestnetwork_cfg_containers_chestreserve"] = "Unidades mantidas por baú",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "Com os baús mantidos pelo servidor: unidades de cada item que cada baú sempre mantém, nunca usadas para construir ou fabricar, para que o guardar rápido ainda encontre o baú. Imposto pelo servidor; ali substitui \"Manter um de cada item por baú\".",
				["chestnetwork_cfg_containers_openingsafetydelay"] = "Espera máxima ao abrir (ms)",
				["chestnetwork_cfg_containers_openingsafetydelay_desc"] = "Com os baús mantidos pelo servidor: quando um jogador abre um baú em que se apoiam créditos de outros jogadores, o menu espera que esses jogadores os devolvam (uma ida e volta), no máximo este tempo para um jogador que deixou de responder. Imposto pelo servidor.",
				["chestnetwork_cfg_interaction_usealtinteract"] = "Ações Shift + E",
				["chestnetwork_cfg_interaction_usealtinteract_desc"] = "O uso alternativo (Shift + E, controle incluído) abastece máquinas, guarda itens e veste suportes de armadura.",
				["chestnetwork_cfg_interaction_shortcut"] = "Atalho adicional",
				["chestnetwork_cfg_interaction_shortcut_desc"] = "Tecla adicional que faz o mesmo que Shift + E no objeto mirado.",
				["chestnetwork_cfg_interaction_fillall"] = "Abastecer todas as máquinas de um tipo",
				["chestnetwork_cfg_interaction_fillall_desc"] = "Em uma máquina, Shift + A (a tecla que digita A, seja qual for o layout do teclado) abastece todas as máquinas da rede que usam o mesmo combustível (fornos, fogueiras, tochas...), da mais próxima à mais distante. Enquanto isso, essa tecla não faz mais nada. Apenas teclado.",
				["chestnetwork_cfg_interaction_repairall"] = "Reparar tudo de uma vez",
				["chestnetwork_cfg_interaction_repairall_desc"] = "Em uma estação de trabalho, Shift + clique no botão de reparo repara de uma vez todos os itens reparáveis do seu inventário, com uma única mensagem. Somente mouse.",
				["chestnetwork_cfg_filling_enabled"] = "Abastecer máquinas",
				["chestnetwork_cfg_filling_enabled_desc"] = "Abastece fornos e fogueiras com os baús da rede.",
				["chestnetwork_cfg_filling_inventoryuse"] = "Usar meu inventário",
				["chestnetwork_cfg_filling_inventoryuse_desc"] = "Se o seu inventário é usado ao abastecer máquinas: nunca, antes ou depois dos baús.",
				["chestnetwork_cfg_filling_minimumreserve"] = "Reserva mínima",
				["chestnetwork_cfg_filling_minimumreserve_desc"] = "Unidades de cada item sempre deixadas nos baús ao abastecer.",
				["chestnetwork_cfg_autorefuel_enabled"] = "Recarregar as máquinas sozinhas",
				["chestnetwork_cfg_autorefuel_enabled_desc"] = "Fogueiras, tochas, fornalhas e fornos de pedra pegam combustível dos baús da própria rede a cada unidade queimada. Nunca do inventário de um jogador. Imposto pelo servidor.",
				["chestnetwork_cfg_autorefuel_minimumreserve"] = "Reserva mínima (recarga)",
				["chestnetwork_cfg_autorefuel_minimumreserve_desc"] = "Unidades de cada combustível que a recarga automática sempre deixa nos baús.",
				["chestnetwork_cfg_quickstack_enabled"] = "Guardar rápido",
				["chestnetwork_cfg_quickstack_enabled_desc"] = "Shift + E em um baú guarda seus itens nos baús da rede que já os contêm.",
				["chestnetwork_cfg_quickstack_includedcategories"] = "Categorias guardadas",
				["chestnetwork_cfg_quickstack_includedcategories_desc"] = "Tipos de item guardados. A barra rápida e os itens equipados nunca são guardados.",
				["chestnetwork_cfg_armorstand_enabled"] = "Vestir suportes de armadura",
				["chestnetwork_cfg_armorstand_enabled_desc"] = "Shift + E em um suporte de armadura o veste ou troca sua armadura com ele.",
				["chestnetwork_cfg_armorstand_takefromhotbar"] = "Pegar da barra rápida",
				["chestnetwork_cfg_armorstand_takefromhotbar_desc"] = "Vestir um suporte de armadura pode pegar armadura da barra rápida.",
				["chestnetwork_cfg_armorstand_openonuse"] = "Abrir com E",
				["chestnetwork_cfg_armorstand_openonuse_desc"] = "E em um suporte de armadura abre um painel com um espaço por encaixe, em vez de derrubar a peça no chão.",
				["chestnetwork_cfg_inventoryuse_never"] = "Nunca",
				["chestnetwork_cfg_inventoryuse_first"] = "Antes dos baús",
				["chestnetwork_cfg_inventoryuse_last"] = "Depois dos baús",
				["chestnetwork_cfg_quickstack_includedcategories_material"] = "Materiais",
				["chestnetwork_cfg_quickstack_includedcategories_trophy"] = "Troféus",
				["chestnetwork_cfg_quickstack_includedcategories_consumable"] = "Consumíveis",
				["chestnetwork_cfg_quickstack_includedcategories_fish"] = "Peixes",
				["chestnetwork_cfg_quickstack_includedcategories_ammo"] = "Munição",
				["chestnetwork_cfg_quickstack_includedcategories_misc"] = "Diversos",
				["chestnetwork_cfg_section_telemetry"] = "Telemetria",
				["chestnetwork_cfg_telemetry_enabled"] = "Compartilhar estatísticas de uso anônimas",
				["chestnetwork_cfg_telemetry_enabled_desc"] = "Ajude a melhorar o ChestNetwork enviando estatísticas de uso anônimas: recursos usados e erros encontrados. Nenhum dado pessoal.",
				["chestnetwork_cfg_telemetry_consent_title"] = "Ajudar a melhorar o ChestNetwork?",
				["chestnetwork_cfg_telemetry_consent_text"] = "O ChestNetwork gostaria de coletar estatísticas de uso anônimas para melhorar o mod: quais recursos são usados, com que frequência e os erros encontrados. Nenhum dado pessoal é coletado (nem ID Steam, nem nome do jogador, nem mundo, nem posição). Você pode mudar sua escolha a qualquer momento em Configurações > Mods. Detalhes na página do mod (Privacy and telemetry). Você concorda?"
			},
			["Polish"] = new Dictionary<string, string>
			{
				["chestnetwork_cfg_section_networkpanel"] = "Panel sieci",
				["chestnetwork_cfg_networkpanel_enabled"] = "Panel sieci z ekwipunkiem",
				["chestnetwork_cfg_networkpanel_enabled_desc"] = "W sieci skrzyń klawisz ekwipunku otwiera też panel z całą zawartością skrzyń sieci: kliknij przedmiot, aby wziąć cały stos, Shift + klik, aby wybrać ilość, Ctrl + klik, aby wziąć go prosto do ekwipunku; upuść na nim przedmiot z ekwipunku, aby odłożyć go do skrzyń, które już go zawierają.",
				["chestnetwork_cfg_section_general"] = "Ogólne",
				["chestnetwork_cfg_section_containers"] = "Skrzynie w sieci",
				["chestnetwork_cfg_section_interaction"] = "Interakcja",
				["chestnetwork_cfg_section_filling"] = "Napełnianie maszyn",
				["chestnetwork_cfg_section_autorefuel"] = "Automatyczne uzupełnianie",
				["chestnetwork_cfg_section_quickstack"] = "Szybkie odkładanie",
				["chestnetwork_cfg_section_armorstand"] = "Stojak na zbroję",
				["chestnetwork_cfg_general_enabled"] = "Używaj sieci skrzyń",
				["chestnetwork_cfg_general_enabled_desc"] = "Buduj i wytwarzaj z zasobów skrzyń w sieci stołów warsztatowych.",
				["chestnetwork_cfg_general_keeponeperchest"] = "Zostaw 1 sztukę w każdej skrzyni",
				["chestnetwork_cfg_general_keeponeperchest_desc"] = "Budowanie, wytwarzanie i napełnianie maszyn zostawia 1 sztukę każdego przedmiotu w każdej skrzyni, dopóki inne skrzynie wystarczają, aby szybkie odkładanie nadal znajdowało tę skrzynię.",
				["chestnetwork_cfg_containers_usecarts"] = "Bierz z wozów",
				["chestnetwork_cfg_containers_usecarts_desc"] = "Wozy w sieci liczą się jako skrzynie: ich zawartość może zostać użyta. Bez efektu, gdy serwer przechowuje skrzynie.",
				["chestnetwork_cfg_containers_useships"] = "Bierz ze statków",
				["chestnetwork_cfg_containers_useships_desc"] = "Statki w sieci liczą się jako skrzynie: ich zawartość może zostać użyta. Bez efektu, gdy serwer przechowuje skrzynie.",
				["chestnetwork_cfg_containers_allowequippeditems"] = "Zużywaj założone przedmioty",
				["chestnetwork_cfg_containers_allowequippeditems_desc"] = "Noszone przedmioty mogą zostać zużyte przy budowaniu lub wytwarzaniu.",
				["chestnetwork_cfg_containers_chestreserve"] = "Jednostki zostawiane w skrzyni",
				["chestnetwork_cfg_containers_chestreserve_desc"] = "Gdy serwer przechowuje s

plugins/ChestNetwork.Core.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using ChestNetwork.Core.Armor;
using ChestNetwork.Core.Credit;
using ChestNetwork.Core.Deposit;
using ChestNetwork.Core.Filling;
using ChestNetwork.Core.Internal;
using ChestNetwork.Core.Panel;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChestNetwork.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+62fdcf3d2084b41ec9a10e4e7b2c8ce48e5480d7")]
[assembly: AssemblyProduct("ChestNetwork.Core")]
[assembly: AssemblyTitle("ChestNetwork.Core")]
[assembly: InternalsVisibleTo("ChestNetwork.Core.Tests")]
[assembly: InternalsVisibleTo("ChestNetwork.Plugin")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace ChestNetwork.Core
{
	public enum ContainerKind
	{
		Chest,
		Cart,
		Ship,
		Other
	}
	public sealed record ContainerSnapshot
	{
		public string Id { get; init; }

		public Vector3 Position { get; init; }

		public ContainerKind Kind { get; init; }

		public bool IsInUse { get; init; }

		public bool IsAccessible { get; init; }

		public int SlotCount { get; init; }

		public IReadOnlyList<ItemStack> Items
		{
			get
			{
				return _items;
			}
			init
			{
				_items = CopyItems(value);
			}
		}

		private readonly IReadOnlyList<ItemStack> _items = Array.Empty<ItemStack>();

		public ContainerSnapshot(string id, Vector3 position, ContainerKind kind, IEnumerable<ItemStack?>? items = null, bool isInUse = false, bool isAccessible = true, int slotCount = 0)
		{
			Id = id;
			Position = position;
			Kind = kind;
			Items = CopyItems(items);
			IsInUse = isInUse;
			IsAccessible = isAccessible;
			SlotCount = slotCount;
		}

		public bool Equals(ContainerSnapshot? other)
		{
			if ((object)other == null)
			{
				return false;
			}
			if (string.Equals(Id, other.Id, StringComparison.Ordinal) && Position.Equals(other.Position) && Kind == other.Kind && IsInUse == other.IsInUse && IsAccessible == other.IsAccessible && SlotCount == other.SlotCount)
			{
				return HaveSameItems(_items, other._items);
			}
			return false;
		}

		public override int GetHashCode()
		{
			int num = 0;
			foreach (ItemStack item in _items)
			{
				num += item.GetHashCode();
			}
			return HashCode.Combine(Id, Position, Kind, IsInUse, IsAccessible, SlotCount, _items.Count, num);
		}

		private static IReadOnlyList<ItemStack> CopyItems(IEnumerable<ItemStack?>? items)
		{
			if (items == null)
			{
				return Array.Empty<ItemStack>();
			}
			return (from item in items
				where (object)item != null
				select (item)).ToArray();
		}

		private static bool HaveSameItems(IReadOnlyList<ItemStack> left, IReadOnlyList<ItemStack> right)
		{
			if (left.Count != right.Count)
			{
				return false;
			}
			Dictionary<ItemStack, int> dictionary = new Dictionary<ItemStack, int>();
			foreach (ItemStack item in left)
			{
				dictionary.TryGetValue(item, out var value);
				dictionary[item] = value + 1;
			}
			foreach (ItemStack item2 in right)
			{
				if (!dictionary.TryGetValue(item2, out var value2) || value2 == 0)
				{
					return false;
				}
				dictionary[item2] = value2 - 1;
			}
			return true;
		}

		[CompilerGenerated]
		private bool PrintMembers(StringBuilder builder)
		{
			RuntimeHelpers.EnsureSufficientExecutionStack();
			builder.Append("Id = ");
			builder.Append((object?)Id);
			builder.Append(", Position = ");
			builder.Append(Position.ToString());
			builder.Append(", Kind = ");
			builder.Append(Kind.ToString());
			builder.Append(", IsInUse = ");
			builder.Append(IsInUse.ToString());
			builder.Append(", IsAccessible = ");
			builder.Append(IsAccessible.ToString());
			builder.Append(", SlotCount = ");
			builder.Append(SlotCount.ToString());
			builder.Append(", Items = ");
			builder.Append(Items);
			return true;
		}

		[CompilerGenerated]
		private ContainerSnapshot(ContainerSnapshot original)
		{
			_items = original._items;
			Id = original.Id;
			Position = original.Position;
			Kind = original.Kind;
			IsInUse = original.IsInUse;
			IsAccessible = original.IsAccessible;
			SlotCount = original.SlotCount;
		}
	}
	public readonly record struct ItemKey(string ItemId, int Quality);
	public sealed record ItemStack(string ItemId, int Quality, int Amount, bool IsEquipped = false, int? Slot = null, string? StackKey = null, int MaxStack = 0);
	public enum ConnectionRule
	{
		OverlappingZones,
		StationInsideZone
	}
	public enum QualityMatching
	{
		Ignore,
		Exact,
		AtLeast
	}
	public sealed record ModConfig
	{
		public static ModConfig Default { get; } = new ModConfig();

		public ConnectionRule ConnectionRule { get; init; }

		public bool InclusiveBoundaries { get; init; } = true;

		public IReadOnlyCollection<string>? AllowedStationTypes { get; init; }

		public IReadOnlyCollection<ContainerKind> ExcludedContainerKinds { get; init; } = (IReadOnlyCollection<ContainerKind>)(object)new ContainerKind[2]
		{
			ContainerKind.Cart,
			ContainerKind.Ship
		};

		public QualityMatching QualityMatching { get; init; }

		public bool AllowEquippedItems { get; init; }

		public bool AutoRefuel { get; init; } = true;

		public FillSettings AutoRefuelSettings { get; init; } = FillSettings.Default;

		public bool ServerKeepsChests { get; init; }

		public int ChestReserve { get; init; } = 1;

		public int OpeningSafetyDelay { get; init; } = 5000;

		internal static ModConfig Validate(ModConfig? config)
		{
			ModConfig modConfig = config ?? Default;
			if (!Enum.IsDefined(typeof(ConnectionRule), modConfig.ConnectionRule))
			{
				throw new ArgumentOutOfRangeException("config", modConfig.ConnectionRule, "Unknown connection rule.");
			}
			if (!Enum.IsDefined(typeof(QualityMatching), modConfig.QualityMatching))
			{
				throw new ArgumentOutOfRangeException("config", modConfig.QualityMatching, "Unknown quality matching.");
			}
			return modConfig;
		}

		[CompilerGenerated]
		private ModConfig(ModConfig original)
		{
			ConnectionRule = original.ConnectionRule;
			InclusiveBoundaries = original.InclusiveBoundaries;
			AllowedStationTypes = original.AllowedStationTypes;
			ExcludedContainerKinds = original.ExcludedContainerKinds;
			QualityMatching = original.QualityMatching;
			AllowEquippedItems = original.AllowEquippedItems;
			AutoRefuel = original.AutoRefuel;
			AutoRefuelSettings = original.AutoRefuelSettings;
			ServerKeepsChests = original.ServerKeepsChests;
			ChestReserve = original.ChestReserve;
			OpeningSafetyDelay = original.OpeningSafetyDelay;
		}

		public ModConfig()
		{
		}
	}
	public sealed record Requirement(string ItemId, int Amount, int? Quality = null);
	public sealed record StationSnapshot(string Id, Vector3 Position, float Range, string StationType);
	public sealed record Withdrawal(string? ContainerId, string ItemId, int Quality, long Amount)
	{
		public bool IsFromInventory => ContainerId == null;
	}
	public sealed class ConsumptionPlan : IWithdrawingPlan, INetworkPlan
	{
		public static ConsumptionPlan Empty { get; } = new ConsumptionPlan(Array.Empty<Withdrawal>());

		public IReadOnlyList<Withdrawal> Withdrawals { get; }

		IReadOnlyList<Withdrawal> IWithdrawingPlan.FirstUse => Withdrawals;

		public IReadOnlyList<string> ContainersTouched { get; }

		public bool IsEmpty => Withdrawals.Count == 0;

		internal ConsumptionPlan(IReadOnlyList<Withdrawal> withdrawals)
		{
			Withdrawals = withdrawals;
			ContainersTouched = ContainerIds.Touched(withdrawals.Select((Withdrawal w) => w.ContainerId));
		}

		public long TotalFor(string itemId)
		{
			return WithdrawalTotals.TotalFor(Withdrawals, itemId);
		}
	}
	public sealed record Shortage(string ItemId, int? Quality, long Required, long Available)
	{
		public long Missing => Required - Available;
	}
	public enum PlanStatus
	{
		Success,
		InvalidRequirements,
		InsufficientResources
	}
	public sealed class PlanResult
	{
		public PlanStatus Status { get; }

		public bool IsSuccess => Status == PlanStatus.Success;

		public ConsumptionPlan? Plan { get; }

		public IReadOnlyList<Shortage> Shortages { get; }

		public IReadOnlyList<Requirement> InvalidRequirements { get; }

		private PlanResult(PlanStatus status, ConsumptionPlan? plan, IReadOnlyList<Shortage> shortages, IReadOnlyList<Requirement> invalidRequirements)
		{
			Status = status;
			Plan = plan;
			Shortages = shortages;
			InvalidRequirements = invalidRequirements;
		}

		internal static PlanResult Success(ConsumptionPlan plan)
		{
			return new PlanResult(PlanStatus.Success, plan, Array.Empty<Shortage>(), Array.Empty<Requirement>());
		}

		internal static PlanResult Invalid(IReadOnlyList<Requirement> invalid)
		{
			return new PlanResult(PlanStatus.InvalidRequirements, null, Array.Empty<Shortage>(), invalid);
		}

		internal static PlanResult Insufficient(IReadOnlyList<Shortage> shortages)
		{
			return new PlanResult(PlanStatus.InsufficientResources, null, shortages, Array.Empty<Requirement>());
		}
	}
	public interface INetworkPlan
	{
		IReadOnlyList<string> ContainersTouched { get; }

		bool IsEmpty { get; }
	}
	public interface IWithdrawingPlan : INetworkPlan
	{
		IReadOnlyList<Withdrawal> Withdrawals { get; }

		IReadOnlyList<Withdrawal> FirstUse { get; }
	}
	public interface ITargetingPlan : INetworkPlan
	{
		IReadOnlyList<string> TargetsTouched { get; }
	}
	public sealed class ConsumptionPlanner
	{
		private readonly record struct DemandKey(string ItemId, int? Quality);

		private readonly record struct Demand(string ItemId, int? Quality, long Amount);

		private readonly record struct WithdrawalKey(int SourceIndex, string ItemId, int Quality);

		private readonly ModConfig _config;

		private readonly bool _keepOnePerContainer;

		public ConsumptionPlanner(ModConfig? config = null, bool keepOnePerContainer = false)
		{
			_config = ModConfig.Validate(config);
			_keepOnePerContainer = keepOnePerContainer;
		}

		public PlanResult Plan(IEnumerable<Requirement?>? requirements, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			List<Requirement> list = new List<Requirement>();
			List<Requirement> list2 = new List<Requirement>();
			if (requirements != null)
			{
				foreach (Requirement requirement in requirements)
				{
					if ((object)requirement != null)
					{
						list.Add(requirement);
						if (string.IsNullOrEmpty(requirement.ItemId) || requirement.Amount < 0)
						{
							list2.Add(requirement);
						}
					}
				}
			}
			if (list2.Count > 0)
			{
				return PlanResult.Invalid(list2);
			}
			List<Demand> list3 = GroupDemands(list);
			if (list3.Count == 0)
			{
				return PlanResult.Success(ConsumptionPlan.Empty);
			}
			List<ContainerSnapshot> uniqueContainers = Deduplication.ById(containers, (ContainerSnapshot c) => c.Id);
			SourceStock?[] sources = new SourceStock[uniqueContainers.Count + 1];
			sources[0] = new SourceStock(null, Stock.TallyInventory(inventory, _config));
			Dictionary<WithdrawalKey, long> taken = new Dictionary<WithdrawalKey, long>();
			List<Shortage> list4 = new List<Shortage>();
			foreach (Demand item in list3)
			{
				Demand demand = item;
				long num = demand.Amount - SourceDraw.Draw(demand.Amount, sources.Length, delegate(int i)
				{
					ref SourceStock reference = ref sources[i];
					return reference ?? (reference = new SourceStock(uniqueContainers[i - 1].Id, Stock.TallyContainer(uniqueContainers[i - 1])));
				}, demand.ItemId, _keepOnePerContainer, (SourceStock source) => source.Available(demand.ItemId, Accepts), delegate(int index, SourceStock source, long units)
				{
					source.Take(demand.ItemId, units, Accepts, delegate(int quality, long amount)
					{
						taken.Accumulate(new WithdrawalKey(index, demand.ItemId, quality), amount);
					});
				});
				if (num > 0)
				{
					list4.Add(new Shortage(demand.ItemId, demand.Quality, demand.Amount, demand.Amount - num));
				}
				bool Accepts(int quality)
				{
					return Stock.Matches(_config.QualityMatching, quality, demand.Quality);
				}
			}
			if (list4.Count > 0)
			{
				return PlanResult.Insufficient(list4);
			}
			return PlanResult.Success(new ConsumptionPlan(ToWithdrawals(taken, sources)));
		}

		private List<Demand> GroupDemands(List<Requirement> requested)
		{
			bool flag = _config.QualityMatching == QualityMatching.Ignore;
			Dictionary<DemandKey, long> dictionary = new Dictionary<DemandKey, long>();
			foreach (Requirement item in requested)
			{
				DemandKey key = new DemandKey(item.ItemId, flag ? ((int?)null) : item.Quality);
				dictionary.Accumulate(key, item.Amount);
			}
			List<Demand> list = new List<Demand>(dictionary.Count);
			foreach (KeyValuePair<DemandKey, long> item2 in dictionary)
			{
				list.Add(new Demand(item2.Key.ItemId, item2.Key.Quality, item2.Value));
			}
			list.Sort(CompareDemands);
			return list;
		}

		private static int CompareDemands(Demand a, Demand b)
		{
			int num = string.CompareOrdinal(a.ItemId, b.ItemId);
			if (num != 0)
			{
				return num;
			}
			int num2 = b.Quality.HasValue.CompareTo(a.Quality.HasValue);
			if (num2 != 0)
			{
				return num2;
			}
			return b.Quality.GetValueOrDefault().CompareTo(a.Quality.GetValueOrDefault());
		}

		private static List<Withdrawal> ToWithdrawals(Dictionary<WithdrawalKey, long> taken, SourceStock?[] sources)
		{
			List<WithdrawalKey> list = new List<WithdrawalKey>(taken.Keys);
			list.Sort(delegate(WithdrawalKey a, WithdrawalKey b)
			{
				int num = a.SourceIndex.CompareTo(b.SourceIndex);
				if (num != 0)
				{
					return num;
				}
				int num2 = string.CompareOrdinal(a.ItemId, b.ItemId);
				return (num2 == 0) ? a.Quality.CompareTo(b.Quality) : num2;
			});
			List<Withdrawal> list2 = new List<Withdrawal>(list.Count);
			foreach (WithdrawalKey item in list)
			{
				list2.Add(new Withdrawal(sources[item.SourceIndex].ContainerId, item.ItemId, item.Quality, taken[item]));
			}
			return list2;
		}
	}
	public sealed class ContainerSelector
	{
		private readonly ModConfig _config;

		private readonly ContainerUsability _usability;

		public ContainerSelector(ModConfig? config = null)
		{
			_config = ModConfig.Validate(config);
			_usability = new ContainerUsability(_config);
		}

		public IReadOnlyList<ContainerSnapshot> Select(StationNetwork network, IEnumerable<ContainerSnapshot?>? containers)
		{
			if (network == null)
			{
				throw new ArgumentNullException("network");
			}
			if (network.IsEmpty)
			{
				return Array.Empty<ContainerSnapshot>();
			}
			List<ContainerSnapshot> list = Deduplication.ById(containers, (ContainerSnapshot container) => container.Id);
			List<KeyValuePair<double, ContainerSnapshot>> list2 = new List<KeyValuePair<double, ContainerSnapshot>>(list.Count);
			List<int> nearby = new List<int>();
			foreach (ContainerSnapshot item in list)
			{
				if (IsEligible(item, network, nearby))
				{
					list2.Add(new KeyValuePair<double, ContainerSnapshot>(Geometry.DistanceSquared(network.Origin, item.Position), item));
				}
			}
			list2.Sort(CompareByDistanceThenId);
			ContainerSnapshot[] array = new ContainerSnapshot[list2.Count];
			for (int num = 0; num < array.Length; num++)
			{
				array[num] = list2[num].Value;
			}
			return array;
		}

		private static int CompareByDistanceThenId(KeyValuePair<double, ContainerSnapshot> a, KeyValuePair<double, ContainerSnapshot> b)
		{
			int num = a.Key.CompareTo(b.Key);
			if (num == 0)
			{
				return string.CompareOrdinal(a.Value.Id, b.Value.Id);
			}
			return num;
		}

		private bool IsEligible(ContainerSnapshot container, StationNetwork network, List<int> nearby)
		{
			if (!_usability.Check(container).HasValue)
			{
				return network.Contains(container.Position, _config.InclusiveBoundaries, nearby);
			}
			return false;
		}
	}
	public enum ValidationIssueKind
	{
		ContainerMissing,
		ContainerInUse,
		ContainerInaccessible,
		ContainerExcluded,
		InsufficientQuantity,
		SlotUnavailable,
		NotATarget,
		InventoryFull
	}
	public sealed record ValidationIssue(ValidationIssueKind Kind, string? ContainerId, string? ItemId = null, int? Quality = null, long Required = 0L, long Available = 0L, int? Slot = null);
	public sealed class ValidationResult
	{
		public static ValidationResult Valid { get; } = new ValidationResult(Array.Empty<ValidationIssue>());

		public bool IsValid => Issues.Count == 0;

		public IReadOnlyList<ValidationIssue> Issues { get; }

		internal ValidationResult(IReadOnlyList<ValidationIssue> issues)
		{
			Issues = issues;
		}
	}
	public sealed class PlanValidator
	{
		private sealed class ContainerChecks
		{
			private readonly ContainerUsability _usability;

			private readonly Dictionary<string, ContainerSnapshot> _byId = new Dictionary<string, ContainerSnapshot>(StringComparer.Ordinal);

			private readonly Dictionary<string, ContainerSnapshot?> _verdicts = new Dictionary<string, ContainerSnapshot>(StringComparer.Ordinal);

			public List<ValidationIssue> Issues { get; } = new List<ValidationIssue>();

			public ContainerChecks(ContainerUsability usability, IEnumerable<ContainerSnapshot?>? containers)
			{
				_usability = usability;
				foreach (ContainerSnapshot item in Deduplication.ById(containers, (ContainerSnapshot c) => c.Id))
				{
					_byId.Add(item.Id, item);
				}
			}

			public ContainerSnapshot? Use(string id)
			{
				if (_verdicts.TryGetValue(id, out ContainerSnapshot value))
				{
					return value;
				}
				ContainerSnapshot value2;
				ValidationIssueKind? validationIssueKind = (_byId.TryGetValue(id, out value2) ? _usability.Check(value2) : new ValidationIssueKind?(ValidationIssueKind.ContainerMissing));
				if (validationIssueKind.HasValue)
				{
					Issues.Add(new ValidationIssue(validationIssueKind.Value, id, null, null, 0L, 0L));
					value2 = null;
				}
				_verdicts.Add(id, value2);
				return value2;
			}
		}

		private readonly ModConfig _config;

		private readonly ContainerUsability _usability;

		public PlanValidator(ModConfig? config = null)
		{
			_config = ModConfig.Validate(config);
			_usability = new ContainerUsability(_config);
		}

		public ValidationResult Validate(ConsumptionPlan plan, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			return ValidateWithdrawals(plan?.Withdrawals ?? throw new ArgumentNullException("plan"), inventory, containers);
		}

		public ValidationResult ValidateTake(PanelTakePlan plan, IEnumerable<ContainerSnapshot?>? containers)
		{
			return ValidateWithdrawals(plan?.Withdrawals ?? throw new ArgumentNullException("plan"), null, containers);
		}

		public ValidationResult ValidateFill(FillPlan plan, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			return ValidateWithdrawals(plan?.Withdrawals ?? throw new ArgumentNullException("plan"), inventory, containers);
		}

		public ValidationResult ValidateNetworkFill(NetworkFillPlan plan, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			return ValidateWithdrawals(plan?.Withdrawals ?? throw new ArgumentNullException("plan"), inventory, containers);
		}

		private ValidationResult ValidateWithdrawals(IReadOnlyList<Withdrawal> withdrawals, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			ContainerChecks containerChecks = new ContainerChecks(_usability, containers);
			List<ValidationIssue> issues = containerChecks.Issues;
			Dictionary<ItemKey, long> dictionary = Stock.TallyInventory(inventory, _config);
			Dictionary<string, Dictionary<ItemKey, long>> dictionary2 = new Dictionary<string, Dictionary<ItemKey, long>>(StringComparer.Ordinal);
			foreach (Withdrawal withdrawal in withdrawals)
			{
				Dictionary<ItemKey, long> value = dictionary;
				if (withdrawal.ContainerId != null)
				{
					ContainerSnapshot containerSnapshot = containerChecks.Use(withdrawal.ContainerId);
					if ((object)containerSnapshot == null)
					{
						continue;
					}
					if (!dictionary2.TryGetValue(withdrawal.ContainerId, out value))
					{
						value = Stock.TallyContainer(containerSnapshot);
						dictionary2.Add(withdrawal.ContainerId, value);
					}
				}
				value.TryGetValue(new ItemKey(withdrawal.ItemId, withdrawal.Quality), out var value2);
				if (value2 < withdrawal.Amount)
				{
					issues.Add(new ValidationIssue(ValidationIssueKind.InsufficientQuantity, withdrawal.ContainerId, withdrawal.ItemId, withdrawal.Quality, withdrawal.Amount, value2));
				}
			}
			return new ValidationResult(issues);
		}

		public ValidationResult ValidateDeposit(DepositPlan plan, IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			if (plan == null)
			{
				throw new ArgumentNullException("plan");
			}
			ContainerChecks containerChecks = new ContainerChecks(_usability, containers);
			List<ValidationIssue> issues = containerChecks.Issues;
			Dictionary<int, ItemStack> dictionary = BySlot(inventory);
			foreach (IGrouping<int, StackDeposit> item in from d in plan.Deposits
				group d by d.SourceSlot)
			{
				StackDeposit stackDeposit = item.First();
				long num = item.Sum((StackDeposit d) => d.Amount);
				ItemStack value;
				long num2 = ((dictionary.TryGetValue(item.Key, out value) && value.ItemId == stackDeposit.ItemId && value.StackKey == stackDeposit.StackKey) ? value.Amount : 0);
				if (num2 < num)
				{
					issues.Add(new ValidationIssue(ValidationIssueKind.InsufficientQuantity, null, stackDeposit.ItemId, stackDeposit.Quality, num, num2, item.Key));
				}
			}
			foreach (IGrouping<string, StackDeposit> item2 in from d in plan.Deposits
				group d by d.ContainerId)
			{
				ContainerSnapshot containerSnapshot = containerChecks.Use(item2.Key);
				if ((object)containerSnapshot == null)
				{
					continue;
				}
				foreach (string item3 in item2.Select((StackDeposit d) => d.ItemId).Distinct())
				{
					if (!DepositRules.IsTarget(containerSnapshot, item3))
					{
						issues.Add(new ValidationIssue(ValidationIssueKind.NotATarget, item2.Key, item3, null, 0L, 0L));
					}
				}
				foreach (IGrouping<int, StackDeposit> intoSlot in from d in item2
					group d by d.TargetSlot)
				{
					StackDeposit stackDeposit2 = intoSlot.First();
					long num3 = intoSlot.Sum((StackDeposit d) => d.Amount);
					ItemStack itemStack = containerSnapshot.Items.FirstOrDefault((ItemStack stack) => stack.Slot == intoSlot.Key && stack.Amount > 0);
					ItemStack value2;
					int num4 = ((dictionary.TryGetValue(stackDeposit2.SourceSlot, out value2) && value2.MaxStack > 0) ? value2.MaxStack : (itemStack?.MaxStack ?? 0));
					if (num4 > 0)
					{
						long num5 = (((object)itemStack == null) ? num4 : DepositRules.RoomOnTop(itemStack.ItemId, itemStack.StackKey, itemStack.Amount, stackDeposit2.ItemId, stackDeposit2.StackKey, num4));
						if (!DepositRules.IsValidSlot(intoSlot.Key, containerSnapshot.SlotCount) || num5 < num3)
						{
							issues.Add(new ValidationIssue(ValidationIssueKind.SlotUnavailable, item2.Key, stackDeposit2.ItemId, stackDeposit2.Quality, num3, Math.Max(0L, num5), intoSlot.Key));
						}
					}
				}
			}
			return new ValidationResult(issues);
		}

		public ValidationResult ValidateArmorFill(ArmorFillPlan plan, IEnumerable<ArmorPiece?>? currentPieces, IEnumerable<ContainerSnapshot?>? containers, IEnumerable<ArmorSlot>? freeStandSlots, string standId)
		{
			if (plan == null)
			{
				throw new ArgumentNullException("plan");
			}
			ContainerChecks containerChecks = new ContainerChecks(_usability, containers);
			List<ValidationIssue> issues = containerChecks.Issues;
			List<ArmorPiece> source = (from p in currentPieces ?? Array.Empty<ArmorPiece>()
				where (object)p != null
				select (p)).ToList();
			HashSet<ArmorSlot> hashSet = new HashSet<ArmorSlot>(freeStandSlots ?? Array.Empty<ArmorSlot>());
			foreach (KeyValuePair<ArmorSlot, ArmorPiece> choice in plan.Choices)
			{
				ArmorPiece chosen = choice.Value;
				if ((chosen.ContainerId == null || (object)containerChecks.Use(chosen.ContainerId) != null) && !source.Any((ArmorPiece p) => p.ContainerId == chosen.ContainerId && p.Slot == chosen.Slot && p.IsSameItemAs(chosen) && !p.IsEquipped))
				{
					issues.Add(new ValidationIssue(ValidationIssueKind.InsufficientQuantity, chosen.ContainerId, chosen.ItemId, chosen.Quality, 1L, 0L, chosen.Slot));
				}
				if (!hashSet.Contains(choice.Key))
				{
					issues.Add(new ValidationIssue(ValidationIssueKind.SlotUnavailable, standId, chosen.ItemId, chosen.Quality, 1L, 0L, (int)choice.Key));
				}
			}
			return new ValidationResult(issues);
		}

		public ValidationResult ValidateArmorSwap(ArmorSwapPlan plan, IReadOnlyDictionary<ArmorSlot, ArmorPiece>? stand, IReadOnlyDictionary<ArmorSlot, ArmorPiece>? worn, int standWeapons, int freeInventorySlots, string standId)
		{
			if (plan == null)
			{
				throw new ArgumentNullException("plan");
			}
			List<ValidationIssue> list = new List<ValidationIssue>();
			Dictionary<ArmorSlot, ArmorPiece> dictionary = plan.ToPlayer.ToDictionary<KeyValuePair<ArmorSlot, ArmorPiece>, ArmorSlot, ArmorPiece>((KeyValuePair<ArmorSlot, ArmorPiece> m) => m.Key, (KeyValuePair<ArmorSlot, ArmorPiece> m) => m.Value);
			ArmorSlot[] array = (ArmorSlot[])Enum.GetValues(typeof(ArmorSlot));
			foreach (ArmorSlot slot in array)
			{
				ArmorPiece value;
				ArmorPiece armorPiece = ((stand != null && stand.TryGetValue(slot, out value)) ? value : null);
				dictionary.TryGetValue(slot, out var value2);
				if (!SamePiece(armorPiece, value2) && ((object)value2 != null || plan.ToStand.Any<KeyValuePair<ArmorSlot, ArmorPiece>>((KeyValuePair<ArmorSlot, ArmorPiece> m) => m.Key == slot)))
				{
					ArmorPiece armorPiece2 = value2 ?? armorPiece;
					list.Add(new ValidationIssue(ValidationIssueKind.SlotUnavailable, standId, armorPiece2.ItemId, armorPiece2.Quality, 1L, 0L, (int)slot));
				}
			}
			foreach (KeyValuePair<ArmorSlot, ArmorPiece> item in plan.ToStand)
			{
				if (!SamePiece((worn != null && worn.TryGetValue(item.Key, out ArmorPiece value3)) ? value3 : null, item.Value))
				{
					list.Add(new ValidationIssue(ValidationIssueKind.InsufficientQuantity, null, item.Value.ItemId, item.Value.Quality, 1L, 0L, (int)item.Key));
				}
			}
			int num2 = ArmorSwapPlan.RequiredSlots(plan.ToPlayer.Count, plan.ToStand.Count, standWeapons);
			if (freeInventorySlots < num2)
			{
				long required = num2;
				long available = Math.Max(0, freeInventorySlots);
				list.Add(new ValidationIssue(ValidationIssueKind.InventoryFull, null, null, null, required, available));
			}
			return new ValidationResult(list);
		}

		private static bool SamePiece(ArmorPiece? a, ArmorPiece? b)
		{
			if ((object)a != null)
			{
				if ((object)b != null)
				{
					return a.IsSameItemAs(b);
				}
				return false;
			}
			return (object)b == null;
		}

		private static Dictionary<int, ItemStack> BySlot(IEnumerable<ItemStack?>? inventory)
		{
			Dictionary<int, ItemStack> dictionary = new Dictionary<int, ItemStack>();
			foreach (ItemStack item in DepositRules.SourcesBySlot(inventory))
			{
				dictionary.Add(item.Slot.Value, item);
			}
			return dictionary;
		}
	}
	public sealed class ResourceCount
	{
		private readonly Dictionary<ItemKey, long> _byKey;

		private readonly Dictionary<string, long> _byItem;

		private readonly QualityMatching _qualityMatching;

		public IReadOnlyDictionary<ItemKey, long> ByItemAndQuality => _byKey;

		internal ResourceCount(Dictionary<ItemKey, long> byKey, QualityMatching qualityMatching)
		{
			_byKey = byKey;
			_qualityMatching = qualityMatching;
			_byItem = new Dictionary<string, long>(StringComparer.Ordinal);
			foreach (KeyValuePair<ItemKey, long> item in byKey)
			{
				_byItem.TryGetValue(item.Key.ItemId, out var value);
				_byItem[item.Key.ItemId] = value + item.Value;
			}
		}

		public long GetTotal(string itemId)
		{
			if (!_byItem.TryGetValue(itemId, out var value))
			{
				return 0L;
			}
			return value;
		}

		public long GetTotal(string itemId, int quality)
		{
			if (!_byKey.TryGetValue(new ItemKey(itemId, quality), out var value))
			{
				return 0L;
			}
			return value;
		}

		public long GetAvailable(Requirement requirement)
		{
			if ((object)requirement == null)
			{
				throw new ArgumentNullException("requirement");
			}
			if (!requirement.Quality.HasValue || _qualityMatching == QualityMatching.Ignore)
			{
				return GetTotal(requirement.ItemId);
			}
			long num = 0L;
			foreach (KeyValuePair<ItemKey, long> item in _byKey)
			{
				if (string.Equals(item.Key.ItemId, requirement.ItemId, StringComparison.Ordinal) && Stock.Matches(_qualityMatching, item.Key.Quality, requirement.Quality))
				{
					num += item.Value;
				}
			}
			return num;
		}
	}
	public sealed class ResourceCounter
	{
		private readonly ModConfig _config;

		public ResourceCounter(ModConfig? config = null)
		{
			_config = ModConfig.Validate(config);
		}

		public ResourceCount Count(IEnumerable<ItemStack?>? inventory, IEnumerable<ContainerSnapshot?>? containers)
		{
			Dictionary<ItemKey, long> dictionary = Stock.TallyInventory(inventory, _config);
			foreach (ContainerSnapshot item in Deduplication.ById(containers, (ContainerSnapshot c) => c.Id))
			{
				foreach (KeyValuePair<ItemKey, long> item2 in Stock.TallyContainer(item))
				{
					dictionary.TryGetValue(item2.Key, out var value);
					dictionary[item2.Key] = value + item2.Value;
				}
			}
			return new ResourceCount(dictionary, _config.QualityMatching);
		}
	}
	public sealed class StationNetwork
	{
		public Vector3 Origin { get; }

		public IReadOnlyList<StationSnapshot> Stations { get; }

		public bool IsEmpty => Stations.Count == 0;

		internal double[] X { get; }

		internal double[] Y { get; }

		internal double[] Z { get; }

		internal double[] Ranges { get; }

		internal double MaxRange { get; }

		internal SpatialGrid Grid { get; }

		internal StationNetwork(Vector3 origin, IReadOnlyList<StationSnapshot> stations)
		{
			Origin = origin;
			Stations = stations;
			StationArrays stationArrays = new StationArrays(stations);
			X = stationArrays.X;
			Y = stationArrays.Y;
			Z = stationArrays.Z;
			Ranges = stationArrays.Ranges;
			MaxRange = stationArrays.MaxRange;
			Grid = new SpatialGrid(X, Z, MaxRange);
		}

		internal bool Contains(Vector3 position, bool inclusive, List<int> nearby)
		{
			double num = position.X;
			double ay = position.Y;
			double num2 = position.Z;
			Grid.Query(num, num2, MaxRange, nearby);
			foreach (int item in nearby)
			{
				if (Geometry.IsWithin(Geometry.DistanceSquared(num, ay, num2, X[item], Y[item], Z[item]), Ranges[item], inclusive))
				{
					return true;
				}
			}
			return false;
		}
	}
	public sealed class StationNetworkResolver
	{
		private readonly ModConfig _config;

		private readonly HashSet<string>? _allowedTypes;

		public StationNetworkResolver(ModConfig? config = null)
		{
			_config = ModConfig.Validate(config);
			_allowedTypes = ((_config.AllowedStationTypes == null) ? null : new HashSet<string>(_config.AllowedStationTypes, StringComparer.Ordinal));
		}

		public StationNetwork Resolve(Vector3 playerPosition, IEnumerable<StationSnapshot?>? stations)
		{
			List<StationSnapshot> list = Deduplication.ById(stations, (StationSnapshot station) => station.Id);
			list.RemoveAll((StationSnapshot station) => !IsUsable(station));
			int count = list.Count;
			StationArrays stationArrays = new StationArrays(list);
			double[] x = stationArrays.X;
			double[] y = stationArrays.Y;
			double[] z = stationArrays.Z;
			double[] ranges = stationArrays.Ranges;
			double maxRange = stationArrays.MaxRange;
			bool[] array = new bool[count];
			int[] array2 = new int[count];
			int num = 0;
			int num2 = 0;
			bool inclusiveBoundaries = _config.InclusiveBoundaries;
			for (int num3 = 0; num3 < count; num3++)
			{
				if (Geometry.IsWithin(Geometry.DistanceSquared(x[num3], y[num3], z[num3], playerPosition.X, playerPosition.Y, playerPosition.Z), ranges[num3], inclusiveBoundaries))
				{
					array[num3] = true;
					array2[num2++] = num3;
				}
			}
			if (num2 > 0)
			{
				SpatialGrid spatialGrid = new SpatialGrid(x, z, ConnectionRadius(maxRange, maxRange));
				List<int> list2 = new List<int>();
				while (num < num2)
				{
					int num4 = array2[num++];
					spatialGrid.Query(x[num4], z[num4], ConnectionRadius(ranges[num4], maxRange), list2);
					foreach (int item in list2)
					{
						if (!array[item] && Geometry.IsWithin(Geometry.DistanceSquared(x[num4], y[num4], z[num4], x[item], y[item], z[item]), ConnectionRadius(ranges[num4], ranges[item]), inclusiveBoundaries))
						{
							array[item] = true;
							array2[num2++] = item;
						}
					}
				}
			}
			List<StationSnapshot> list3 = new List<StationSnapshot>(num2);
			for (int num5 = 0; num5 < count; num5++)
			{
				if (array[num5])
				{
					list3.Add(list[num5]);
				}
			}
			list3.Sort((StationSnapshot a, StationSnapshot b) => string.CompareOrdinal(a.Id, b.Id));
			return new StationNetwork(playerPosition, list3);
		}

		private bool IsUsable(StationSnapshot station)
		{
			if (float.IsFinite(station.Range) && station.Range > 0f)
			{
				if (_allowedTypes != null)
				{
					if (station.StationType != null)
					{
						return _allowedTypes.Contains(station.StationType);
					}
					return false;
				}
				return true;
			}
			return false;
		}

		private double ConnectionRadius(double rangeA, double rangeB)
		{
			if (_config.ConnectionRule != ConnectionRule.StationInsideZone)
			{
				return rangeA + rangeB;
			}
			return Math.Max(rangeA, rangeB);
		}
	}
}
namespace ChestNetwork.Core.Serving
{
	public enum ChestPrivacy
	{
		Private,
		Group,
		Public
	}
	public sealed record WardSnapshot(Vector3 Position, float Radius, bool Enabled, long Creator, IReadOnlyCollection<long> Permitted);
	public static class ChestAccess
	{
		public static bool IsAccessible(ChestPrivacy privacy, long creator, long playerId, bool checksWards, Vector3 position, IEnumerable<WardSnapshot?> wards)
		{
			bool flag = privacy switch
			{
				ChestPrivacy.Public => true, 
				ChestPrivacy.Private => creator == playerId, 
				_ => false, 
			};
			if (!flag || !checksWards)
			{
				return flag;
			}
			bool flag2 = false;
			foreach (WardSnapshot ward in wards)
			{
				if ((object)ward != null && ward.Enabled && HorizontalDistance(ward.Position, position) < ward.Radius)
				{
					if (ward.Creator == playerId || ward.Permitted.Contains(playerId))
					{
						return true;
					}
					flag2 = true;
				}
			}
			return !flag2;
		}

		private static float HorizontalDistance(Vector3 a, Vector3 b)
		{
			return new Vector2(a.X - b.X, a.Z - b.Z).Length();
		}
	}
	public sealed record SavedStack(string? ItemId, int Quality, int Amount);
	public static class InventoryIntegrity
	{
		public static bool IsPreserved(IEnumerable<SavedStack> saved, IEnumerable<SavedStack> decoded)
		{
			List<SavedStack> list = saved.ToList();
			if (list.Any((SavedStack stack) => stack.ItemId == null))
			{
				return false;
			}
			Dictionary<(string, int), long> dictionary = Totals(list);
			Dictionary<(string?, int), long> after = Totals(decoded);
			long value;
			if (dictionary.Count == after.Count)
			{
				return dictionary.All((KeyValuePair<(string, int), long> total) => after.TryGetValue(total.Key, out value) && value == total.Value);
			}
			return false;
		}

		private static Dictionary<(string?, int), long> Totals(IEnumerable<SavedStack> stacks)
		{
			return (from stack in stacks
				group stack by (ItemId: stack.ItemId, Quality: stack.Quality)).ToDictionary((IGrouping<(string ItemId, int Quality), SavedStack> group) => group.Key, (IGrouping<(string ItemId, int Quality), SavedStack> group) => ((IEnumerable<SavedStack>)group).Sum((Func<SavedStack, long>)((SavedStack stack) => stack.Amount)));
		}
	}
	public sealed record StationExtensionSnapshot(Vector3 Position, string StationType, float MaxStationDistance, string Name, bool Stacks);
	public static class StationRange
	{
		public static float BuildRange(Vector3 position, string stationType, float baseRange, float extraRangePerLevel, IEnumerable<StationExtensionSnapshot?> extensions)
		{
			List<string> list = new List<string>();
			foreach (StationExtensionSnapshot extension in extensions)
			{
				if ((object)extension != null && string.Equals(extension.StationType, stationType, StringComparison.Ordinal) && Vector3.Distance(extension.Position, position) < extension.MaxStationDistance && (extension.Stacks || !list.Contains(extension.Name)))
				{
					list.Add(extension.Name);
				}
			}
			return baseRange + (float)list.Count * extraRangePerLevel;
		}
	}
}
namespace ChestNetwork.Core.Repair
{
	public static class RepairAll
	{
		public static int Run(Func<bool> anyRepairable, Action repairOne, int maxRepairs)
		{
			if (anyRepairable == null)
			{
				throw new ArgumentNullException("anyRepairable");
			}
			if (repairOne == null)
			{
				throw new ArgumentNullException("repairOne");
			}
			int i;
			for (i = 0; i < maxRepairs; i++)
			{
				if (!anyRepairable())
				{
					break;
				}
				repairOne();
			}
			return i;
		}
	}
}
namespace ChestNetwork.Core.Panel
{
	public static class ChestCount
	{
		public const int Cap = 999;

		public static string Format(int count)
		{
			if (count > 999)
			{
				return 999.ToString(CultureInfo.InvariantCulture) + "+";
			}
			return Math.Max(0, count).ToString(CultureInfo.InvariantCulture);
		}
	}
	public enum FamilyRole
	{
		Source,
		Ingot,
		Product
	}
	public sealed record ItemFamily(string Id, FamilyRole Role);
	public static class FamilyInference
	{
		public static IReadOnlyDictionary<string, ItemFamily> Infer(GameData data)
		{
			if ((object)data == null)
			{
				throw new ArgumentNullException("data");
			}
			Dictionary<string, string> idOf = data.Items.Where((GameItem item) => !string.IsNullOrEmpty(item.ItemId)).GroupBy<GameItem, string>((GameItem item) => item.Prefab, StringComparer.Ordinal).ToDictionary<IGrouping<string, GameItem>, string, string>((IGrouping<string, GameItem> group) => group.Key, (IGrouping<string, GameItem> group) => Least(group.Select((GameItem item) => item.ItemId)), StringComparer.Ordinal);
			HashSet<string> used = new HashSet<string>(from input in data.Recipes.Concat(data.Pieces).SelectMany((GameCraft craft) => craft.Inputs).Where(idOf.ContainsKey)
				select idOf[input], StringComparer.Ordinal);
			List<(string, string)> source = (from conversion in data.Conversions
				where !conversion.Prepares && idOf.ContainsKey(conversion.From) && idOf.ContainsKey(conversion.To)
				select (idOf[conversion.From], idOf[conversion.To])).Distinct().ToList();
			HashSet<string> smelted = new HashSet<string>(source.Select<(string, string), string>(((string From, string To) edge) => edge.To), StringComparer.Ordinal);
			Dictionary<string, ItemFamily> dictionary = new Dictionary<string, ItemFamily>(StringComparer.Ordinal);
			AddSmeltedFamilies(source.Where<(string, string)>(((string From, string To) edge) => !used.Contains(edge.From)).ToList(), dictionary);
			AddProducts(data, idOf, smelted, dictionary);
			return dictionary;
		}

		private static void AddSmeltedFamilies(List<(string From, string To)> edges, Dictionary<string, ItemFamily> families)
		{
			Dictionary<string, string> parent = new Dictionary<string, string>(StringComparer.Ordinal);
			foreach (var (text, text2) in edges)
			{
				parent[Find(text)] = Find(text2);
				parent[text] = Find(text);
				parent[text2] = Find(text2);
			}
			HashSet<string> sources = new HashSet<string>(edges.Select<(string, string), string>(((string From, string To) edge) => edge.From), StringComparer.Ordinal);
			foreach (IGrouping<string, string> item in parent.Keys.GroupBy<string, string>(Find, StringComparer.Ordinal))
			{
				List<string> list = item.Where((string item) => !sources.Contains(item)).OrderBy<string, string>((string item) => item, StringComparer.Ordinal).ToList();
				if (list.Count == 0)
				{
					continue;
				}
				foreach (string item2 in item)
				{
					families[item2] = new ItemFamily(list[0], (!sources.Contains(item2)) ? FamilyRole.Ingot : FamilyRole.Source);
				}
			}
			string Find(string item)
			{
				string value;
				while (parent.TryGetValue(item, out value) && value != item)
				{
					item = value;
				}
				return item;
			}
		}

		private static void AddProducts(GameData data, Dictionary<string, string> idOf, HashSet<string> smelted, Dictionary<string, ItemFamily> families)
		{
			List<(string, string)> list = new List<(string, string)>();
			foreach (GameCraft recipe in data.Recipes)
			{
				if (idOf.TryGetValue(recipe.Output, out string value) && !smelted.Contains(value) && !families.ContainsKey(value))
				{
					string text = Principal(recipe, idOf);
					if (text != null && families.TryGetValue(text, out ItemFamily value2) && value2.Role == FamilyRole.Ingot)
					{
						list.Add((value, value2.Id));
					}
				}
			}
			foreach (IGrouping<string, (string, string)> item in list.GroupBy<(string, string), string>(((string Output, string Family) candidate) => candidate.Output, StringComparer.Ordinal))
			{
				families[item.Key] = new ItemFamily(Least(item.Select<(string, string), string>(((string Output, string Family) candidate) => candidate.Family)), FamilyRole.Product);
			}
		}

		private static string? Principal(GameCraft recipe, Dictionary<string, string> idOf)
		{
			Dictionary<string, long> dictionary = new Dictionary<string, long>(StringComparer.Ordinal);
			for (int i = 0; i < recipe.Inputs.Count; i++)
			{
				if (idOf.TryGetValue(recipe.Inputs[i], out string value))
				{
					dictionary.TryGetValue(value, out var value2);
					dictionary[value] = value2 + ((recipe.Amounts == null || i >= recipe.Amounts.Count) ? 1 : recipe.Amounts[i]);
				}
			}
			return (from entry in dictionary.OrderByDescending((KeyValuePair<string, long> entry) => entry.Value).ThenBy<KeyValuePair<string, long>, string>((KeyValuePair<string, long> entry) => entry.Key, StringComparer.Ordinal)
				select entry.Key).FirstOrDefault();
		}

		internal static string Least(IEnumerable<string> names)
		{
			return names.OrderBy<string, string>((string name) => name, StringComparer.Ordinal).ElementAt(0);
		}
	}
	public enum Biome
	{
		Meadows,
		BlackForest,
		Swamp,
		Ocean,
		Mountain,
		Plains,
		Mistlands,
		AshLands,
		DeepNorth
	}
	internal static class Biomes
	{
		private static readonly Dictionary<string, Biome> ByName = Enum.GetValues(typeof(Biome)).Cast<Biome>().ToDictionary<Biome, string, Biome>((Biome biome) => biome.ToString(), (Biome biome) => biome, StringComparer.Ordinal);

		public static bool TryParse(string name, out Biome biome)
		{
			return ByName.TryGetValue(name, out biome);
		}
	}
	public sealed record ItemProgression(string ItemId, Biome? Biome, int Depth, int Uses, bool ToPrepare);
	public sealed class ProgressionTable
	{
		private const string ResourceName = "ChestNetwork.Core.Panel.item-progression.tsv";

		private static readonly string[] Roles = new string[3] { "source", "ingot", "product" };

		private static readonly Dictionary<string, MaterialGroup> Groups = Enum.GetValues(typeof(MaterialGroup)).Cast<MaterialGroup>().ToDictionary<MaterialGroup, string, MaterialGroup>((MaterialGroup group) => group.ToString().ToLowerInvariant(), (MaterialGroup group) => group, StringComparer.Ordinal);

		private static ProgressionTable? s_default;

		private readonly Dictionary<string, ItemProgression> _byItem;

		private readonly Dictionary<string, ItemFamily> _families;

		private readonly Dictionary<string, MaterialGroup> _groups;

		public static ProgressionTable Default => s_default ?? (s_default = FromResource(typeof(ProgressionTable).Assembly, "ChestNetwork.Core.Panel.item-progression.tsv"));

		public int Count => _byItem.Count;

		public IReadOnlyList<ItemProgression> Entries => _byItem.Values.OrderBy<ItemProgression, string>((ItemProgression entry) => entry.ItemId, StringComparer.Ordinal).ToList();

		private ProgressionTable(IEnumerable<(ItemProgression Entry, ItemFamily? Family, MaterialGroup? Group)> entries)
		{
			_byItem = new Dictionary<string, ItemProgression>(StringComparer.Ordinal);
			_families = new Dictionary<string, ItemFamily>(StringComparer.Ordinal);
			_groups = new Dictionary<string, MaterialGroup>(StringComparer.Ordinal);
			foreach (var (itemProgression, itemFamily, materialGroup) in entries)
			{
				_byItem[itemProgression.ItemId] = itemProgression;
				if (materialGroup.HasValue)
				{
					_groups[itemProgression.ItemId] = materialGroup.Value;
				}
				else
				{
					_groups.Remove(itemProgression.ItemId);
				}
				if (itemFamily != null)
				{
					_families[itemProgression.ItemId] = itemFamily;
				}
				else
				{
					_families.Remove(itemProgression.ItemId);
				}
			}
		}

		public static ProgressionTable Of(IEnumerable<ItemProgression?>? entries, IReadOnlyDictionary<string, ItemFamily>? families = null, IReadOnlyDictionary<string, MaterialGroup>? groups = null)
		{
			ItemFamily value;
			MaterialGroup value2;
			return new ProgressionTable(from entry in entries ?? Enumerable.Empty<ItemProgression>()
				where entry != null && !string.IsNullOrEmpty(entry.ItemId)
				select (entry, (families != null && families.TryGetValue(entry.ItemId, out value)) ? value : null, (groups != null && groups.TryGetValue(entry.ItemId, out value2)) ? new MaterialGroup?(value2) : ((MaterialGroup?)null)));
		}

		public MaterialGroup? GroupOf(string? itemId)
		{
			if (itemId == null)
			{
				return null;
			}
			if (!_groups.TryGetValue(itemId, out var value))
			{
				return null;
			}
			return value;
		}

		public ItemProgression? Find(string? itemId)
		{
			if (itemId == null)
			{
				return null;
			}
			if (!_byItem.TryGetValue(itemId, out ItemProgression value))
			{
				return null;
			}
			return value;
		}

		public ItemFamily? FamilyOf(string? itemId)
		{
			if (itemId == null)
			{
				return null;
			}
			if (!_families.TryGetValue(itemId, out ItemFamily value))
			{
				return null;
			}
			return value;
		}

		public static ProgressionTable Parse(string text)
		{
			if (text == null)
			{
				throw new ArgumentNullException("text");
			}
			List<(ItemProgression, ItemFamily, MaterialGroup?)> list = new List<(ItemProgression, ItemFamily, MaterialGroup?)>();
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].TrimEnd('\r');
				if (text2.Length != 0 && text2[0] != '#')
				{
					list.Add(Entry(text2.Split('\t')) ?? throw new FormatException($"Line {i + 1} of the progression table is malformed: '{text2}'."));
				}
			}
			return new ProgressionTable(list);
		}

		public string Format(string header)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (string item in from line in (header ?? string.Empty).Split('\n')
				where line.Length > 0
				select line)
			{
				stringBuilder.Append("# ").Append(item.TrimEnd('\r')).Append('\n');
			}
			foreach (ItemProgression entry in Entries)
			{
				stringBuilder.Append(entry.ItemId).Append('\t').Append(entry.Biome?.ToString() ?? "-")
					.Append('\t')
					.Append(entry.Depth.ToString(CultureInfo.InvariantCulture))
					.Append('\t')
					.Append(entry.Uses.ToString(CultureInfo.InvariantCulture))
					.Append('\t')
					.Append(entry.ToPrepare ? '1' : '0');
				ItemFamily itemFamily = FamilyOf(entry.ItemId);
				if ((object)itemFamily != null)
				{
					stringBuilder.Append('\t').Append(itemFamily.Id).Append('\t')
						.Append(Roles[(int)itemFamily.Role]);
				}
				MaterialGroup? materialGroup = GroupOf(entry.ItemId);
				if (materialGroup.HasValue)
				{
					MaterialGroup valueOrDefault = materialGroup.GetValueOrDefault();
					stringBuilder.Append('\t').Append(valueOrDefault.ToString().ToLowerInvariant());
				}
				stringBuilder.Append('\n');
			}
			return stringBuilder.ToString();
		}

		private static (ItemProgression, ItemFamily?, MaterialGroup?)? Entry(string[] fields)
		{
			if (fields.Length < 5 || fields.Length > 8 || fields[0].Length == 0 || (fields[4] != "0" && fields[4] != "1"))
			{
				return null;
			}
			MaterialGroup? item = null;
			if (fields.Length == 6 || fields.Length == 8)
			{
				item = (Groups.TryGetValue(fields[^1], out var value) ? new MaterialGroup?(value) : ((MaterialGroup?)null));
				if (!item.HasValue)
				{
					return null;
				}
			}
			ItemFamily item2 = null;
			if (fields.Length >= 7)
			{
				int num = Array.IndexOf(Roles, fields[6]);
				if (fields[5].Length == 0 || num < 0)
				{
					return null;
				}
				item2 = new ItemFamily(fields[5], (FamilyRole)num);
			}
			if (!TryBiome(fields[1], out var biome))
			{
				return null;
			}
			if (!int.TryParse(fields[2], NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				return null;
			}
			if (!int.TryParse(fields[3], NumberStyles.None, CultureInfo.InvariantCulture, out var result2))
			{
				return null;
			}
			return (new ItemProgression(fields[0], biome, result, result2, fields[4] == "1"), item2, item);
		}

		private static bool TryBiome(string text, out Biome? biome)
		{
			biome = null;
			if (text == "-")
			{
				return true;
			}
			if (Biomes.TryParse(text, out var biome2))
			{
				biome = biome2;
				return true;
			}
			return false;
		}

		internal static ProgressionTable FromResource(Assembly assembly, string name)
		{
			using Stream stream = assembly.GetManifestResourceStream(name) ?? throw new InvalidOperationException("Missing resource " + name + ".");
			using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
			return Parse(streamReader.ReadToEnd());
		}
	}
	public enum MaterialGroup
	{
		Construction,
		SmelterFuel,
		Metals,
		Loot,
		Components,
		Cooking,
		Seeds,
		Treasures,
		Other
	}
	public static class MaterialGroups
	{
		public static MaterialGroup Row(MaterialGroup group)
		{
			if (group != MaterialGroup.SmelterFuel)
			{
				return group;
			}
			return MaterialGroup.Metals;
		}
	}
	public static class MaterialGroupInference
	{
		private sealed class Uses
		{
			private readonly Dictionary<string, int> _structural = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _planting = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _building = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _cooking = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _gear = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _intermediate = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, int> _recipes = new Dictionary<string, int>(StringComparer.Ordinal);

			private readonly Dictionary<string, long> _maxAmount = new Dictionary<string, long>(StringComparer.Ordinal);

			private readonly Dictionary<string, List<string>> _outputs = new Dictionary<string, List<string>>(StringComparer.Ordinal);

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

			private readonly HashSet<string> _materials;

			private Uses(HashSet<string> materials)
			{
				_materials = materials;
			}

			public int Structural(string id)
			{
				return Count(_structural, id);
			}

			public int Planting(string id)
			{
				return Count(_planting, id);
			}

			public int Recipes(string id)
			{
				return Count(_recipes, id);
			}

			public int Gear(string id)
			{
				return Count(_gear, id);
			}

			public int Intermediate(string id)
			{
				return Count(_intermediate, id);
			}

			public bool IsMostlyCooking(string id)
			{
				int num = Count(_cooking, id);
				if (num > Count(_building, id) && num > Count(_planting, id))
				{
					return num > Count(_intermediate, id);
				}
				return false;
			}

			public long MaxAmount(string id)
			{
				return _maxAmount[id];
			}

			public bool OnlyMakesDeadEnds(string id)
			{
				if (_outputs.TryGetValue(id, out List<string> value))
				{
					return value.All((string output) => _materials.Contains(output) && !_used.Contains(output));
				}
				return false;
			}

			public static Uses Of(GameData data, Dictionary<string, string> idOf, Dictionary<string, string?> typeOf)
			{
				Uses uses = new Uses(new HashSet<string>(from item in data.Items
					where item.ItemType == "Material" && !string.IsNullOrEmpty(item.ItemId)
					select item.ItemId, StringComparer.Ordinal));
				foreach (GameConversion item in data.Conversions.Where((GameConversion conversion) => idOf.ContainsKey(conversion.From)))
				{
					uses._used.Add(idOf[item.From]);
				}
				foreach (GameCraft piece in data.Pieces)
				{
					foreach (string key in Inputs(piece, idOf).Keys)
					{
						uses._used.Add(key);
						if (piece.Tool == "Hammer" && piece.Category != null && StructuralCategories.Contains(piece.Category))
						{
							Add(uses._structural, key);
						}
						else if (piece.Tool != null && PlantingTools.Contains(piece.Tool))
						{
							Add(uses._planting, key);
						}
						else if (piece.Tool == "Feaster")
						{
							Add(uses._cooking, key);
						}
						else
						{
							Add(uses._building, key);
						}
					}
				}
				foreach (GameCraft recipe in data.Recipes)
				{
					string value;
					string text = (idOf.TryGetValue(recipe.Output, out value) ? value : null);
					string value2;
					PanelCategory panelCategory = (typeOf.TryGetValue(recipe.Output, out value2) ? PanelCategories.Of(value2, isFood: false, toPrepare: false) : PanelCategory.Misc);
					foreach (KeyValuePair<string, long> item2 in Inputs(recipe, idOf))
					{
						uses._used.Add(item2.Key);
						Add(uses._recipes, item2.Key);
						uses._maxAmount.TryGetValue(item2.Key, out var value3);
						uses._maxAmount[item2.Key] = Math.Max(value3, item2.Value);
						if (text != null)
						{
							if (!uses._outputs.TryGetValue(item2.Key, out List<string> value4))
							{
								value4 = (uses._outputs[item2.Key] = new List<string>());
							}
							value4.Add(text);
						}
						if (recipe.Station != null && CookingStations.Contains(recipe.Station))
						{
							Add(uses._cooking, item2.Key);
							continue;
						}
						switch (panelCategory)
						{
						case PanelCategory.Ammo:
						case PanelCategory.Weapons:
						case PanelCategory.Armor:
						case PanelCategory.Tools:
							Add(uses._gear, item2.Key);
							break;
						case PanelCategory.MeadsAndPotions:
							Add(uses._cooking, item2.Key);
							break;
						default:
							Add(uses._intermediate, item2.Key);
							break;
						}
					}
				}
				return uses;
			}

			private static Dictionary<string, long> Inputs(GameCraft craft, Dictionary<string, string> idOf)
			{
				Dictionary<string, long> dictionary = new Dictionary<string, long>(StringComparer.Ordinal);
				for (int i = 0; i < craft.Inputs.Count; i++)
				{
					if (idOf.TryGetValue(craft.Inputs[i], out string value))
					{
						dictionary.TryGetValue(value, out var value2);
						dictionary[value] = value2 + ((craft.Amounts == null || i >= craft.Amounts.Count) ? 1 : craft.Amounts[i]);
					}
				}
				return dictionary;
			}

			private static void Add(Dictionary<string, int> counts, string id)
			{
				counts.TryGetValue(id, out var value);
				counts[id] = value + 1;
			}

			private static int Count(Dictionary<string, int> counts, string id)
			{
				if (!counts.TryGetValue(id, out var value))
				{
					return 0;
				}
				return value;
			}
		}

		public const int Structural = 3;

		private const string MaterialType = "Material";

		private const string Hammer = "Hammer";

		private const string Feaster = "Feaster";

		private static readonly HashSet<string> StructuralCategories = new HashSet<string>(StringComparer.Ordinal) { "BuildingWorkbench", "BuildingStonecutter", "DeepNorth" };

		private static readonly HashSet<string> PlantingTools = new HashSet<string>(StringComparer.Ordinal) { "Cultivator", "Hoe" };

		private static readonly HashSet<string> CookingStations = new HashSet<string>(StringComparer.Ordinal) { "$piece_cauldron", "$piece_preptable", "$piece_meadcauldron" };

		public static IReadOnlyDictionary<string, MaterialGroup> Infer(GameData data, IReadOnlyDictionary<string, ItemFamily> families)
		{
			if ((object)data == null)
			{
				throw new ArgumentNullException("data");
			}
			if (families == null)
			{
				throw new ArgumentNullException("families");
			}
			Dictionary<string, string> idOf = data.Items.Where((GameItem item) => !string.IsNullOrEmpty(item.ItemId)).GroupBy<GameItem, string>((GameItem item) => item.Prefab, StringComparer.Ordinal).ToDictionary<IGrouping<string, GameItem>, string, string>((IGrouping<string, GameItem> group) => group.Key, (IGrouping<string, GameItem> group) => FamilyInference.Least(group.Select((GameItem item) => item.ItemId)), StringComparer.Ordinal);
			Dictionary<string, string> typeOf = data.Items.GroupBy<GameItem, string>((GameItem item) => item.Prefab, StringComparer.Ordinal).ToDictionary<IGrouping<string, GameItem>, string, string>((IGrouping<string, GameItem> group) => group.Key, (IGrouping<string, GameItem> group) => LeastType((from item in @group
				where item.ItemType != null
				select item.ItemType).ToList()), StringComparer.Ordinal);
			HashSet<string> prepared = new HashSet<string>(from conversion in data.Conversions
				where conversion.Prepares && idOf.ContainsKey(conversion.From)
				select idOf[conversion.From], StringComparer.Ordinal);
			HashSet<string> hashSet = new HashSet<string>(from conversion in data.Conversions
				where !conversion.Prepares && !string.IsNullOrEmpty(conversion.Fuel) && idOf.ContainsKey(conversion.Fuel)
				select idOf[conversion.Fuel], StringComparer.Ordinal);
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (GameItem item in data.Items.Where((GameItem item) => !string.IsNullOrEmpty(item.ItemId)))
			{
				dictionary.TryGetValue(item.ItemId, out var value);
				dictionary[item.ItemId] = Math.Max(value, item.Value);
			}
			Uses uses = Uses.Of(data, idOf, typeOf);
			Dictionary<string, MaterialGroup> dictionary2 = new Dictionary<string, MaterialGroup>(StringComparer.Ordinal);
			foreach (string item2 in from id in (from item in data.Items
					where item.ItemType == "Material" && !string.IsNullOrEmpty(item.ItemId)
					select item.ItemId).Distinct<string>(StringComparer.Ordinal)
				where !prepared.Contains(id)
				select id)
			{
				dictionary2[item2] = GroupOf(item2, dictionary[item2] > 0, hashSet.Contains(item2), families.ContainsKey(item2), uses);
			}
			return dictionary2;
		}

		private static string? LeastType(List<string> types)
		{
			if (types.Count != 0)
			{
				return FamilyInference.Least(types);
			}
			return null;
		}

		private static MaterialGroup GroupOf(string id, bool hasValue, bool isFuel, bool inFamily, Uses uses)
		{
			if (hasValue)
			{
				return MaterialGroup.Treasures;
			}
			if (isFuel)
			{
				return MaterialGroup.SmelterFuel;
			}
			if (inFamily)
			{
				return MaterialGroup.Metals;
			}
			if (uses.Structural(id) >= 3)
			{
				return MaterialGroup.Construction;
			}
			if (uses.Planting(id) >= 1 && uses.Recipes(id) == 0)
			{
				return MaterialGroup.Seeds;
			}
			if (uses.Gear(id) == 0 && uses.IsMostlyCooking(id))
			{
				return MaterialGroup.Cooking;
			}
			if (uses.Gear(id) + uses.Intermediate(id) > 0)
			{
				if (uses.MaxAmount(id) > 1)
				{
					return MaterialGroup.Loot;
				}
				if (!uses.OnlyMakesDeadEnds(id))
				{
					return MaterialGroup.Components;
				}
				return MaterialGroup.Other;
			}
			return MaterialGroup.Other;
		}
	}
	public sealed record ItemFacts(string? ItemType, bool IsFood);
	public sealed record PanelItem(ItemKey Item, long Units, int MaxStack, PanelCategory Category, ItemProgression? Progression, PanelPiece? Piece = null, MaterialGroup? Group = null)
	{
		public int GroupRank
		{
			get
			{
				if (Category == PanelCategory.Materials)
				{
					return (int)(Group ?? ((MaterialGroup)2147483647));
				}
				return 0;
			}
		}

		public int RowBlock
		{
			get
			{
				if (Category == PanelCategory.Materials)
				{
					MaterialGroup? materialGroup = Group;
					if (materialGroup.HasValue)
					{
						MaterialGroup valueOrDefault = materialGroup.GetValueOrDefault();
						return (int)MaterialGroups.Row(valueOrDefault);
					}
					return int.MaxValue;
				}
				return 0;
			}
		}
	}
	public sealed record PanelPiece(ChestSlot Slot, PieceFingerprint? Seen);
	public sealed record PanelSection(PanelCategory Category, IReadOnlyList<PanelItem> Items);
	public static class NetworkPanelContent
	{
		public static IReadOnlyList<PanelSection> Build(IEnumerable<ContainerSnapshot?>? chests, int reserve, Func<string, ItemFacts?> facts, ProgressionTable table, Func<string, int, PieceFingerprint?>? pieceOf = null)
		{
			if (facts == null)
			{
				throw new ArgumentNullException("facts");
			}
			if (table == null)
			{
				throw new ArgumentNullException("table");
			}
			List<ContainerSnapshot> list = (from chest in Deduplication.ById(chests, (ContainerSnapshot chest) => chest.Id)
				select chest with
				{
					Items = ChestReserve.Usable(chest.Items, reserve)
				}).ToList();
			List<(ItemStack, string)> list2 = new List<(ItemStack, string)>();
			if (pieceOf != null)
			{
				for (int num = 0; num < list.Count; num++)
				{
					string chestId = list[num].Id;
					list2.AddRange(from stack in list[num].Items.Where(IsPiece)
						select (stack: stack, chestId: chestId));
					list[num] = list[num]with
					{
						Items = list[num].Items.Where((ItemStack stack) => !IsPiece(stack)).ToList()
					};
				}
			}
			IReadOnlyDictionary<ItemKey, long> byItemAndQuality = new ResourceCounter().Count(null, list).ByItemAndQuality;
			Dictionary<ItemKey, int> maxStack = new Dictionary<ItemKey, int>();
			foreach (ItemStack item in list.SelectMany((ContainerSnapshot chest) => chest.Items))
			{
				ItemKey key = new ItemKey(item.ItemId, item.Quality);
				maxStack.TryGetValue(key, out var value);
				maxStack[key] = Math.Max(value, item.MaxStack);
			}
			return (from item in (from item in byItemAndQuality.Select((KeyValuePair<ItemKey, long> entry) => Item(entry.Key, entry.Value, maxStack[entry.Key], null)).Concat(list2.Select<(ItemStack, string), PanelItem>(((ItemStack Stack, string Chest) piece) => Item(new ItemKey(piece.Stack.ItemId, piece.Stack.Quality), 1L, 1, new PanelPiece(new ChestSlot(piece.Chest, piece.Stack.Slot.Value), pieceOf(piece.Chest, piece.Stack.Slot.Value)))))
					orderby item.Category, item.GroupRank, Lead(item, table).Biome, Lead(item, table).Depth, Lead(item, table).Uses descending
					select item).ThenBy<PanelItem, string>((PanelItem item) => Lead(item, table).Id, StringComparer.Ordinal).ThenBy((PanelItem item) => FamilyOf(item, table)?.Role ?? FamilyRole.Source).ThenBy((PanelItem item) => (int)(item.Progression?.Biome ?? ((Biome)2147483647)))
					.ThenBy((PanelItem item) => item.Progression?.Depth ?? 0)
					.ThenByDescending((PanelItem item) => item.Progression?.Uses ?? 0)
					.ThenBy<PanelItem, string>((PanelItem item) => item.Item.ItemId, StringComparer.Ordinal)
					.ThenBy((PanelItem item) => item.Item.Quality)
					.ThenBy<PanelItem, string>((PanelItem item) => item.Piece?.Slot.Chest, StringComparer.Ordinal)
					.ThenBy((PanelItem item) => item.Piece?.Slot.Slot ?? 0)
				group item by item.Category into @group
				select new PanelSection(@group.Key, @group.ToList())).ToList();
			PanelItem Item(ItemKey item, long count, int max, PanelPiece? piece)
			{
				ItemFacts itemFacts = facts(item.ItemId);
				ItemProgression itemProgression = table.Find(item.ItemId);
				PanelCategory panelCategory = ((itemFacts == null) ? PanelCategory.Misc : PanelCategories.Of(itemFacts.ItemType, itemFacts.IsFood, itemProgression?.ToPrepare ?? false));
				return new PanelItem(item, count, max, panelCategory, itemProgression, piece, (panelCategory == PanelCategory.Materials) ? table.GroupOf(item.ItemId) : ((MaterialGroup?)null));
			}
		}

		private static ItemFamily? FamilyOf(PanelItem item, ProgressionTable table)
		{
			if (item.Category == PanelCategory.Materials)
			{
				ItemFamily itemFamily = table.FamilyOf(item.Item.ItemId);
				if ((object)itemFamily != null && table.Find(itemFamily.Id) != null)
				{
					return itemFamily;
				}
			}
			return null;
		}

		private static (int Biome, int Depth, int Uses, string Id) Lead(PanelItem item, ProgressionTable table)
		{
			ItemFamily itemFamily = FamilyOf(item, table);
			ItemProgression itemProgression = ((itemFamily == null) ? item.Progression : table.Find(itemFamily.Id));
			Biome? biome = itemProgression?.Biome;
			int item2;
			if (biome.HasValue)
			{
				Biome valueOrDefault = biome.GetValueOrDefault();
				item2 = (int)valueOrDefault;
			}
			else
			{
				item2 = int.MaxValue;
			}
			return (Biome: item2, Depth: itemProgression?.Depth ?? 0, Uses: itemProgression?.Uses ?? 0, Id: itemFamily?.Id ?? item.Item.ItemId);
		}

		private static bool IsPiece(ItemStack stack)
		{
			if (stack.MaxStack == 1)
			{
				return stack.Slot.HasValue;
			}
			return false;
		}
	}
	public sealed record PanelHeader(PanelCategory Category, float Top);
	public sealed class NetworkPanelLayout
	{
		public const float HeaderHeight = 0.5f;

		private readonly Dictionary<(int X, int Y), int> _itemAt;

		public const int GrowthHeadroom = 4;

		public int Width { get; }

		public int Height { get; }

		public float DrawnHeight { get; }

		public IReadOnlyList<PanelItem> Items { get; }

		public IReadOnlyList<PanelCell> Cells { get; }

		public IReadOnlyList<PanelHeader> Headers { get; }

		private NetworkPanelLayout(int width, IReadOnlyList<PanelItem> items, IReadOnlyList<PanelCell> cells, IReadOnlyList<PanelHeader> headers, int height)
		{
			Width = width;
			Items = items;
			Cells = cells;
			Headers = headers;
			Height = height;
			DrawnHeight = (float)height + (float)headers.Count * 0.5f;
			_itemAt = Enumerable.Range(0, cells.Count).ToDictionary((int i) => (X: cells[i].X, Y: cells[i].Y));
		}

		public static NetworkPanelLayout Of(IEnumerable<PanelSection?>? sections, int width)
		{
			width = Math.Max(1, width);
			List<PanelItem> list = new List<PanelItem>();
			List<PanelCell> list2 = new List<PanelCell>();
			List<PanelHeader> list3 = new List<PanelHeader>();
			int num = 0;
			foreach (PanelSection item in from section in sections ?? Enumerable.Empty<PanelSection>()
				where section != null && section.Items.Count > 0
				select (section))
			{
				float num2 = (float)(list3.Count + 1) * 0.5f;
				list3.Add(new PanelHeader(item.Category, (float)num + (float)list3.Count * 0.5f));
				int num3 = 0;
				int num4 = num;
				for (int num5 = 0; num5 < item.Items.Count; num5++)
				{
					if (num3 > 0 && item.Items[num5].RowBlock != item.Items[num5 - 1].RowBlock)
					{
						num3 = 0;
						num4++;
					}
					list.Add(item.Items[num5]);
					list2.Add(new PanelCell(num3, num4, num3, (float)num4 + num2));
					if (++num3 == width)
					{
						num3 = 0;
						num4++;
					}
				}
				num = ((num3 > 0) ? (num4 + 1) : num4);
			}
			return new NetworkPanelLayout(width, list, list2, list3, num);
		}

		public int GridRows(int shown)
		{
			int num = Math.Max(1, (int)Math.Ceiling(DrawnHeight));
			if (shown > 0)
			{
				if (shown < num)
				{
					return num + 4;
				}
				return shown;
			}
			return num;
		}

		public bool HasSameCells(NetworkPanelLayout? other)
		{
			if (other != null && other.Width == Width && Cells.SequenceEqual(other.Cells))
			{
				return Enumerable.Range(0, Items.Count).All((int i) => Items[i]with
				{
					Units = 0L
				} == other.Items[i]with
				{
					Units = 0L
				});
			}
			return false;
		}

		public PanelItem? ItemAt(int x, int y)
		{
			if (!_itemAt.TryGetValue((x, y), out var value))
			{
				return null;
			}
			return Items[value];
		}
	}
	public static class NetworkPanelWidth
	{
		public static int Columns(int normalColumns, double spareSpace, double cellSpace)
		{
			int num = Math.Max(1, normalColumns);
			double num2 = Math.Floor(spareSpace / cellSpace);
			if (cellSpace <= 0.0 || !(num2 >= 1.0))
			{
				return num;
			}
			return (int)Math.Min((double)num + num2, 2147483647.0);
		}
	}
	public enum PanelCategory
	{
		Materials,
		ToPrepare,
		Food,
		MeadsAndPotions,
		Ammo,
		Weapons,
		Armor,
		Tools,
		Trophies,
		Fish,
		Misc
	}
	public static class PanelCategories
	{
		private static readonly Dictionary<string, PanelCategory> ByType = new Dictionary<string, PanelCategory>(StringComparer.Ordinal)
		{
			["Material"] = PanelCategory.Materials,
			["Consumable"] = PanelCategory.MeadsAndPotions,
			["Ammo"] = PanelCategory.Ammo,
			["AmmoNonEquipable"] = PanelCategory.Ammo,
			["OneHandedWeapon"] = PanelCategory.Weapons,
			["TwoHandedWeapon"] = PanelCategory.Weapons,
			["TwoHandedWeaponLeft"] = PanelCategory.Weapons,
			["Bow"] = PanelCategory.Weapons,
			["Shield"] = PanelCategory.Weapons,
			["Helmet"] = PanelCategory.Armor,
			["Chest"] = PanelCategory.Armor,
			["Legs"] = PanelCategory.Armor,
			["Shoulder"] = PanelCategory.Armor,
			["Utility"] = PanelCategory.Armor,
			["Trinket"] = PanelCategory.Armor,
			["Tool"] = PanelCategory.Tools,
			["Torch"] = PanelCategory.Tools,
			["Trophy"] = PanelCategory.Trophies,
			["Fish"] = PanelCategory.Fish
		};

		public static PanelCategory Of(string? itemType, bool isFood, bool toPrepare)
		{
			if (itemType == null)
			{
				return PanelCategory.Misc;
			}
			if (!ByType.TryGetValue(itemType, out var value))
			{
				return PanelCategory.Misc;
			}
			switch (value)
			{
			case PanelCategory.Materials:
				if (toPrepare)
				{
					return PanelCategory.ToPrepare;
				}
				break;
			case PanelCategory.MeadsAndPotions:
				if (isFood)
				{
					return PanelCategory.Food;
				}
				break;
			}
			return value;
		}
	}
	public sealed record ChestSlot(string Chest, int Slot);
	public sealed class PanelTakePlan : IWithdrawingPlan, INetworkPlan
	{
		public ItemKey Item { get; }

		public ChestSlot? Piece { get; }

		public IReadOnlyList<Withdrawal> Withdrawals { get; }

		public IReadOnlyList<Withdrawal> FirstUse => Withdrawals;

		public IReadOnlyList<string> ContainersTouched { get; }

		public bool IsEmpty
		{
			get
			{
				if (Withdrawals.Count == 0)
				{
					return (object)Piece == null;
				}
				return false;
			}
		}

		public long Units
		{
			get
			{
				if ((object)Piece != null)
				{
					return 1L;
				}
				return Withdrawals.Sum((Withdrawal w) => w.Amount);
			}
		}

		private PanelTakePlan(ItemKey item, IReadOnlyList<Withdrawal> withdrawals, ChestSlot? piece)
		{
			Item = item;
			Withdrawals = withdrawals;
			Piece = piece;
			IReadOnlyList<string> readOnlyList;
			if (!(piece != null))
			{
				readOnlyList = ContainerIds.Touched(withdrawals.Select((Withdrawal w) => w.ContainerId));
			}
			else
			{
				IReadOnlyList<string> readOnlyList2 = new string[1] { piece.Chest };
				readOnlyList = readOnlyList2;
			}
			ContainersTouched = readOnlyList;
		}

		public static PanelTakePlan OfPiece(ItemKey item, ChestSlot piece)
		{
			return new PanelTakePlan(item, Array.Empty<Withdrawal>(), piece ?? throw new ArgumentNullException("piece"));
		}

		internal static PanelTakePlan OfUnits(ItemKey item, IReadOnlyList<Withdrawal> withdrawals)
		{
			return new PanelTakePlan(item, withdrawals, null);
		}
	}
	public static class PanelTake
	{
		public static PanelTakePlan? Plan(ItemKey item, int wanted, IEnumerable<ContainerSnapshot?>? sources, ModConfig? config = null)
		{
			ModConfig config2 = ModConfig.Validate(config)with
			{
				QualityMatching = QualityMatching.Exact
			};
			List<ContainerSnapshot> containers = (sources ?? Enumerable.Empty<ContainerSnapshot>()).ToList();
			long total = new ResourceCounter(config2).Count(null, containers).GetTotal(item.ItemId, item.Quality);
			int num = (int)Math.Min(wanted, total);
			if (num <= 0)
			{
				return null;
			}
			PlanResult planResult = new ConsumptionPlanner(config2).Plan(new Requirement[1]
			{
				new Requirement(item.ItemId, num, item.Quality)
			}, null, containers);
			return PanelTakePlan.OfUnits(item, planResult.Plan.Withdrawals);
		}

		public static ChestSlot? PieceAt(IEnumerable<ContainerSnapshot?>? chests, ItemKey item, ChestSlot slot)
		{
			if (!Deduplication.ById(chests, (ContainerSnapshot chest) => chest.Id).Any((ContainerSnapshot chest) => chest.Id == slot.Chest && chest.Items.Any((ItemStack stack) => stack.Amount > 0 && stack.Slot == slot.Slot && stack.Quality == item.Quality && string.Equals(stack.ItemId, item.ItemId, StringComparison.Ordinal))))
			{
				return null;
			}
			return slot;
		}
	}
	public sealed record GameItem(string Prefab, string ItemId, string? ItemType = null, int Value = 0);
	public sealed record GameSource(string Prefab, string Biomes);
	public sealed record GameYield(string Prefab, IReadOnlyList<string> Items, IReadOnlyList<string> Spawns);
	public sealed record GameCraft(string Output, IReadOnlyList<string> Inputs, IReadOnlyList<int>? Amounts = null, string? Station = null, string? Tool = null, string? Category = null);
	public sealed record GameConversion(string From, string To, bool Prepares, string? Fuel = null);
	public sealed record GameData(IReadOnlyList<GameItem> Items, IReadOnlyList<GameSource> Sources, IReadOnlyList<GameYield> Yields, IReadOnlyList<GameCraft> Recipes, IReadOnlyList<GameCraft> Pieces, IReadOnlyList<GameConversion> Conversions);
	public static class ProgressionInference
	{
		private const int WideSource = 3;

		public static ProgressionTable Infer(GameData data)
		{
			if ((object)data == null)
			{
				throw new ArgumentNullException("data");
			}
			Dictionary<string, GameYield> yields = data.Yields.GroupBy<GameYield, string>((GameYield entry) => entry.Prefab, StringComparer.Ordinal).ToDictionary<IGrouping<string, GameYield>, string, GameYield>((IGrouping<string, GameYield> group) => group.Key, (IGrouping<string, GameYield> group) => new GameYield(group.Key, group.SelectMany((GameYield entry) => entry.Items).ToList(), group.SelectMany((GameYield entry) => entry.Spawns).ToList()), StringComparer.Ordinal);
			Dictionary<string, int> narrow = new Dictionary<string, int>(StringComparer.Ordinal);
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (GameSource source in data.Sources)
			{
				List<int> list = Biomes(source.Biomes);
				if (list.Count == 0)
				{
					continue;
				}
				Dictionary<string, int> values = ((list.Count >= 3) ? dictionary : narrow);
				foreach (string item in Yielded(source.Prefab, yields))
				{
					Lower(values, item, list.Min());
				}
			}
			Dictionary<string, int> dictionary2 = new Dictionary<string, int>(narrow, StringComparer.Ordinal);
			foreach (KeyValuePair<string, int> item2 in dictionary.Where((KeyValuePair<string, int> entry) => !narrow.ContainsKey(entry.Key)))
			{
				dictionary2[item2.Key] = item2.Value;
			}
			Dictionary<string, int> dictionary3 = new Dictionary<string, int>(dictionary2, StringComparer.Ordinal);
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			while (true)
			{
				PropagateBiomes(data, yields, dictionary3);
				Dictionary<string, int> dictionary4 = WithKnownIngredients(data, dictionary3);
				if (dictionary4.Count == 0)
				{
					break;
				}
				foreach (KeyValuePair<string, int> item3 in dictionary4)
				{
					dictionary3[item3.Key] = item3.Value;
					hashSet.Add(item3.Key);
				}
			}
			return Table(data, dictionary3, Depths(data, yields, dictionary3, dictionary2, hashSet));
		}

		internal static List<int> Biomes(string? flags)
		{
			List<int> list = new List<int>();
			string[] array = flags?.Split(',') ?? Array.Empty<string>();
			for (int i = 0; i < array.Length; i++)
			{
				if (ChestNetwork.Core.Panel.Biomes.TryParse(array[i].Trim(), out var biome) && !list.Contains((int)biome))
				{
					list.Add((int)biome);
				}
			}
			return list;
		}

		private static IEnumerable<string> Yielded(string prefab, Dictionary<string, GameYield> yields)
		{
			HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal);
			Stack<string> pending = new Stack<string>();
			pending.Push(prefab);
			while (pending.Count > 0)
			{
				string text = pending.Pop();
				if (!seen.Add(text) || !yields.TryGetValue(text, out GameYield yield))
				{
					continue;
				}
				foreach (string item in yield.Items)
				{
					yield return item;
				}
				foreach (string spawn in yield.Spawns)
				{
					pending.Push(spawn);
				}
				yield = null;
			}
		}

		private static void PropagateBiomes(GameData data, Dictionary<string, GameYield> yields, Dictionary<string, int> biome)
		{
			bool flag = true;
			while (flag)
			{
				flag = false;
				foreach (GameConversion conversion in data.Conversions)
				{
					if (biome.TryGetValue(conversion.From, out var value))
					{
						flag |= Lower(biome, conversion.To, value);
					}
				}
				foreach (GameCraft recipe in data.Recipes)
				{
					int? num = Needs(recipe, biome);
					if (num.HasValue)
					{
						int valueOrDefault = num.GetValueOrDefault();
						flag |= Lower(biome, recipe.Output, valueOrDefault);
					}
				}
				foreach (GameCraft piece in data.Pieces)
				{
					int? num = Needs(piece, biome);
					if (!num.HasValue)
					{
						continue;
					}
					int valueOrDefault2 = num.GetValueOrDefault();
					foreach (string item in Yielded(piece.Output, yields))
					{
						flag |= Lower(biome, item, valueOrDefault2);
					}
				}
			}
		}

		private static Dictionary<string, int> Depths(GameData data, Dictionary<string, GameYield> yields, Dictionary<string, int> biome, Dictionary<string, int> seeded, HashSet<string> guessed)
		{
			Dictionary<string, int> depth = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (KeyValuePair<string, int> item in biome)
			{
				if (guessed.Contains(item.Key) || (seeded.TryGetValue(item.Key, out var value) && value == item.Value))
				{
					depth[item.Key] = 0;
				}
			}
			foreach (GameCraft piece in data.Pieces)
			{
				int? num = Needs(piece, biome);
				if (!num.HasValue)
				{
					continue;
				}
				int needs = num.GetValueOrDefault();
				foreach (string item2 in from grown in Yielded(piece.Output, yields)
					where biome[grown] == needs
					select grown)
				{
					depth[item2] = 0;
				}
			}
			bool flag = true;
			while (flag)
			{
				flag = false;
				foreach (GameConversion conversion in data.Conversions)
				{
					if (biome.TryGetValue(conversion.From, out var value2) && value2 == biome[conversion.To] && depth.TryGetValue(conversion.From, out var value3))
					{
						flag |= Lower(depth, conversion.To, value3 + 1);
					}
				}
				foreach (GameCraft recipe in data.Recipes)
				{
					int? num = Needs(recipe, biome);
					if (!num.HasValue)
					{
						continue;
					}
					int valueOrDefault = num.GetValueOrDefault();
					if (valueOrDefault == biome[recipe.Output] && recipe.Inputs.All(depth.ContainsKey))
					{
						flag |= Lower(depth, recipe.Output, recipe.Inputs.Max((string input) => depth[input]) + 1);
					}
				}
			}
			return depth;
		}

		private static int? Needs(GameCraft craft, Dictionary<string, int> biome)
		{
			if (craft.Inputs.Count != 0 && craft.Inputs.All(biome.ContainsKey))
			{
				return craft.Inputs.Max((string input) => biome[input]);
			}
			return null;
		}

		private static Dictionary<string, int> WithKnownIngredients(GameData data, Dictionary<string, int> biome)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (GameCraft recipe in data.Recipes)
			{
				List<int> list = (from input in recipe.Inputs.Where(biome.ContainsKey)
					select biome[input]).ToList();
				if (list.Count == 0)
				{
					continue;
				}
				foreach (string item in recipe.Inputs.Where((string input) => !biome.ContainsKey(input)))
				{
					Lower(dictionary, item, list.Max());
				}
			}
			return dictionary;
		}

		private static bool Lower(Dictionary<string, int> values, string item, int candidate)
		{
			if (values.TryGetValue(item, out var value) && value <= candidate)
			{
				return false;
			}
			values[item] = candidate;
			return true;
		}

		private static ProgressionTable Table(GameData data, Dictionary<string, int> biome, Dictionary<string, int> depth)
		{
			Dictionary<string, int> uses = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (string item in data.Recipes.Concat(data.Pieces).SelectMany((GameCraft craft) => craft.Inputs))
			{
				uses.TryGetValue(item, out var value);
				uses[item] = value + 1;
			}
			HashSet<string> prepared = new HashSet<string>(from conversion in data.Conversions
				where conversion.Prepares
				select conversion.From, StringComparer.Ordinal);
			IReadOnlyDictionary<string, ItemFamily> families = FamilyInference.Infer(data);
			IReadOnlyDictionary<string, MaterialGroup> groups = MaterialGroupInference.Infer(data, families);
			return ProgressionTable.Of(data.Items.Where((GameItem item) => !string.IsNullOrEmpty(item.ItemId)).GroupBy<GameItem, string>((GameItem item) => item.ItemId, StringComparer.Ordinal).Select(delegate(IGrouping<string, GameItem> group)
			{
				List<(int, int)> list = (from item in @group
					where biome.ContainsKey(item.Prefab)
					select (biome[item.Prefab], depth[item.Prefab])).ToList();
				(int, int)? tuple = ((list.Count == 0) ? (((int, int)?)null) : new(int, int)?(list.Min()));
				int value2;
				return new ItemProgression(group.Key, tuple.HasValue ? new Biome?((Biome)tuple.Value.Item1) : ((Biome?)null), tuple?.Item2 ?? 0, group.Sum((GameItem item) => uses.TryGetValue(item.Prefab, out value2) ? value2 : 0), group.Any((GameItem item) => prepared.Contains(item.Prefab)));
			}), families, groups);
		}
	}
	public static class TakeAmount
	{
		public static int Limit(int maxStack, long available)
		{
			return (int)Math.Max(0L, Math.Min(Math.Max(1, maxStack), available));
		}
	}
}
namespace ChestNetwork.Core.Multiplayer
{
	public sealed class CommitHold
	{
		private readonly double _maxSeconds;

		private readonly double _quietSeconds;

		private readonly double _staleSeconds;

		private object? _action;

		private double _since;

		private double _lastSeen;

		public bool IsHolding => _action != null;

		public CommitHold(double maxSeconds, double quietSeconds, double staleSeconds)
		{
			if (!(maxSeconds > 0.0) || double.IsInfinity(maxSeconds))
			{
				throw new ArgumentOutOfRangeException("maxSeconds", maxSeconds, "Must be a positive finite number.");
			}
			if (!(quietSeconds >= 0.0) || quietSeconds > maxSeconds)
			{
				throw new ArgumentOutOfRangeException("quietSeconds", quietSeconds, "Must be between 0 and the maximum.");
			}
			if (!(staleSeconds > 0.0) || double.IsInfinity(staleSeconds))
			{
				throw new ArgumentOutOfRangeException("staleSeconds", staleSeconds, "Must be a positive finite number.");
			}
			_maxSeconds = maxSeconds;
			_quietSeconds = quietSeconds;
			_staleSeconds = staleSeconds;
		}

		public bool ShouldHold(object action, bool waitsForContainers, double now)
		{
			if (action == null || !waitsForContainers)
			{
				End();
				return false;
			}
			if (action != _action || now - _lastSeen > _staleSeconds)
			{
				_action = action;
				_since = now;
			}
			_lastSeen = now;
			if (now - _since >= _maxSeconds)
			{
				End();
				return false;
			}
			return true;
		}

		public bool IsActive(double now)
		{
			if (_action != null)
			{
				return now - _lastSeen <= _staleSeconds;
			}
			return false;
		}

		public bool IsQuiet(double now)
		{
			if (_action != null)
			{
				return now - _since < _quietSeconds;
			}
			return false;
		}

		public double? HeldSeconds(double now)
		{
			if (_action == null)
			{
				return null;
			}
			return now - _since;
		}

		public void End()
		{
			_action = null;
		}
	}
	public enum ExpiredGrantAction
	{
		None,
		Use,
		HandBack
	}
	public static class ExpiredGrantPolicy
	{
		public static ExpiredGrantAction Decide(bool isOwner, uint localRevision, uint grantedRevision)
		{
			if (!isOwner)
			{
				return ExpiredGrantAction.None;
			}
			if (localRevision < grantedRevision)
			{
				return ExpiredGrantAction.HandBack;
			}
			return ExpiredGrantAction.Use;
		}
	}
	public static class ModConfigCodec
	{
		private const string Header = "cn1";

		private const string AllTypes = "*";

		public static string Encode(ModConfig config)
		{
			if ((object)config == null)
			{
				throw new ArgumentNullException("config");
			}
			string text = ((config.AllowedStationTypes == null) ? "*" : Names(config.AllowedStationTypes));
			FillSettings fillSettings = config.AutoRefuelSettings ?? FillSettings.Default;
			string text2 = string.Join(",", (from kind in ((IEnumerable<ContainerKind>)(((object)config.ExcludedContainerKinds) ?? ((object)Array.Empty<ContainerKind>()))).Distinct()
				orderby kind
				select kind).Select(delegate(ContainerKind kind)
			{
				int num = (int)kind;
				return num.ToString(CultureInfo.InvariantCulture);
			}));
			return string.Join("|", "cn1", "rule=" + ((int)config.ConnectionRule).ToString(CultureInfo.InvariantCulture), "inclusive=" + Flag(config.InclusiveBoundaries), "types=" + text, "excluded=" + text2, "quality=" + ((int)config.QualityMatching).ToString(CultureInfo.InvariantCulture), "equipped=" + Flag(config.AllowEquippedItems), "keep=" + Flag(config.ServerKeepsChests), "refuel=" + Flag(config.AutoRefuel), "refuelreserve=" + fillSettings.MinimumReserve.ToString(CultureInfo.InvariantCulture), "refuelscope=" + ((int)fillSettings.ReserveScope).ToString(CultureInfo.InvariantCulture), "refuelmax=" + fillSettings.MaxPerAction.GetValueOrDefault().ToString(CultureInfo.InvariantCulture), "refuelforbidden=" + Names((IEnumerable<string>)(((object)fillSettings.ForbiddenItems) ?? ((object)Array.Empty<string>()))), "chestreserve=" + Math.Max(0, config.ChestReserve).ToString(CultureInfo.InvariantCulture), "openingdelay=" + Math.Max(0, config.OpeningSafetyDelay).ToString(CultureInfo.InvariantCulture));
		}

		public static bool TryDecode(string? text, out ModConfig config, out string error)
		{
			config = ModConfig.Default;
			if (string.IsNullOrEmpty(text))
			{
				error = "Empty configuration.";
				return false;
			}
			string[] array = text.Split('|');
			if (array[0] != "cn1")
			{
				error = "Unknown configuration format '" + array[0] + "'.";
				return false;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			foreach (string item in array.Skip(1))
			{
				int num = item.IndexOf('=');
				if (num <= 0)
				{
					error = "Malformed entry '" + item + "'.";
					return false;
				}
				string text2 = item.Substring(0, num);
				if (dictionary.ContainsKey(text2))
				{
					error = "Duplicated key '" + text2 + "'.";
					return false;
				}
				dictionary.Add(text2, item.Substring(num + 1));
			}
			if (!TryEnum<ConnectionRule>(dictionary, "rule", out var result, out error) || !TryFlag(dictionary, "inclusive", out var flag, out error) || !TryTypes(dictionary, out IReadOnlyCollection<string> types, out error) || !TryKinds(dictionary, out IReadOnlyCollection<ContainerKind> kinds, out error) || !TryEnum<QualityMatching>(dictionary, "quality", out var result2, out error) || !TryFlag(dictionary, "equipped", out var flag2, out error) || !TryFlag(dictionary, "refuel", out var flag3, out error) || !TryCount(dictionary, "refuelreserve", out var count, out error) || !TryEnum<ReserveScope>(dictionary, "refuelscope", out var result3, out error) || !TryCount(dictionary, "refuelmax", out var count2, out error) || !TryGet(dictionary, "refuelforbidden", out string value, out error) || !TryFlag(dictionary, "keep", out var flag4, out error) || !TryCount(dictionary, "chestreserve", out var count3, out error) || !TryCount(dictionary, "openingdelay", out var count4, out error))
			{
				return false;
			}
			config = ModConfig.Default with
			{
				ConnectionRule = result,
				InclusiveBoundaries = flag,
				AllowedStationTypes = types,
				ExcludedContainerKinds = kinds,
				QualityMatching = result2,
				AllowEquippedItems = flag2,
				AutoRefuel = flag3,
				AutoRefuelSettings = FillSettings.Default with
				{
					InventoryUse = InventoryUse.Never,
					MinimumReserve = count,
					ReserveScope = result3,
					MaxPerAction = ((count2 > 0) ? new int?(count2) : ((int?)null)),
					ForbiddenItems = (IReadOnlyCollection<string>?)(object)Unescape(value)
				},
				ServerKeepsChests = flag4,
				ChestReserve = count3,
				OpeningSafetyDelay = count4
			};
			error = string.Empty;
			return true;
		}

		private static string Flag(bool value)
		{
			if (!value)
			{
				return "0";
			}
			return "1";
		}

		private static string Names(IEnumerable<string> names)
		{
			return string.Join(",", names.Where((string name) => !string.IsNullOrEmpty(name)).Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string name) => name, StringComparer.Ordinal)
				.Select(Uri.EscapeDataString));
		}

		private static string[] Unescape(string value)
		{
			if (value.Length != 0)
			{
				return value.Split(',').Select(Uri.UnescapeDataString).ToArray();
			}
			return Array.Empty<string>();
		}

		private static bool TryCount(Dictionary<string, string> values, string key, out int count, out string error)
		{
			count = 0;
			if (!TryGet(values, key, out string value, out error))
			{
				return false;
			}
			if (!TryInt(value, out count))
			{
				error = "Invalid count '" + value + "' for '" + key + "'.";
				return false;
			}
			return true;
		}

		private static bool TryGet(Dictionary<string, string> values, string key, out string value, out string error)
		{
			if (!values.TryGetValue(key, out value))
			{
				error = "Missing key '" + key + "'.";
				return false;
			}
			error = string.Empty;
			return true;
		}

		private static bool TryFlag(Dictionary<string, string> values, string key, out bool flag, out string error)
		{
			flag = false;
			if (!TryGet(values, key, out string value, out error))
			{
				return false;
			}
			if (value != "0" && value != "1")
			{
				error = "Invalid flag '" + value + "' for '" + key + "'.";
				return false;
			}
			flag = value == "1";
			return true;
		}

		private static bool TryInt(string value, out int number)
		{
			return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out number);
		}

		private static bool TryEnum<T>(Dictionary<string, string> values, string key, out T result, out string error) where T : struct, Enum
		{
			result = default(T);
			if (!TryGet(values, key, out string value, out error))
			{
				return false;
			}
			if (!TryInt(value, out var number) || !Enum.IsDefined(typeof(T), number))
			{
				error = "Invalid value '" + value + "' for '" + key + "'.";
				return false;
			}
			result = (T)Enum.ToObject(typeof(T), number);
			return true;
		}

		private static bool TryTypes(Dictionary<string, string> values, out IReadOnlyCollection<string>? types, out string error)
		{
			types = null;
			if (!TryGet(values, "types", out string value, out error))
			{
				return false;
			}
			if (value == "*")
			{
				return true;
			}
			types = (IReadOnlyCollection<string>?)(object)Unescape(value);
			return true;
		}

		private static bool TryKinds(Dictionary<string, string> values, out IReadOnlyCollection<ContainerKind> kinds, out string error)
		{
			kinds = (IReadOnlyCollection<ContainerKind>)(object)Array.Empty<ContainerKind>();
			if (!TryGet(values, "excluded", out string value, out error))
			{
				return false;
			}
			if (value.Length == 0)
			{
				return true;
			}
			List<ContainerKind> list = new List<ContainerKind>();
			string[] array = value.Split(',');
			foreach (string text in array)
			{
				if (!TryInt(text, out var number) || !Enum.IsDefined(typeof(ContainerKind), number))
				{
					error = "Invalid container kind '" + text + "'.";
					return false;
				}
				list.Add((ContainerKind)number);
			}
			kinds = list;
			return true;
		}
	}
	public enum GrantDecision
	{
		Grant,
		NotOwner,
		InUse,
		NoAccess,
		Reserved
	}
	public static class OwnershipGrantPolicy
	{
		public static GrantDecision Decide(bool isOwner, bool isInUse, bool requesterHasAccess, double reservedUntil, double now)
		{
			return Decide(isOwner, isInUse, requesterHasAccess, reservedUntil, now, ownerUsesSoon: true);
		}

		public static GrantDecision Decide(bool isOwner, bool isInUse, bool requesterHasAccess, double reservedUntil, double now, bool ownerUsesSoon)
		{
			if (!isOwner)
			{
				return GrantDecision.NotOwner;
			}
			if (isInUse)
			{
				return GrantDecision.InUse;
			}
			if (!requesterHasAccess)
			{
				return GrantDecision.NoAccess;
			}
			if (!ownerUsesSoon || !(now < reservedUntil))
			{
				return GrantDecision.Grant;
			}
			return GrantDecision.Reserved;
		}
	}
	public enum OwnershipState
	{
		Idle,
		Requested,
		AwaitingData,
		Unavailable
	}
	public sealed class OwnershipTracker
	{
		private readonly struct Entry
		{
			public OwnershipState State { get; }

			public double Since { get; }

			public uint GrantedRevision { get; }

			public bool Unanswered { get; }

			public Entry(OwnershipState state, double since, uint grantedRevision, bool unanswered = false)
			{
				State = state;
				Since = since;
				GrantedRevision = grantedRevision;
				Unanswered = unanswered;
			}
		}

		private readonly double _requestTimeout;

		private readonly double _retryDelay;

		private readonly double _dataTimeout;

		private readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry>(StringComparer.Ordinal);

		public OwnershipTracker(double requestTimeout, double retryDelay)
			: this(requestTimeout, retryDelay, double.PositiveInfinity)
		{
		}

		public OwnershipTracker(double requestTimeout, double retryDelay, double dataTimeout)
		{
			if (!(requestTimeout > 0.0) || double.IsInfinity(requestTimeout))
			{
				throw new ArgumentOutOfRangeException("requestTimeout", requestTimeout, "Must be a positive finite number.");
			}
			if (!(retryDelay >= 0.0) || double.IsInfinity(retryDelay))
			{
				throw new ArgumentOutOfRangeException("retryDelay", retryDelay, "Must be a non-negative finite number.");
			}
			if (!(dataTimeout > 0.0))
			{
				throw new ArgumentOutOfRangeException("dataTimeout", dataTimeout, "Must be a positive number (infinity for no timeout).");
			}
			_requestTimeout = requestTimeout;
			_retryDelay = retryDelay;
			_dataTimeout = dataTimeout;
		}

		public OwnershipState StateOf(string containerId, double now)
		{
			if (!_entries.TryGetValue(containerId, out var value))
			{
				return OwnershipState.Idle;
			}
			switch (value.State)
			{
			case OwnershipState.Requested:
				if (now - value.Since >= _requestTimeout)
				{
					_entries[containerId] = new Entry(OwnershipState.Unavailable, value.Since + _requestTimeout, 0u, unanswered: true);
					return StateOf(containerId, now);
				}
				break;
			case OwnershipState.AwaitingData:
				if (now - value.Since >= _dataTimeout)
				{
					return OwnershipState.Idle;
				}
				break;
			case OwnershipState.Unavailable:
				if (now - value.Since >= _retryDelay)
				{
					_entries.Remove(containerId);
					return OwnershipState.Idle;
				}
				break;
			}
			return value.State;
		}

		public bool TryBeginRequest(string containerId, double now)
		{
			if (StateOf(containerId, now) != OwnershipState.Idle)
			{
				return false;
			}
			_entries[containerId] = new Entry(OwnershipState.Requested, now, 0u);
			return true;
		}

		public void OnGranted(string containerId, uint dataRevision, double now)
		{
			_entries[containerId] = new Entry(OwnershipState.AwaitingData, now, dataRevision);
		}

		public void OnDenied(string containerId, double now)
		{
			if (!_entries.TryGetValue(containerId, out var value) || value.State != OwnershipState.AwaitingData)
			{
				_entries[containerId] = new Entry(OwnershipState.Unavailable, now, 0u);
			}
		}

		public bool OnDataRevision(string containerId, uint localRevision)
		{
			if (_entries.TryGetValue(containerId, out var value) && value.State == OwnershipState.AwaitingData && localRevision >= value.GrantedRevision)
			{
				_entries.Remove(containerId);
				return true;
			}
			return false;
		}

		public bool IsUsableWhenOwned(string containerId, double now)
		{
			return StateOf(containerId, now) != OwnershipState.AwaitingData;
		}

		public void Forget(string containerId)
		{
			_entries.Remove(containerId);
		}

		public IReadOnlyList<string> AwaitingData()
		{
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, Entry> entry in _entries)
			{
				if (entry.Value.State == OwnershipState.AwaitingData)
				{
					list.Add(entry.Key);
				}
			}
			list.Sort(StringComparer.Ordinal);
			return list;
		}

		public IReadOnlyList<ExpiredGrant> TakeExpired(double now)
		{
			List<ExpiredGrant> list = new List<ExpiredGrant>();
			foreach (KeyValuePair<string, Entry> entry in _entries)
			{
				if (entry.Value.State == OwnershipState.AwaitingData && now - entry.Value.Since >= _dataTimeout)
				{
					list.Add(new ExpiredGrant(entry.Key, entry.Value.GrantedRevision));
				}
			}
			list.Sort((ExpiredGrant x, ExpiredGrant y) => StringComparer.Ordinal.Compare(x.ContainerId, y.ContainerId));
			foreach (ExpiredGrant item in list)
			{
				_entries.Remove(item.ContainerId);
			}
			return list;
		}

		public IReadOnlyList<string> TakeUnanswered(double now)
		{
			List<string> list = null;
			foreach (KeyValuePair<string, Entry> entry in _entries)
			{
				if ((entry.Value.State == OwnershipState.Requested && now - entry.Value.Since >= _requestTimeout) || entry.Value.Unanswered)
				{
					(list ?? (list = new List<string>())).Add(entry.Key);
				}
			}
			if (list == null)
			{
				return Array.Empty<string>();
			}
			list.RemoveAll((string id) => !TakeReport(id, now));
			list.Sort(StringComparer.Ordinal);
			return list;
		}

		private bool TakeReport(string containerId, double now)
		{
			if (StateOf(containerId, now) != OwnershipState.Unavailable)
			{
				return false;
			}
			Entry entry = _entries[containerId];
			_entries[containerId] = new Entry(entry.State, entry.Since, entry.GrantedRevision);
			return entry.Unanswered;
		}
	}
	public sealed record ExpiredGrant(string ContainerId, uint GrantedRevision);
	public static class Protocol
	{
		public const int Version = 6;

		public static bool IsCompatible(int remoteVersion)
		{
			return remoteVersion == 6;
		}
	}
}
namespace ChestNetwork.Core.Keeping
{
	public readonly struct ObjectId : IEquatable<ObjectId>, IComparable<ObjectId>
	{
		public long UserId { get; }

		public uint Id { get; }

		public ObjectId(long userId, uint id)
		{
			UserId = userId;
			Id = id;
		}

		public static bool operator ==(ObjectId left, ObjectId right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ObjectId left, ObjectId right)
		{
			return !left.Equals(right);
		}

		public bool Equals(ObjectId other)
		{
			if (UserId == other.UserId)
			{
				return Id == other.Id;
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is ObjectId other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(UserId, Id);
		}

		public int CompareTo(ObjectId other)
		{
			int num = UserId.CompareTo(other.UserId);
			if (num == 0)
			{
				return Id.CompareTo(other.Id);
			}
			return num;
		}

		public override string ToString()
		{
			return $"{UserId}:{Id}";
		}
	}
	public enum OwnerState
	{
		Server,
		ClientInArea,
		ClientOutOfArea,
		Absent
	}
	public enum KeepAction
	{
		Vanilla,
		Keep,
		ReturnToServer
	}
	public static class ChestKeeping
	{
		public static bool ShouldPin(bool enabled, bool eligible, bool nearPlayer)
		{
			return enabled && eligible && nearPlayer;
		}

		public static bool InLoadedArea(int zoneDx, int zoneDz, int near, bool classic)
		{
			long num = Math.Abs((long)zoneDx);
			long num2 = Math.Abs((long)zoneDz);
			if (num > near || num2 > near)
			{
				return false;
			}
			double num3 = (double)near + 0.5;
			if (!classic)
			{
				return (double)(num * num + num2 * num2) < num3 * num3;
			}
			return true;
		}

		public static KeepAction Decide(bool pinned, OwnerState owner)
		{
			if (!pinned)
			{
				return KeepAc

plugins/Roims.ConfigurationParasite.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GUIFramework;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Roims.ConfigurationParasite.Texts;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using Valheim.SettingsGui;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Roims.ConfigurationParasite")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+62fdcf3d2084b41ec9a10e4e7b2c8ce48e5480d7")]
[assembly: AssemblyProduct("Roims.ConfigurationParasite")]
[assembly: AssemblyTitle("Roims.ConfigurationParasite")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Roims.ConfigurationParasite
{
	internal sealed class ConfigurationManagerAttributes
	{
		public bool? Browsable;

		public string? Category;

		public int? Order;

		public string? DispName;

		public string? Description;
	}
	internal static class Consent
	{
		private const float SettleDelay = 1.5f;

		private static float s_menuSince = -1f;

		private static bool s_failed;

		private static bool s_done;

		public static void Tick()
		{
			if (s_failed || s_done)
			{
				return;
			}
			try
			{
				FejdStartup instance = FejdStartup.instance;
				if (!((Object)(object)instance != (Object)null) || !((Object)(object)instance.m_mainMenu != (Object)null) || !instance.m_mainMenu.activeInHierarchy || !UnifiedPopup.IsAvailable() || UnifiedPopup.IsVisible() || Localization.instance == null)
				{
					s_menuSince = -1f;
					return;
				}
				if (s_menuSince < 0f)
				{
					s_menuSince = Time.unscaledTime;
				}
				if (!(Time.unscaledTime - s_menuSince < 1.5f))
				{
					ConsentRequest consentRequest = Parasite.Mods.SelectMany((ParasiteMod mod) => mod.ConsentRequests).FirstOrDefault((ConsentRequest pending) => !pending.Asked.Value && !pending.Shown);
					if (consentRequest != null)
					{
						Show(consentRequest);
					}
					else
					{
						s_done = true;
					}
				}
			}
			catch (Exception arg)
			{
				s_failed = true;
				Parasite.Log.LogWarning((object)$"Consent question not shown: {arg}");
			}
		}

		private static void Show(ConsentRequest request)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_004e: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			request.Shown = true;
			UnifiedPopup.Push((PopupBase)new YesNoPopup(request.TitleToken, request.TextToken, (PopupButtonCallback)delegate
			{
				Answer(request, accepted: true);
			}, (PopupButtonCallback)delegate
			{
				Answer(request, accepted: false);
			}, true, false));
		}

		private static void Answer(ConsentRequest request, bool accepted)
		{
			UnifiedPopup.Pop();
			request.Setting.Value = accepted;
			request.Asked.Value = true;
			Parasite.Log.LogInfo((object)string.Format("Consent for {0}: {1}.", ((ConfigEntryBase)request.Setting).Definition, accepted ? "accepted" : "refused"));
		}
	}
	public static class Parasite
	{
		public const string HarmonyId = "roims.configurationparasite";

		private static readonly List<ParasiteMod> s_mods = new List<ParasiteMod>();

		private static Harmony? s_harmony;

		internal static ManualLogSource Log { get; } = Logger.CreateLogSource("ConfigurationParasite");

		internal static IReadOnlyList<ParasiteMod> Mods => s_mods;

		internal static bool IsClient
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return !ZNet.instance.IsServer();
				}
				return false;
			}
		}

		public static ParasiteMod Register(BaseUnityPlugin plugin, string displayName, string textPrefix)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			ParasiteMod parasiteMod = new ParasiteMod(plugin.Config, displayName, textPrefix);
			s_mods.Add(parasiteMod);
			if (s_harmony == null)
			{
				s_harmony = new Harmony("roims.configurationparasite");
				PatchEach(s_harmony);
				Guard("driver", delegate
				{
					//IL_0005: Unknown result type (might be due to invalid IL or missing references)
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0010: Expected O, but got Unknown
					//IL_0010: Unknown result type (might be due to invalid IL or missing references)
					GameObject val = new GameObject("ConfigurationParasite");
					Object.DontDestroyOnLoad((Object)val);
					((Object)val).hideFlags = (HideFlags)61;
					val.AddComponent<ParasiteDriver>();
				});
			}
			Guard("texts", ParasiteTexts.RegisterIfReady);
			return parasiteMod;
		}

		private static void PatchEach(Harmony harmony)
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Parasite).Assembly);
			foreach (Type type in typesFromAssembly)
			{
				if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0)
				{
					Guard("patch " + type.Name, delegate
					{
						harmony.CreateClassProcessor(type).Patch();
					});
				}
			}
		}

		private static void Guard(string what, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				Log.LogWarning((object)$"{what} unavailable, settings stay editable in the .cfg file: {arg}");
			}
		}
	}
	internal sealed class ParasiteDriver : MonoBehaviour
	{
		private float _nextCheck;

		private bool? _wasClient;

		private void Update()
		{
			try
			{
				Tick();
			}
			catch (Exception arg)
			{
				Parasite.Log.LogWarning((object)$"Settings driver stopped (consent questions, F1 visibility): {arg}");
				((Behaviour)this).enabled = false;
			}
		}

		private void Tick()
		{
			Consent.Tick();
			if (Time.unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.unscaledTime + 1f;
			bool isClient = Parasite.IsClient;
			if (_wasClient == isClient)
			{
				return;
			}
			_wasClient = isClient;
			foreach (ParasiteMod mod in Parasite.Mods)
			{
				foreach (Setting setting in mod.Settings)
				{
					setting.Attributes.Browsable = setting.IsVisible(isClient);
				}
			}
		}
	}
	public sealed class ParasiteMod
	{
		private readonly List<Setting> _settings = new List<Setting>();

		private readonly List<string> _sections = new List<string>();

		internal ConfigFile Config { get; }

		internal string DisplayName { get; }

		internal string TextPrefix { get; }

		internal IReadOnlyList<Setting> Settings => _settings;

		internal IReadOnlyList<string> Sections => _sections;

		internal List<ConsentRequest> ConsentRequests { get; } = new List<ConsentRequest>();

		public bool IsApplying { get; internal set; }

		public event Action? Applied;

		internal ParasiteMod(ConfigFile config, string displayName, string textPrefix)
		{
			Config = config;
			DisplayName = displayName;
			TextPrefix = textPrefix.ToLowerInvariant();
		}

		internal void RaiseApplied()
		{
			this.Applied?.Invoke();
		}

		public void AddTexts(IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> byLanguage)
		{
			ParasiteTexts.Add(DisplayName, byLanguage);
		}

		public void AskConsent(ConfigEntry<bool> setting, ConfigEntry<bool> asked, string titleToken, string textToken)
		{
			ConsentRequests.Add(new ConsentRequest(setting, asked, titleToken, textToken));
		}

		public ParasiteSection Section(string name)
		{
			if (!_sections.Contains(name))
			{
				_sections.Add(name);
			}
			return new ParasiteSection(this, name);
		}

		internal string SectionToken(string section)
		{
			return SettingTokens.Section(TextPrefix, section);
		}

		internal string EnumToken(Type enumType, object value)
		{
			return SettingTokens.EnumValue(TextPrefix, enumType.Name, value.ToString());
		}

		internal void Add(Setting setting)
		{
			_settings.Add(setting);
		}
	}
	public sealed class ParasiteSection
	{
		private readonly ParasiteMod _mod;

		private readonly string _name;

		internal ParasiteSection(ParasiteMod mod, string name)
		{
			_mod = mod;
			_name = name;
		}

		public ConfigEntry<bool> Bool(string key, bool defaultValue, string description, SettingScope scope = (SettingScope)0)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Declare(key, defaultValue, description, null, SettingKind.Bool, scope);
		}

		public ConfigEntry<int> Int(string key, int defaultValue, int min, int max, string description, SettingScope scope = (SettingScope)0)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return Declare(key, defaultValue, description, (AcceptableValueBase?)(object)new AcceptableValueRange<int>(min, max), SettingKind.Int, scope);
		}

		public ConfigEntry<T> Enum<T>(string key, T defaultValue, string description) where T : struct, Enum
		{
			return Declare(key, defaultValue, description, null, SettingKind.Enum, (SettingScope)0);
		}

		public ConfigEntry<string> Choices(string key, string defaultValue, IReadOnlyList<string> choices, string description)
		{
			ConfigEntry<string> result = Declare(key, defaultValue, description, null, SettingKind.Choices, (SettingScope)0);
			_mod.Settings[_mod.Settings.Count - 1].Choices = choices;
			return result;
		}

		public ConfigEntry<KeyboardShortcut> Shortcut(string key, KeyboardShortcut defaultValue, string description)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Declare<KeyboardShortcut>(key, defaultValue, description, null, SettingKind.Shortcut, (SettingScope)0);
		}

		public ConfigEntry<T> FileOnly<T>(string key, T defaultValue, string description, AcceptableValueBase? acceptableValues = null)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				Browsable = false
			};
			return _mod.Config.Bind<T>(_name, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1] { configurationManagerAttributes }));
		}

		private ConfigEntry<T> Declare<T>(string key, T defaultValue, string description, AcceptableValueBase? acceptable, SettingKind kind, SettingScope scope)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				Category = _name,
				Order = -_mod.Settings.Count,
				Browsable = true
			};
			ConfigEntry<T> val = _mod.Config.Bind<T>(_name, key, defaultValue, new ConfigDescription(description, acceptable, new object[1] { configurationManagerAttributes }));
			Setting setting = new Setting(_mod, _name, (ConfigEntryBase)(object)val, kind, scope, configurationManagerAttributes);
			_mod.Add(setting);
			ParasiteTexts.Localize(setting);
			return val;
		}
	}
	internal sealed class ConsentRequest
	{
		public ConfigEntry<bool> Setting { get; }

		public ConfigEntry<bool> Asked { get; }

		public string TitleToken { get; }

		public string TextToken { get; }

		public bool Shown { get; set; }

		public ConsentRequest(ConfigEntry<bool> setting, ConfigEntry<bool> asked, string titleToken, string textToken)
		{
			Setting = setting;
			Asked = asked;
			TitleToken = titleToken;
			TextToken = textToken;
		}
	}
	internal enum SettingKind
	{
		Bool,
		Int,
		Enum,
		Shortcut,
		Choices
	}
	internal sealed class Setting
	{
		public ParasiteMod Mod { get; }

		public string Section { get; }

		public ConfigEntryBase Entry { get; }

		public SettingKind Kind { get; }

		public SettingScope Scope { get; }

		public ConfigurationManagerAttributes Attributes { get; }

		public string LabelToken { get; }

		public string DescriptionToken { get; }

		public IReadOnlyList<string> Choices { get; set; } = Array.Empty<string>();

		public Setting(ParasiteMod mod, string section, ConfigEntryBase entry, SettingKind kind, SettingScope scope, ConfigurationManagerAttributes attributes)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			Mod = mod;
			Section = section;
			Entry = entry;
			Kind = kind;
			Scope = scope;
			Attributes = attributes;
			LabelToken = SettingTokens.Label(mod.TextPrefix, section, entry.Definition.Key);
			DescriptionToken = SettingTokens.Description(mod.TextPrefix, section, entry.Definition.Key);
		}

		public string ChoiceToken(string choice)
		{
			return SettingTokens.Choice(Mod.TextPrefix, Section, Entry.Definition.Key, choice);
		}

		public bool IsVisible(bool isClient)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return SettingVisibility.IsVisible(Scope, isClient);
		}
	}
}
namespace Roims.ConfigurationParasite.Ui
{
	internal sealed class ModsTab : MonoBehaviour, ISettingsTab
	{
		private static readonly KeyCode[] s_modifiers;

		private static readonly KeyCode[] s_keys;

		private const float CaptureTimeout = 10f;

		private readonly List<ModPage> _pages = new List<ModPage>();

		private readonly List<Button> _subTabButtons = new List<Button>();

		private Settings _settings;

		private Button _tabButtonTemplate;

		private GameObject[] _keyHints = (GameObject[])(object)new GameObject[0];

		private int _activePage;

		private Button? _back;

		private Button? _ok;

		private ShortcutRow? _capturing;

		private int _captureFrame;

		private float _captureStart;

		private bool _followSelection = true;

		private GameObject? _selected;

		event Action<string, int> ISettingsTab.SharedSettingChanged
		{
			add
			{
			}
			remove
			{
			}
		}

		public void Setup(Settings settings, Button tabButtonTemplate, GameObject[] keyHints)
		{
			_settings = settings;
			_tabButtonTemplate = tabButtonTemplate;
			_keyHints = keyHints;
		}

		public void Initialize()
		{
			try
			{
				Build();
			}
			catch (Exception arg)
			{
				Parasite.Log.LogWarning((object)$"Mods tab content not built: {arg}");
			}
		}

		public void OnTabOpen(Button backButton, Button okButton)
		{
			_back = backButton;
			_ok = okButton;
			try
			{
				WireNavigation();
				SelectFirst();
			}
			catch (Exception arg)
			{
				Parasite.Log.LogWarning((object)$"Mods tab navigation not set up: {arg}");
			}
		}

		public void OnOkAsync(OkActionCompletedHandler okActionCompletedCallback)
		{
			try
			{
				EndCapture(null);
				foreach (ModPage page in _pages)
				{
					page.Apply();
				}
			}
			catch (Exception arg)
			{
				Parasite.Log.LogWarning((object)$"Mods tab: settings not all saved: {arg}");
			}
			finally
			{
				if (okActionCompletedCallback != null)
				{
					okActionCompletedCallback.Invoke();
				}
			}
		}

		public void OnBack()
		{
			EndCapture(null);
		}

		public void Terminate()
		{
		}

		private void OnDisable()
		{
			EndCapture(null);
		}

		public void StartCapture(ShortcutRow row)
		{
			EndCapture(null);
			_capturing = row;
			_captureFrame = Time.frameCount;
			_captureStart = Time.unscaledTime;
			row.ShowPrompt();
			_settings.BlockNavigation(true);
		}

		private void Build()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Expected O, but got Unknown
			NativeTemplates nativeTemplates = NativeTemplates.Find(_settings);
			bool isClient = Parasite.IsClient;
			RectTransform parent = (RectTransform)((Component)this).transform;
			RectTransform val = NativeControls.NewRect("SubTabs", (Transform)(object)parent);
			val.anchorMin = new Vector2(0f, 1f);
			val.anchorMax = new Vector2(1f, 1f);
			val.pivot = new Vector2(0.5f, 1f);
			val.sizeDelta = new Vector2(-16f, 40f);
			val.anchoredPosition = new Vector2(0f, -12f);
			RectTransform parent2 = NativeControls.Stretch(NativeControls.NewRect("Body", (Transform)(object)parent), 0f, 60f);
			if (Parasite.Mods.Count == 1)
			{
				ParasiteMod parasiteMod = Parasite.Mods[0];
				TextMeshProUGUI obj = NativeControls.NewText("Title", (Transform)(object)val, nativeTemplates.HangingLabel, parasiteMod.DisplayName, 1.3f, (FontStyles)1);
				((TMP_Text)obj).alignment = (TextAlignmentOptions)4097;
				NativeControls.Stretch(((TMP_Text)obj).rectTransform, 16f);
				ModPage modPage = ModPage.Build(parasiteMod, parent2, nativeTemplates, isClient, this);
				((Component)modPage.Root).gameObject.SetActive(true);
				_pages.Add(modPage);
				Parasite.Log.LogDebug((object)$"Mods tab built: single mod, no sub-tab, client: {isClient}.");
				return;
			}
			HorizontalLayoutGroup obj2 = ((Component)val).gameObject.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj2).spacing = 8f;
			((LayoutGroup)obj2).padding = new RectOffset(8, 8, 0, 0);
			((LayoutGroup)obj2).childAlignment = (TextAnchor)3;
			((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = false;
			TabHandler val2 = ((Component)val).gameObject.AddComponent<TabHandler>();
			val2.m_gamepadInput = false;
			val2.m_keybaordInput = false;
			val2.m_tabKeyInput = false;
			Rect rect = ((RectTransform)((Component)_tabButtonTemplate).transform).rect;
			Vector2 size = ((Rect)(ref rect)).size;
			foreach (ParasiteMod mod in Parasite.Mods)
			{
				ModPage modPage2 = ModPage.Build(mod, parent2, nativeTemplates, isClient, this);
				_pages.Add(modPage2);
				Button val3 = Object.Instantiate<Button>(_tabButtonTemplate, (Transform)(object)val, false);
				((Object)val3).name = "SubTab_" + mod.DisplayName;
				NativeControls.Neutralize(((Component)val3).gameObject);
				NativeControls.SetTabLabel(val3, _tabButtonTemplate, _keyHints, mod.DisplayName);
				LayoutElement obj3 = ((Component)val3).GetComponent<LayoutElement>() ?? ((Component)val3).gameObject.AddComponent<LayoutElement>();
				obj3.preferredWidth = Mathf.Max(size.x, 120f);
				obj3.preferredHeight = Mathf.Max(size.y, 36f);
				_subTabButtons.Add(val3);
				val2.m_tabs.Add(new Tab
				{
					m_button = val3,
					m_page = modPage2.Root,
					m_default = (_pages.Count == 1)
				});
			}
			val2.ActiveTabChanged += delegate(int index)
			{
				_activePage = index;
				WireNavigation();
				SelectFirst();
			};
			Parasite.Log.LogDebug((object)$"Mods tab built: {_pages.Count} sub-tab(s), client: {isClient}.");
		}

		private void WireNavigation()
		{
			if (_pages.Count != 0)
			{
				List<Selectable> selectables = _pages[_activePage].Selectables;
				Selectable val = selectables.FirstOrDefault();
				Selectable val2 = selectables.LastOrDefault();
				for (int i = 0; i < _subTabButtons.Count; i++)
				{
					NativeControls.SetNavigation((Selectable)(object)_subTabButtons[i], null, (Selectable?)(((object)val) ?? ((object)_back)), (Selectable?)(object)((i > 0) ? _subTabButtons[i - 1] : null), (Selectable?)(object)((i < _subTabButtons.Count - 1) ? _subTabButtons[i + 1] : null));
				}
				for (int j = 0; j < selectables.Count; j++)
				{
					NativeControls.SetNavigation(selectables[j], (Selectable?)((j > 0) ? ((object)selectables[j - 1]) : ((object)SubTabButton())), (Selectable?)((j < selectables.Count - 1) ? ((object)selectables[j + 1]) : ((object)_back)), null, null);
				}
				if ((Object)(object)_back != (Object)null && (Object)(object)_ok != (Object)null)
				{
					Selectable val3 = val2 ?? SubTabButton();
					GuiUtils.SetNavigationUp((Selectable)(object)_back, val3);
					GuiUtils.SetNavigationUp((Selectable)(object)_ok, val3);
				}
			}
		}

		private Selectable? SubTabButton()
		{
			if (_subTabButtons.Count <= _activePage)
			{
				return null;
			}
			return (Selectable?)(object)_subTabButtons[_activePage];
		}

		private void SelectFirst()
		{
			if (ZInput.IsGamepadActive() && (Object)(object)EventSystem.current != (Object)null && _pages.Count > 0)
			{
				Selectable val = _pages[_activePage].Selectables.FirstOrDefault() ?? SubTabButton();
				if ((Object)(object)val != (Object)null)
				{
					EventSystem.current.SetSelectedGameObject(((Component)val).gameObject);
				}
			}
		}

		private void Update()
		{
			if (_capturing != null)
			{
				try
				{
					Capture();
					return;
				}
				catch (Exception ex)
				{
					Parasite.Log.LogWarning((object)("Key capture stopped: " + ex.Message));
					EndCapture(null);
					return;
				}
			}
			if (!_followSelection)
			{
				return;
			}
			try
			{
				FollowSelection();
			}
			catch (Exception ex2)
			{
				Parasite.Log.LogWarning((object)("Mods tab stops following the gamepad selection: " + ex2.Message));
				_followSelection = false;
			}
		}

		private void FollowSelection()
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			if (ZInput.IsExclusiveGamepadActive() && (Object)(object)EventSystem.current != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)(object)_selected)
			{
				_selected = EventSystem.current.currentSelectedGameObject;
				if ((Object)(object)_selected != (Object)null && _pages.Count > 0 && _selected.transform.IsChildOf((Transform)(object)_pages[_activePage].Root))
				{
					_pages[_activePage].EnsureVisible.CenterOnItem((RectTransform)_selected.transform);
				}
			}
		}

		private void Capture()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (Time.frameCount == _captureFrame)
			{
				return;
			}
			if (Time.unscaledTime - _captureStart > 10f || AnyGamepadButtonDown())
			{
				EndCapture(null);
				return;
			}
			if (ZInput.GetKeyDown((KeyCode)27, false))
			{
				EndCapture(null);
				return;
			}
			if (ZInput.GetKeyDown((KeyCode)8, false))
			{
				EndCapture(KeyboardShortcut.Empty);
				return;
			}
			KeyCode[] array = s_keys;
			foreach (KeyCode val in array)
			{
				if (ZInput.GetKeyDown(val, false))
				{
					KeyCode[] array2 = s_modifiers.Where((KeyCode modifier) => ZInput.GetKey(modifier, false)).ToArray();
					EndCapture((KeyboardShortcut?)new KeyboardShortcut(val, array2));
					break;
				}
			}
		}

		private static bool AnyGamepadButtonDown()
		{
			Gamepad current = Gamepad.current;
			if (current != null)
			{
				if (!current.buttonSouth.wasPressedThisFrame && !current.buttonEast.wasPressedThisFrame && !current.buttonNorth.wasPressedThisFrame && !current.buttonWest.wasPressedThisFrame && !current.startButton.wasPressedThisFrame)
				{
					return current.selectButton.wasPressedThisFrame;
				}
				return true;
			}
			return false;
		}

		private void EndCapture(KeyboardShortcut? value)
		{
			if (_capturing != null)
			{
				_capturing.EndCapture(value);
				_capturing = null;
				if (((Behaviour)this).isActiveAndEnabled)
				{
					((MonoBehaviour)this).StartCoroutine(UnblockNextFrame());
				}
				else
				{
					_settings.BlockNavigation(false);
				}
			}
		}

		private IEnumerator UnblockNextFrame()
		{
			yield return null;
			_settings.BlockNavigation(false);
		}

		static ModsTab()
		{
			KeyCode[] array = new KeyCode[6];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			s_modifiers = (KeyCode[])(object)array;
			s_keys = (from key in ZInput.s_keyCodeToKeyMap.Keys.Concat(ZInput.s_keyCodeToMouseButtonMap.Keys)
				where (int)key != 323 && (int)key != 324 && (int)key != 27 && (int)key != 8 && !s_modifiers.Contains(key)
				select key).Distinct().ToArray();
		}
	}
	internal sealed class ModPage
	{
		private readonly List<SettingRow> _rows = new List<SettingRow>();

		private readonly ParasiteMod _mod;

		public RectTransform Root { get; }

		public ScrollRectEnsureVisible EnsureVisible { get; }

		public List<Selectable> Selectables => _rows.SelectMany((SettingRow row) => row.Selectables).ToList();

		private ModPage(ParasiteMod mod, RectTransform root, ScrollRectEnsureVisible ensureVisible)
		{
			_mod = mod;
			Root = root;
			EnsureVisible = ensureVisible;
		}

		public static ModPage Build(ParasiteMod mod, RectTransform parent, NativeTemplates templates, bool isClient, ModsTab tab)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			RectTransform val = NativeControls.Stretch(NativeControls.NewRect("Mod_" + mod.DisplayName, (Transform)(object)parent));
			((Component)val).gameObject.SetActive(false);
			RectTransform val2 = NativeControls.Stretch(NativeControls.NewRect("Viewport", (Transform)(object)val), 0f, 0f, 12f);
			((Component)val2).gameObject.AddComponent<RectMask2D>();
			((Graphic)((Component)val2).gameObject.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
			RectTransform val3 = NativeControls.NewRect("Content", (Transform)(object)val2);
			val3.anchorMin = new Vector2(0f, 1f);
			val3.anchorMax = new Vector2(1f, 1f);
			val3.pivot = new Vector2(0.5f, 1f);
			val3.sizeDelta = Vector2.zero;
			VerticalLayoutGroup obj = ((Component)val3).gameObject.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj).spacing = templates.Spacing;
			((LayoutGroup)obj).padding = new RectOffset(Mathf.RoundToInt(templates.ColumnLeft), 8, 8, 24);
			((LayoutGroup)obj).childAlignment = (TextAnchor)0;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = false;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			((Component)val3).gameObject.AddComponent<ContentSizeFitter>().verticalFit = (FitMode)2;
			ScrollRect obj2 = ((Component)val).gameObject.AddComponent<ScrollRect>();
			obj2.viewport = val2;
			obj2.content = val3;
			obj2.horizontal = false;
			obj2.vertical = true;
			obj2.movementType = (MovementType)2;
			obj2.scrollSensitivity = templates.ScrollSensitivity;
			AddScrollbar(obj2, val, templates);
			ScrollRectEnsureVisible val4 = ((Component)val).gameObject.AddComponent<ScrollRectEnsureVisible>();
			val4.maskTransform = val2;
			ModPage modPage = new ModPage(mod, val, val4);
			Localization instance = Localization.instance;
			foreach (string section in mod.Sections)
			{
				Setting[] array = mod.Settings.Where((Setting setting) => setting.Section == section && setting.IsVisible(isClient)).ToArray();
				if (array.Length == 0)
				{
					continue;
				}
				AddText((Transform)(object)val3, templates, instance.Localize(mod.SectionToken(section)), 1.15f, (FontStyles)1, 32f);
				if (!isClient && array.Any((Setting setting) => (int)setting.Scope == 1))
				{
					AddText((Transform)(object)val3, templates, instance.Localize("$roims_cp_hosted_note"), 0.8f, (FontStyles)2, 26f);
				}
				Setting[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					SettingRow settingRow = SettingRow.Create(array2[num], (Transform)(object)val3, templates, tab);
					if (settingRow != null)
					{
						modPage._rows.Add(settingRow);
					}
				}
			}
			return modPage;
		}

		public void Apply()
		{
			bool saveOnConfigSet = _mod.Config.SaveOnConfigSet;
			_mod.Config.SaveOnConfigSet = false;
			_mod.IsApplying = true;
			bool flag = false;
			try
			{
				foreach (SettingRow row in _rows)
				{
					flag |= row.Apply();
				}
			}
			finally
			{
				_mod.IsApplying = false;
				_mod.Config.SaveOnConfigSet = saveOnConfigSet;
				if (flag)
				{
					try
					{
						_mod.Config.Save();
					}
					finally
					{
						_mod.RaiseApplied();
					}
				}
			}
		}

		private static void AddScrollbar(ScrollRect scroll, RectTransform root, NativeTemplates templates)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)templates.Scrollbar == (Object)null))
			{
				Scrollbar val = Object.Instantiate<Scrollbar>(templates.Scrollbar, (Transform)(object)root, false);
				((Object)val).name = "Scrollbar";
				NativeControls.Neutralize(((Component)val).gameObject);
				RectTransform val2 = (RectTransform)((Component)val).transform;
				val2.anchorMin = new Vector2(1f, 0f);
				val2.anchorMax = new Vector2(1f, 1f);
				val2.pivot = new Vector2(1f, 0.5f);
				Rect rect = ((RectTransform)((Component)templates.Scrollbar).transform).rect;
				val2.sizeDelta = new Vector2(Mathf.Max(((Rect)(ref rect)).width, 10f), 0f);
				val2.anchoredPosition = Vector2.zero;
				val.direction = (Direction)2;
				Navigation navigation = ((Selectable)val).navigation;
				((Navigation)(ref navigation)).mode = (Mode)0;
				((Selectable)val).navigation = navigation;
				scroll.verticalScrollbar = val;
				scroll.verticalScrollbarVisibility = (ScrollbarVisibility)1;
			}
		}

		private static void AddText(Transform content, NativeTemplates templates, string text, float sizeFactor, FontStyles style, float height)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = NativeControls.NewRect("Text", content);
			val.sizeDelta = new Vector2(templates.ColumnWidth, height);
			TextMeshProUGUI obj = NativeControls.NewText("Label", (Transform)(object)val, templates.HangingLabel, text, sizeFactor, style);
			((TMP_Text)obj).alignment = (TextAlignmentOptions)1025;
			NativeControls.Stretch(((TMP_Text)obj).rectTransform, templates.LabelLeft);
		}
	}
	internal abstract class SettingRow
	{
		public Setting Setting { get; }

		public GameObject Root { get; }

		public Selectable Selectable { get; }

		public virtual IEnumerable<Selectable> Selectables => (IEnumerable<Selectable>)(object)new Selectable[1] { Selectable };

		protected SettingRow(Setting setting, GameObject root, Selectable selectable)
		{
			Setting = setting;
			Root = root;
			Selectable = selectable;
		}

		public abstract bool Apply();

		public static SettingRow? Create(Setting setting, Transform content, NativeTemplates templates, ModsTab tab)
		{
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Expected O, but got Unknown
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Expected O, but got Unknown
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			if (setting.Kind == SettingKind.Choices)
			{
				return ChoicesRow.Create(setting, content, templates);
			}
			ControlTemplate controlTemplate = setting.Kind switch
			{
				SettingKind.Bool => templates.Toggle, 
				SettingKind.Int => templates.Slider, 
				SettingKind.Enum => templates.Dropdown, 
				SettingKind.Shortcut => templates.Button, 
				_ => null, 
			};
			if (controlTemplate == null)
			{
				Parasite.Log.LogWarning((object)$"No template for {setting.Kind}: {setting.Entry.Definition} not shown.");
				return null;
			}
			TMP_Text label;
			GameObject val = Clone(controlTemplate, content, templates, setting, setting.LabelToken, out label);
			Selectable component = val.GetComponent<Selectable>();
			TMP_Text val2 = null;
			foreach (TMP_Text item in (from text in val.GetComponentsInChildren<TMP_Text>(true)
				where (Object)(object)text != (Object)(object)label
				select text).ToList())
			{
				bool flag = component is TMP_Dropdown;
				bool num;
				if (setting.Kind != SettingKind.Int)
				{
					if (setting.Kind != SettingKind.Shortcut)
					{
						goto IL_013d;
					}
					num = (Object)(object)val2 == (Object)null;
				}
				else
				{
					num = ((Object)item).name == "Value";
				}
				if (num)
				{
					val2 = item;
					continue;
				}
				goto IL_013d;
				IL_013d:
				if (!flag && (Object)(object)item.transform.parent == (Object)(object)val.transform)
				{
					Object.DestroyImmediate((Object)(object)((Component)item).gameObject);
				}
			}
			return setting.Kind switch
			{
				SettingKind.Bool => new BoolRow(setting, val, (Toggle)component), 
				SettingKind.Int => new IntRow(setting, val, (Slider)component, val2), 
				SettingKind.Enum => new EnumRow(setting, val, (TMP_Dropdown)component, templates.ColumnWidth), 
				_ => new ShortcutRow(setting, val, (Button)component, val2, tab), 
			};
		}

		internal static GameObject Clone(ControlTemplate template, Transform content, NativeTemplates templates, Setting setting, string labelToken, out TMP_Text? label)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(template.Control, content, false);
			((Object)val).name = setting.Entry.Definition.Key;
			val.SetActive(true);
			NativeControls.Neutralize(val);
			RectTransform val2 = (RectTransform)val.transform;
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0f, 1f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0f, 0.5f);
			val2.sizeDelta = template.Size;
			label = NativeTemplates.HangingLabels(val).FirstOrDefault();
			foreach (TMP_Text item in NativeTemplates.HangingLabels(val).Skip(1).ToList())
			{
				Object.DestroyImmediate((Object)(object)((Component)item).gameObject);
			}
			if ((Object)(object)label == (Object)null && (Object)(object)templates.HangingLabel != (Object)null)
			{
				label = Object.Instantiate<TMP_Text>(templates.HangingLabel, val.transform, false);
				((Object)label).name = "Label";
			}
			if ((Object)(object)label != (Object)null)
			{
				label.text = Localization.instance.Localize(labelToken);
			}
			SettingsTooltip[] componentsInChildren = val.GetComponentsInChildren<SettingsTooltip>(true);
			foreach (SettingsTooltip obj in componentsInChildren)
			{
				obj.SetTexts(setting.LabelToken, setting.DescriptionToken);
				obj.m_textIdSwitch = string.Empty;
				obj.m_textIdPlayStation = string.Empty;
				obj.m_textIdXbox = string.Empty;
			}
			return val;
		}
	}
	internal sealed class ChoicesRow : SettingRow
	{
		private readonly List<KeyValuePair<string, Toggle>> _toggles;

		public override IEnumerable<Selectable> Selectables => _toggles.Select<KeyValuePair<string, Toggle>, Selectable>((KeyValuePair<string, Toggle> toggle) => (Selectable)(object)toggle.Value);

		private ChoicesRow(Setting setting, GameObject root, List<KeyValuePair<string, Toggle>> toggles)
			: base(setting, root, (Selectable)(object)toggles[0].Value)
		{
			_toggles = toggles;
		}

		public static ChoicesRow? Create(Setting setting, Transform content, NativeTemplates templates)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if (templates.Toggle == null || setting.Choices.Count == 0)
			{
				Parasite.Log.LogWarning((object)$"No toggle template or no choice: {setting.Entry.Definition} not shown.");
				return null;
			}
			RectTransform val = NativeControls.NewRect(setting.Entry.Definition.Key, content);
			val.sizeDelta = templates.Toggle.Size;
			if ((Object)(object)templates.HangingLabel != (Object)null)
			{
				Object.Instantiate<TMP_Text>(templates.HangingLabel, (Transform)(object)val, false).text = Localization.instance.Localize(setting.LabelToken);
			}
			string text = (string)setting.Entry.BoxedValue;
			List<KeyValuePair<string, Toggle>> list = new List<KeyValuePair<string, Toggle>>();
			foreach (string choice in setting.Choices)
			{
				TMP_Text label;
				Toggle component = SettingRow.Clone(templates.Toggle, content, templates, setting, setting.ChoiceToken(choice), out label).GetComponent<Toggle>();
				component.SetIsOnWithoutNotify(ListValue.Contains(text, choice));
				list.Add(new KeyValuePair<string, Toggle>(choice, component));
			}
			return new ChoicesRow(setting, ((Component)val).gameObject, list);
		}

		public override bool Apply()
		{
			string text = ListValue.Edit((string)base.Setting.Entry.BoxedValue, base.Setting.Choices, from toggle in _toggles
				where toggle.Value.isOn
				select toggle.Key);
			if (text == null)
			{
				return false;
			}
			base.Setting.Entry.BoxedValue = text;
			return true;
		}
	}
	internal sealed class BoolRow : SettingRow
	{
		private readonly Toggle _toggle;

		private readonly PendingEdit<bool> _edit;

		public BoolRow(Setting setting, GameObject root, Toggle toggle)
			: base(setting, root, (Selectable)(object)toggle)
		{
			_toggle = toggle;
			_edit = new PendingEdit<bool>((bool)setting.Entry.BoxedValue);
			_toggle.SetIsOnWithoutNotify(_edit.Initial);
		}

		public override bool Apply()
		{
			_edit.Current = _toggle.isOn;
			if (!_edit.IsChanged)
			{
				return false;
			}
			base.Setting.Entry.BoxedValue = _edit.Current;
			return true;
		}
	}
	internal sealed class IntRow : SettingRow
	{
		private readonly Slider _slider;

		private readonly TMP_Text? _valueText;

		private readonly int[] _steps;

		private readonly PendingEdit<int> _edit;

		public IntRow(Setting setting, GameObject root, Slider slider, TMP_Text? valueText)
			: base(setting, root, (Selectable)(object)slider)
		{
			_slider = slider;
			_valueText = valueText;
			AcceptableValueRange<int> val = (AcceptableValueRange<int>)(object)setting.Entry.Description.AcceptableValues;
			int num = (int)setting.Entry.BoxedValue;
			_steps = SliderScale.Steps(val.MinValue, val.MaxValue, num);
			_edit = new PendingEdit<int>(SliderScale.IndexOf(_steps, num));
			_slider.minValue = 0f;
			_slider.maxValue = _steps.Length - 1;
			_slider.wholeNumbers = true;
			_slider.SetValueWithoutNotify((float)_edit.Initial);
			((UnityEvent<float>)(object)_slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				ShowValue();
			});
			ShowValue();
		}

		public override bool Apply()
		{
			_edit.Current = (int)_slider.value;
			if (!_edit.IsChanged)
			{
				return false;
			}
			base.Setting.Entry.BoxedValue = _steps[_edit.Current];
			return true;
		}

		private void ShowValue()
		{
			if ((Object)(object)_valueText != (Object)null)
			{
				_valueText.text = _steps[(int)_slider.value].ToString();
			}
		}
	}
	internal sealed class EnumRow : SettingRow
	{
		private readonly TMP_Dropdown _dropdown;

		private readonly object[] _values;

		private readonly PendingEdit<int> _edit;

		public EnumRow(Setting setting, GameObject root, TMP_Dropdown dropdown, float columnWidth)
			: base(setting, root, (Selectable)(object)dropdown)
		{
			_dropdown = dropdown;
			Type type = setting.Entry.SettingType;
			_values = Enum.GetValues(type).Cast<object>().ToArray();
			Localization localization = Localization.instance;
			_dropdown.ClearOptions();
			_dropdown.AddOptions(_values.Select((object value) => localization.Localize(setting.Mod.EnumToken(type, value))).ToList());
			_edit = new PendingEdit<int>(EnumChoice.IndexOf<object>((IReadOnlyList<object>)_values, setting.Entry.BoxedValue));
			_dropdown.SetValueWithoutNotify(_edit.Initial);
			_dropdown.RefreshShownValue();
			FitWidth(_dropdown, columnWidth);
		}

		private static void FitWidth(TMP_Dropdown dropdown, float columnWidth)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			TMP_Text caption = dropdown.captionText;
			RectTransform val = (RectTransform)((Component)dropdown).transform;
			if (!((Object)(object)caption == (Object)null))
			{
				Rect rect = val.rect;
				float width = ((Rect)(ref rect)).width;
				rect = caption.rectTransform.rect;
				float num = width - ((Rect)(ref rect)).width;
				float num2 = dropdown.options.Max((OptionData option) => caption.GetPreferredValues(option.text).x);
				val.sizeDelta = new Vector2(Mathf.Min(columnWidth, Mathf.Max(val.sizeDelta.x, num2 + Mathf.Max(num, 24f) + 8f)), val.sizeDelta.y);
			}
		}

		public override bool Apply()
		{
			_edit.Current = _dropdown.value;
			if (!_edit.IsChanged)
			{
				return false;
			}
			base.Setting.Entry.BoxedValue = _values[_edit.Current];
			return true;
		}
	}
	internal sealed class ShortcutRow : SettingRow
	{
		private readonly TMP_Text? _valueText;

		private readonly PendingEdit<KeyboardShortcut> _edit;

		public ShortcutRow(Setting setting, GameObject root, Button button, TMP_Text? caption, ModsTab tab)
			: base(setting, root, (Selectable)(object)button)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			ShortcutRow row = this;
			_edit = new PendingEdit<KeyboardShortcut>((KeyboardShortcut)setting.Entry.BoxedValue);
			_valueText = caption;
			((UnityEvent)button.onClick).AddListener((UnityAction)delegate
			{
				tab.StartCapture(row);
			});
			Show();
		}

		public override bool Apply()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (!_edit.IsChanged)
			{
				return false;
			}
			base.Setting.Entry.BoxedValue = _edit.Current;
			return true;
		}

		public void ShowPrompt()
		{
			if ((Object)(object)_valueText != (Object)null)
			{
				_valueText.text = Localization.instance.Localize("$roims_cp_press_key");
			}
		}

		public void EndCapture(KeyboardShortcut? value)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (value.HasValue)
			{
				_edit.Current = value.Value;
			}
			Show();
		}

		private void Show()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_valueText != (Object)null)
			{
				_valueText.text = KeyNames.Of(_edit.Current);
			}
		}
	}
	internal static class KeyNames
	{
		public unsafe static string Of(KeyboardShortcut shortcut)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected I4, but got Unknown
			object obj = KeyboardShortcut.Empty;
			if (!((object)(*(KeyboardShortcut*)(&shortcut))/*cast due to .constrained prefix*/).Equals(obj))
			{
				return string.Join(" + ", ((KeyboardShortcut)(ref shortcut)).Modifiers.Concat((IEnumerable<KeyCode>)(object)new KeyCode[1] { (KeyCode)(int)((KeyboardShortcut)(ref shortcut)).MainKey }).Select(Of));
			}
			return Localization.instance.Localize("$roims_cp_key_none");
		}

		private unsafe static string Of(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				InputControl val = InputSystem.FindControl(ZInput.KeyCodeToPath(key, false));
				if (val == null)
				{
					return ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
				}
				string value;
				return ZInput.s_keyLocalizationMap.TryGetValue(val.name, out value) ? Localization.instance.Localize(value) : val.displayName;
			}
			catch (Exception)
			{
				return ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
			}
		}
	}
	internal sealed class ControlTemplate
	{
		public GameObject Control { get; }

		public Vector2 Size { get; }

		public ControlTemplate(Selectable control)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			Control = ((Component)control).gameObject;
			Rect rect = ((RectTransform)((Component)control).transform).rect;
			Size = ((Rect)(ref rect)).size;
		}
	}
	internal sealed class NativeTemplates
	{
		public ControlTemplate? Toggle { get; private set; }

		public ControlTemplate? Slider { get; private set; }

		public ControlTemplate? Dropdown { get; private set; }

		public ControlTemplate? Button { get; private set; }

		public TMP_Text? HangingLabel { get; private set; }

		public float LabelLeft { get; private set; } = -316f;

		public float ColumnLeft { get; private set; } = 350f;

		public float ColumnWidth { get; private set; } = 540f;

		public float Spacing { get; private set; } = 8f;

		public Scrollbar? Scrollbar { get; private set; }

		public float ScrollSensitivity { get; private set; } = 30f;

		public static NativeTemplates Find(Settings settings)
		{
			NativeTemplates nativeTemplates = new NativeTemplates();
			GameplaySettings componentInChildren = ((Component)settings).GetComponentInChildren<GameplaySettings>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				nativeTemplates.Toggle = Template((Selectable?)(object)componentInChildren.m_toggleRun);
				nativeTemplates.Slider = Template((Selectable?)(object)componentInChildren.m_autoBackups);
				nativeTemplates.Button = Template((Selectable?)(object)componentInChildren.m_resetTutorial);
				nativeTemplates.ReadColumn(componentInChildren);
			}
			else
			{
				Parasite.Log.LogWarning((object)"GameplaySettings not found in the settings screen: toggles, sliders and keys unavailable.");
			}
			nativeTemplates.Dropdown = Template((Selectable?)(object)((Component)settings).GetComponentsInChildren<GuiDropdown>(true).FirstOrDefault());
			nativeTemplates.Scrollbar = (from scroll in ((Component)settings).GetComponentsInChildren<ScrollRect>(true)
				select scroll.verticalScrollbar).FirstOrDefault((Func<Scrollbar, bool>)((Scrollbar bar) => (Object)(object)bar != (Object)null));
			ScrollRect val = (((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.m_toggleRun != (Object)null) ? ((Component)componentInChildren.m_toggleRun).GetComponentInParent<ScrollRect>(true) : null) ?? ((IEnumerable<ScrollRect>)((Component)settings).GetComponentsInChildren<ScrollRect>(true)).FirstOrDefault((Func<ScrollRect, bool>)((ScrollRect scroll) => scroll.vertical));
			if ((Object)(object)val != (Object)null && val.scrollSensitivity > 0f)
			{
				nativeTemplates.ScrollSensitivity = val.scrollSensitivity;
			}
			if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.m_toggleRun != (Object)null)
			{
				nativeTemplates.HangingLabel = HangingLabels(((Component)componentInChildren.m_toggleRun).gameObject).FirstOrDefault();
				if ((Object)(object)nativeTemplates.HangingLabel != (Object)null)
				{
					nativeTemplates.LabelLeft = LeftInControl(((Component)componentInChildren.m_toggleRun).transform, nativeTemplates.HangingLabel.rectTransform);
				}
			}
			Parasite.Log.LogDebug((object)("Templates: toggle " + Describe(nativeTemplates.Toggle) + ", slider " + Describe(nativeTemplates.Slider) + ", dropdown " + Describe(nativeTemplates.Dropdown) + ", " + string.Format("button {0}, scrollbar {1}, scroll sensitivity {2:0.##}{3}; hanging label {4} at {5:0}; ", Describe(nativeTemplates.Button), ((Object)(object)nativeTemplates.Scrollbar != (Object)null) ? ((Object)nativeTemplates.Scrollbar).name : "missing", nativeTemplates.ScrollSensitivity, ((Object)(object)val != (Object)null && val.scrollSensitivity > 0f) ? (" (" + ((Object)val).name + ")") : " (default)", ((Object)(object)nativeTemplates.HangingLabel != (Object)null) ? "found" : "missing", nativeTemplates.LabelLeft) + $"column left {nativeTemplates.ColumnLeft:0}, width {nativeTemplates.ColumnWidth:0}, spacing {nativeTemplates.Spacing:0}."));
			return nativeTemplates;
		}

		internal static IEnumerable<TMP_Text> HangingLabels(GameObject control)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			RectTransform rect = (RectTransform)control.transform;
			return control.GetComponentsInChildren<TMP_Text>(true).Where(delegate(TMP_Text text)
			{
				//IL_0012: 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)
				//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_0024: 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_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				RectTransform obj = rect;
				RectTransform rectTransform = text.rectTransform;
				Rect rect2 = text.rectTransform.rect;
				float x = ((Transform)obj).InverseTransformPoint(((Transform)rectTransform).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect2)).center))).x;
				rect2 = rect.rect;
				return x < ((Rect)(ref rect2)).xMin;
			});
		}

		private static float LeftInControl(Transform control, RectTransform label)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = label.rect;
			float x = control.InverseTransformPoint(((Transform)label).TransformPoint(new Vector3(((Rect)(ref rect)).xMin, 0f))).x;
			rect = ((RectTransform)control).rect;
			return x - ((Rect)(ref rect)).xMin;
		}

		private void ReadColumn(GameplaySettings gameplay)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)((Component)gameplay).transform;
			if ((Object)(object)gameplay.m_toggleRun == (Object)null)
			{
				return;
			}
			Transform parent = ((Component)gameplay.m_toggleRun).transform.parent;
			RectTransform val2 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			if (val2 != null)
			{
				Rect rect = val2.rect;
				float x = ((Transform)val).InverseTransformPoint(((Transform)val2).TransformPoint(new Vector3(((Rect)(ref rect)).xMin, 0f))).x;
				rect = val.rect;
				ColumnLeft = x - ((Rect)(ref rect)).xMin;
				rect = val2.rect;
				ColumnWidth = ((Rect)(ref rect)).width;
				VerticalLayoutGroup component = ((Component)val2).GetComponent<VerticalLayoutGroup>();
				if ((Object)(object)component != (Object)null)
				{
					Spacing = ((HorizontalOrVerticalLayoutGroup)component).spacing;
				}
			}
		}

		private static ControlTemplate? Template(Selectable? control)
		{
			if (!((Object)(object)control != (Object)null))
			{
				return null;
			}
			return new ControlTemplate(control);
		}

		private static string Describe(ControlTemplate? template)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (template != null)
			{
				return $"'{((Object)template.Control).name}' {template.Size.x:0}x{template.Size.y:0}";
			}
			return "missing";
		}
	}
	internal static class NativeControls
	{
		public static void Neutralize(GameObject clone)
		{
			Component[] componentsInChildren = clone.GetComponentsInChildren<Component>(true);
			foreach (Component val in componentsInChildren)
			{
				if (val is UIGamePad)
				{
					Object.DestroyImmediate((Object)(object)val);
					continue;
				}
				Type type = ((object)val).GetType();
				while (type != null && type != typeof(Component))
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (FieldInfo fieldInfo in fields)
					{
						if (!typeof(UnityEventBase).IsAssignableFrom(fieldInfo.FieldType))
						{
							continue;
						}
						object? value = fieldInfo.GetValue(val);
						UnityEventBase val2 = (UnityEventBase)((value is UnityEventBase) ? value : null);
						if (val2 != null)
						{
							for (int k = 0; k < val2.GetPersistentEventCount(); k++)
							{
								val2.SetPersistentListenerState(k, (UnityEventCallState)0);
							}
							val2.RemoveAllListeners();
						}
					}
					type = type.BaseType;
				}
			}
		}

		public static void SetTexts(GameObject root, string text)
		{
			TMP_Text[] componentsInChildren = root.GetComponentsInChildren<TMP_Text>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].text = text;
			}
		}

		public static RectTransform NewRect(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val).SetParent(parent, false);
			return val;
		}

		public static RectTransform Stretch(RectTransform rect, float left = 0f, float top = 0f, float right = 0f, float bottom = 0f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = Vector2.zero;
			rect.anchorMax = Vector2.one;
			rect.pivot = new Vector2(0.5f, 0.5f);
			rect.offsetMin = new Vector2(left, bottom);
			rect.offsetMax = new Vector2(0f - right, 0f - top);
			return rect;
		}

		public static void CopyRect(RectTransform from, RectTransform to)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			to.anchorMin = from.anchorMin;
			to.anchorMax = from.anchorMax;
			to.pivot = from.pivot;
			to.anchoredPosition = from.anchoredPosition;
			to.sizeDelta = from.sizeDelta;
			((Transform)to).localScale = ((Transform)from).localScale;
			((Transform)to).localRotation = ((Transform)from).localRotation;
		}

		public static TextMeshProUGUI NewText(string name, Transform parent, TMP_Text? style, string text, float sizeFactor, FontStyles fontStyle)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI val = ((Component)NewRect(name, parent)).gameObject.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)style != (Object)null)
			{
				((TMP_Text)val).font = style.font;
				((TMP_Text)val).fontSharedMaterial = style.fontSharedMaterial;
				((Graphic)val).color = ((Graphic)style).color;
				((TMP_Text)val).fontSize = style.fontSize * sizeFactor;
			}
			((TMP_Text)val).fontStyle = fontStyle;
			((TMP_Text)val).textWrappingMode = (TextWrappingModes)1;
			((TMP_Text)val).text = text;
			((Graphic)val).raycastTarget = false;
			return val;
		}

		public static void SetNavigation(Selectable selectable, Selectable? up, Selectable? down, Selectable? left, Selectable? right)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			Navigation navigation = selectable.navigation;
			((Navigation)(ref navigation)).mode = (Mode)4;
			((Navigation)(ref navigation)).selectOnUp = up;
			((Navigation)(ref navigation)).selectOnDown = down;
			((Navigation)(ref navigation)).selectOnLeft = left;
			((Navigation)(ref navigation)).selectOnRight = right;
			selectable.navigation = navigation;
		}

		public static void SetTabLabel(Button clone, Button original, IEnumerable<GameObject> keyHints, string text)
		{
			foreach (GameObject keyHint in keyHints)
			{
				if ((Object)(object)keyHint != (Object)null && keyHint.transform.IsChildOf(((Component)original).transform) && (Object)(object)keyHint.transform != (Object)(object)((Component)original).transform)
				{
					Transform val = ((Component)clone).transform.Find(RelativePath(((Component)original).transform, keyHint.transform));
					if ((Object)(object)val != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
					}
				}
			}
			SetTexts(((Component)clone).gameObject, text);
		}

		private static string RelativePath(Transform root, Transform target)
		{
			List<string> list = new List<string>();
			Transform val = target;
			while ((Object)(object)val != (Object)(object)root && (Object)(object)val != (Object)null)
			{
				list.Insert(0, ((Object)val).name);
				val = val.parent;
			}
			return string.Join("/", list);
		}
	}
	[HarmonyPatch(typeof(Settings), "Awake")]
	internal static class SettingsInjection
	{
		public const string PageName = "RoimsConfigurationParasite_Mods";

		private static void Prefix(Settings __instance)
		{
			if (Parasite.Mods.Count == 0)
			{
				return;
			}
			List<GameObject> list = new List<GameObject>();
			try
			{
				Inject(__instance, list);
			}
			catch (Exception arg)
			{
				foreach (GameObject item in list)
				{
					Object.DestroyImmediate((Object)(object)item);
				}
				Parasite.Log.LogWarning((object)$"Mods tab not added, settings screen left as is: {arg}");
			}
		}

		private static void Inject(Settings settings, List<GameObject> created)
		{
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Expected O, but got Unknown
			//IL_020e: Expected O, but got Unknown
			TabHandler val = (((Object)(object)settings.m_tabHandler != (Object)null) ? settings.m_tabHandler : ((Component)settings).GetComponentInChildren<TabHandler>());
			if ((Object)(object)val == (Object)null || val.m_tabs.Count == 0)
			{
				throw new InvalidOperationException("no TabHandler with tabs in the settings screen");
			}
			if (val.m_tabs.Any((Tab tab) => (Object)(object)tab.m_page != (Object)null && ((Object)tab.m_page).name == "RoimsConfigurationParasite_Mods"))
			{
				Parasite.Log.LogInfo((object)"Mods tab already present (another copy of the library): not added twice.");
				return;
			}
			Tab val2 = val.m_tabs.Last((Tab tab) => (Object)(object)tab.m_button != (Object)null && (Object)(object)tab.m_page != (Object)null);
			RectTransform val3 = NativeControls.NewRect("RoimsConfigurationParasite_Mods", ((Transform)val2.m_page).parent);
			created.Add(((Component)val3).gameObject);
			NativeControls.CopyRect(val2.m_page, val3);
			((Transform)val3).SetSiblingIndex(((Transform)val2.m_page).GetSiblingIndex() + 1);
			((Component)val3).gameObject.SetActive(false);
			GameObject[] array = (GameObject[])(((object)settings.m_tabKeyHints) ?? ((object)new GameObject[0]));
			((Component)val3).gameObject.AddComponent<ModsTab>().Setup(settings, val2.m_button, array);
			Button val4 = Object.Instantiate<Button>(val2.m_button, ((Component)val2.m_button).transform.parent, false);
			created.Add(((Component)val4).gameObject);
			((Object)val4).name = "RoimsConfigurationParasite_ModsButton";
			NativeControls.Neutralize(((Component)val4).gameObject);
			NativeControls.SetTabLabel(val4, val2.m_button, array, Localization.instance.Localize("$roims_cp_tab_mods"));
			Place(val4, val, val2.m_button);
			GameObject[] array2 = array;
			foreach (GameObject val5 in array2)
			{
				if ((Object)(object)val5 != (Object)null && val5.transform.IsChildOf(((Component)val2.m_button).transform))
				{
					val5.transform.SetParent(((Component)val4).transform, false);
				}
			}
			val.m_tabs.Add(new Tab
			{
				m_button = val4,
				m_page = val3,
				m_default = false,
				m_onClick = new UnityEvent()
			});
			Parasite.Log.LogDebug((object)$"Mods tab added ({val.m_tabs.Count} tabs).");
		}

		private static void Place(Button button, TabHandler handler, Button last)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)((Component)button).transform;
			RectTransform val2 = (RectTransform)((Component)last).transform;
			((Transform)val).SetSiblingIndex(((Transform)val2).GetSiblingIndex() + 1);
			LayoutGroup component = ((Component)((Transform)val2).parent).GetComponent<LayoutGroup>();
			if ((Object)(object)component != (Object)null)
			{
				Parasite.Log.LogDebug((object)("Tab bar placed by its " + ((object)component).GetType().Name + "."));
				return;
			}
			Button[] array = (from tab in handler.m_tabs
				where (Object)(object)tab.m_button != (Object)null && (Object)(object)tab.m_button != (Object)(object)button
				select tab.m_button).ToArray();
			? val3;
			if (array.Length < 2)
			{
				Rect rect = val2.rect;
				val3 = new Vector2(((Rect)(ref rect)).width, 0f);
			}
			else
			{
				val3 = val2.anchoredPosition - ((RectTransform)((Component)array[^2]).transform).anchoredPosition;
			}
			Vector2 val4 = (Vector2)val3;
			val.anchoredPosition = val2.anchoredPosition + val4;
			Parasite.Log.LogDebug((object)$"Tab bar without layout group: button placed by hand, step {val4}.");
		}
	}
}
namespace Roims.ConfigurationParasite.Texts
{
	internal static class ParasiteTexts
	{
		[HarmonyPatch(typeof(Localization), "SetupLanguage")]
		private static class SetupLanguagePatch
		{
			private static void Postfix(Localization __instance, string language)
			{
				try
				{
					Register(__instance, language);
				}
				catch (Exception arg)
				{
					Parasite.Log.LogWarning((object)$"Texts not registered for {language}: {arg}");
				}
			}
		}

		private static readonly TextCatalog s_catalog = CreateCatalog();

		public static void Add(string owner, IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> byLanguage)
		{
			foreach (string item in TextCatalog.Problems(byLanguage))
			{
				Parasite.Log.LogWarning((object)("Texts of " + owner + ": " + item));
			}
			s_catalog.Add(byLanguage);
			RegisterIfReady();
		}

		public static void RegisterIfReady()
		{
			Localization instance = Localization.m_instance;
			if (instance != null)
			{
				Register(instance, instance.GetSelectedLanguage());
			}
		}

		public static void Localize(Setting setting)
		{
			Localization instance = Localization.m_instance;
			if (instance != null)
			{
				setting.Attributes.DispName = instance.Localize(setting.LabelToken);
				setting.Attributes.Description = instance.Localize(setting.DescriptionToken);
				string text = instance.Localize(setting.Mod.SectionToken(setting.Section));
				setting.Attributes.Category = (text.StartsWith("[", StringComparison.Ordinal) ? setting.Section : text);
			}
		}

		private static TextCatalog CreateCatalog()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			TextCatalog val = new TextCatalog();
			val.Add(LibraryTexts.ByLanguage);
			return val;
		}

		private static void Register(Localization localization, string language)
		{
			foreach (KeyValuePair<string, string> item in s_catalog.Resolve(language))
			{
				localization.AddWord(item.Key, item.Value);
			}
			foreach (ParasiteMod mod in Parasite.Mods)
			{
				foreach (Setting setting in mod.Settings)
				{
					Localize(setting);
				}
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/Roims.ConfigurationParasite.Core.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Roims.ConfigurationParasite.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+62fdcf3d2084b41ec9a10e4e7b2c8ce48e5480d7")]
[assembly: AssemblyProduct("Roims.ConfigurationParasite.Core")]
[assembly: AssemblyTitle("Roims.ConfigurationParasite.Core")]
[assembly: InternalsVisibleTo("Roims.ConfigurationParasite.Tests")]
[assembly: AssemblyVersion("0.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Roims.ConfigurationParasite
{
	public static class LibraryTexts
	{
		public const string TabMods = "$roims_cp_tab_mods";

		public const string HostedNote = "$roims_cp_hosted_note";

		public const string PressKey = "$roims_cp_press_key";

		public const string KeyNone = "$roims_cp_key_none";

		public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> ByLanguage { get; } = new Dictionary<string, IReadOnlyDictionary<string, string>>
		{
			["English"] = Texts("Mods", "Chosen by the host, for every player in the game.", "Press a key (Esc: cancel, Backspace: none)", "None"),
			["French"] = Texts("Mods", "Choisi par l'hôte, pour tous les joueurs de la partie.", "Appuyez sur une touche (Échap : annuler, Retour arrière : aucune)", "Aucune"),
			["German"] = Texts("Mods", "Vom Host festgelegt, für alle Spieler der Partie.", "Taste drücken (Esc: abbrechen, Rücktaste: keine)", "Keine"),
			["Spanish"] = Texts("Mods", "Lo elige el anfitrión, para todos los jugadores de la partida.", "Pulsa una tecla (Esc: cancelar, Retroceso: ninguna)", "Ninguna"),
			["Portuguese_Brazilian"] = Texts("Mods", "Escolhido pelo anfitrião, para todos os jogadores da partida.", "Pressione uma tecla (Esc: cancelar, Backspace: nenhuma)", "Nenhuma"),
			["Polish"] = Texts("Mody", "Wybiera gospodarz, dla wszystkich graczy w rozgrywce.", "Naciśnij klawisz (Esc: anuluj, Backspace: brak)", "Brak"),
			["Russian"] = Texts("Моды", "Выбирает хост, для всех игроков в игре.", "Нажмите клавишу (Esc: отмена, Backspace: нет)", "Нет"),
			["Chinese"] = Texts("模组", "由主机选择,适用于本局所有玩家。", "请按一个键(Esc:取消,退格:无)", "无")
		};

		private static IReadOnlyDictionary<string, string> Texts(string tabMods, string hostedNote, string pressKey, string keyNone)
		{
			return new Dictionary<string, string>
			{
				["$roims_cp_tab_mods"] = tabMods,
				["$roims_cp_hosted_note"] = hostedNote,
				["$roims_cp_press_key"] = pressKey,
				["$roims_cp_key_none"] = keyNone
			};
		}
	}
	public static class ListValue
	{
		public static string[] Split(string? value)
		{
			return (from entry in (value ?? string.Empty).Split(',')
				select entry.Trim() into entry
				where entry.Length > 0
				select entry).ToArray();
		}

		public static string? Edit(string? initial, IReadOnlyList<string> choices, IEnumerable<string> checkedChoices)
		{
			HashSet<string> hashSet = new HashSet<string>(checkedChoices, StringComparer.Ordinal);
			HashSet<string> isChoice = new HashSet<string>(choices, StringComparer.Ordinal);
			string[] array = Split(initial);
			string[] array2 = choices.Where(hashSet.Contains).Concat(array.Where((string entry) => !isChoice.Contains(entry))).Distinct<string>(StringComparer.Ordinal)
				.ToArray();
			if (!new HashSet<string>(array, StringComparer.Ordinal).SetEquals(array2))
			{
				return string.Join(",", array2);
			}
			return null;
		}

		public static bool Contains(string? value, string choice)
		{
			return Split(value).Contains<string>(choice, StringComparer.Ordinal);
		}
	}
	public sealed class PendingEdit<T>
	{
		public T Initial { get; }

		public T Current { get; set; }

		public bool IsChanged => !EqualityComparer<T>.Default.Equals(Current, Initial);

		public PendingEdit(T initial)
		{
			Initial = initial;
			Current = initial;
		}
	}
	public static class EnumChoice
	{
		public static int IndexOf<T>(IReadOnlyList<T> values, T current)
		{
			for (int i = 0; i < values.Count; i++)
			{
				if (EqualityComparer<T>.Default.Equals(values[i], current))
				{
					return i;
				}
			}
			return 0;
		}
	}
	public enum SettingScope
	{
		Player,
		ServerImposed
	}
	public static class SettingVisibility
	{
		public static bool IsVisible(SettingScope scope, bool isClient)
		{
			if (scope != SettingScope.Player)
			{
				return !isClient;
			}
			return true;
		}
	}
	public static class SettingTokens
	{
		public static string Label(string prefix, string section, string key)
		{
			return Token(prefix + "_" + section + "_" + key);
		}

		public static string Description(string prefix, string section, string key)
		{
			return Token(prefix + "_" + section + "_" + key + "_desc");
		}

		public static string Section(string prefix, string section)
		{
			return Token(prefix + "_section_" + section);
		}

		public static string EnumValue(string prefix, string enumTypeName, string value)
		{
			return Token(prefix + "_" + enumTypeName + "_" + value);
		}

		public static string Choice(string prefix, string section, string key, string choice)
		{
			return Token(prefix + "_" + section + "_" + key + "_" + choice);
		}

		private static string Token(string name)
		{
			return "$" + name.ToLowerInvariant();
		}
	}
	public static class SliderScale
	{
		public const int MaxLinearSteps = 100;

		public static int[] Steps(int min, int max, int current)
		{
			if (max < min)
			{
				int num = max;
				max = min;
				min = num;
			}
			SortedSet<int> sortedSet = new SortedSet<int>
			{
				min,
				max,
				Clamp(current, min, max)
			};
			if ((long)max - (long)min <= 100)
			{
				for (long num2 = min; num2 <= max; num2++)
				{
					sortedSet.Add((int)num2);
				}
			}
			else
			{
				for (long num3 = 1L; num3 <= max; num3 *= 10)
				{
					long[] array = new long[3] { 1L, 2L, 5L };
					foreach (long num4 in array)
					{
						long num5 = num3 * num4;
						if (num5 > min && num5 < max)
						{
							sortedSet.Add((int)num5);
						}
					}
				}
			}
			return sortedSet.ToArray();
		}

		public static int IndexOf(int[] steps, int value)
		{
			if (steps.Length == 0)
			{
				return 0;
			}
			int value2 = Clamp(value, steps[0], steps[^1]);
			int num = Array.BinarySearch(steps, value2);
			if (num < 0)
			{
				return Math.Min(steps.Length - 1, ~num);
			}
			return num;
		}

		private static int Clamp(int value, int min, int max)
		{
			return Math.Max(min, Math.Min(max, value));
		}
	}
	public sealed class TextCatalog
	{
		public const string Fallback = "English";

		public static readonly IReadOnlyList<string> Languages = new string[8] { "English", "French", "German", "Spanish", "Portuguese_Brazilian", "Polish", "Russian", "Chinese" };

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

		public void Add(IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> byLanguage)
		{
			foreach (KeyValuePair<string, IReadOnlyDictionary<string, string>> item in byLanguage)
			{
				if (!_byLanguage.TryGetValue(item.Key, out Dictionary<string, string> value))
				{
					value = new Dictionary<string, string>(StringComparer.Ordinal);
					_byLanguage[item.Key] = value;
				}
				foreach (KeyValuePair<string, string> item2 in item.Value)
				{
					value[Normalize(item2.Key)] = item2.Value;
				}
			}
		}

		public IReadOnlyList<KeyValuePair<string, string>> Resolve(string language)
		{
			if (!_byLanguage.TryGetValue("English", out Dictionary<string, string> value))
			{
				return Array.Empty<KeyValuePair<string, string>>();
			}
			_byLanguage.TryGetValue(language, out Dictionary<string, string> translated);
			string value2;
			return (from text in value.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> text) => text.Key, StringComparer.Ordinal)
				select new KeyValuePair<string, string>(text.Key, (translated != null && translated.TryGetValue(text.Key, out value2)) ? value2 : text.Value)).ToList();
		}

		public static IReadOnlyList<string> Problems(IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> byLanguage)
		{
			List<string> list = new List<string>();
			if (!byLanguage.TryGetValue("English", out IReadOnlyDictionary<string, string> value))
			{
				list.Add("English: missing language");
				return list;
			}
			HashSet<string> keys = new HashSet<string>(value.Keys.Select(Normalize), StringComparer.Ordinal);
			foreach (string language in Languages)
			{
				if (!byLanguage.TryGetValue(language, out IReadOnlyDictionary<string, string> value2))
				{
					list.Add(language + ": missing language");
					continue;
				}
				HashSet<string> present = new HashSet<string>(from text in value2
					where text.Value.Trim().Length > 0
					select Normalize(text.Key), StringComparer.Ordinal);
				list.AddRange(from key in keys.Where((string key) => !present.Contains(key)).OrderBy<string, string>((string key) => key, StringComparer.Ordinal)
					select language + ": missing " + key);
				list.AddRange(from key in (from key in value2.Keys.Select(Normalize)
						where !keys.Contains(key)
						select key).OrderBy<string, string>((string key) => key, StringComparer.Ordinal)
					select language + ": orphan " + key);
			}
			list.AddRange(from text in byLanguage.Keys.Where((string value3) => !Languages.Contains(value3)).OrderBy<string, string>((string result) => result, StringComparer.Ordinal)
				select text + ": unknown language");
			return list;
		}

		private static string Normalize(string key)
		{
			if (!key.StartsWith("$", StringComparison.Ordinal))
			{
				return key;
			}
			return key.Substring(1);
		}
	}
}

plugins/ChestNetwork.Telemetry.dll

Decompiled a week ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChestNetwork.Telemetry")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+62fdcf3d2084b41ec9a10e4e7b2c8ce48e5480d7")]
[assembly: AssemblyProduct("ChestNetwork.Telemetry")]
[assembly: AssemblyTitle("ChestNetwork.Telemetry")]
[assembly: InternalsVisibleTo("ChestNetwork.Telemetry.Tests")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChestNetwork.Telemetry
{
	public static class Buckets
	{
		public static string Players(int count)
		{
			return Range(count, 0, 1, 3, 5, 10);
		}

		public static string Mods(int count)
		{
			return Range(count, 0, 5, 15, 30, 60);
		}

		public static string Others(int count)
		{
			return Range(count, 0, 1, 2);
		}

		public static string Range(int value, params int[] upperBounds)
		{
			int num = 0;
			for (int i = 0; i < upperBounds.Length; i++)
			{
				int num2 = upperBounds[i];
				if (value <= num2)
				{
					if (num != num2)
					{
						return num.ToString(CultureInfo.InvariantCulture) + "-" + num2.ToString(CultureInfo.InvariantCulture);
					}
					return num2.ToString(CultureInfo.InvariantCulture);
				}
				num = num2 + 1;
			}
			return num.ToString(CultureInfo.InvariantCulture) + "+";
		}
	}
	public sealed class ChestNetworkMetrics
	{
		public const string Prefix = "chestnetwork.";

		public const string Schema = "1";

		private static readonly HashSet<string> VanillaMachines = new HashSet<string>(StringComparer.Ordinal)
		{
			"smelter", "charcoal_kiln", "blastfurnace", "eitrrefinery", "windmill", "piece_spinningwheel", "piece_oven", "fire_pit", "fire_pit_iron", "hearth",
			"bonfire", "piece_bathtub", "piece_groundtorch", "piece_groundtorch_wood", "piece_groundtorch_green", "piece_groundtorch_blue", "piece_groundtorch_mist", "piece_walltorch", "piece_brazierceiling01", "piece_brazierfloor01",
			"piece_brazierfloor02", "piece_jackoturnip", "piece_dvergr_lantern", "piece_dvergr_lantern_pole", "candle_resin"
		};

		public MetricSet Set { get; }

		public Counter Heartbeat { get; }

		public Counter Exports { get; }

		public Counter Actions { get; }

		public Histogram ActionWait { get; }

		public Histogram ContainersTouched { get; }

		public Histogram ItemsMoved { get; }

		public Counter ValidationFailures { get; }

		public Counter ConsumedUnits { get; }

		public Counter ConsumeSources { get; }

		public Counter VanillaFallbacks { get; }

		public Counter Fills { get; }

		public Histogram FillAllMachines { get; }

		public Counter StoredUnits { get; }

		public Histogram ArmorSlotsFilled { get; }

		public Counter OwnershipRequests { get; }

		public Counter OwnershipServed { get; }

		public Histogram OwnershipAcquire { get; }

		public Counter DataTimeouts { get; }

		public Counter ItemReturns { get; }

		public Counter Handshakes { get; }

		public Counter Credits { get; }

		public Counter CreditUnits { get; }

		public Histogram CreditOpenWait { get; }

		public Histogram CreditReserved { get; }

		public Histogram CreditOpen { get; }

		public Histogram CreditShare { get; }

		public Histogram CreditHeld { get; }

		public Histogram ResolveTime { get; }

		public Histogram Stations { get; }

		public Histogram Containers { get; }

		public Counter Exceptions { get; }

		public Gauge Settings { get; }

		public Gauge SharedPatches { get; }

		public ChestNetworkMetrics(MetricSet set)
		{
			Set = set ?? throw new ArgumentNullException("set");
			Heartbeat = set.AddCounter("chestnetwork.session.heartbeat", "{export}", "One per export of a running game: active sessions.");
			Exports = set.AddCounter("chestnetwork.telemetry.export", "{request}", "Telemetry requests by result.", "result");
			Actions = set.AddCounter("chestnetwork.action", "{action}", "Network actions by flow, stage and outcome.", "flow", "stage", "outcome");
			ActionWait = set.AddHistogram("chestnetwork.action.wait", "ms", "Delay between the start of an action and its commit.", new long[9] { 50L, 100L, 250L, 500L, 1000L, 2000L, 3500L, 5000L, 10000L }, "flow");
			ContainersTouched = set.AddHistogram("chestnetwork.action.containers_touched", "{container}", "Containers changed by a committed action.", new long[9] { 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L }, "flow");
			ItemsMoved = set.AddHistogram("chestnetwork.action.items_moved", "{item}", "Units moved by a committed action.", new long[10] { 0L, 1L, 5L, 10L, 25L, 50L, 100L, 250L, 500L, 1000L }, "flow");
			ValidationFailures = set.AddCounter("chestnetwork.validation.failed", "{validation}", "Plans failing their revalidation, by first issue.", "flow", "stage", "issue");
			ConsumedUnits = set.AddCounter("chestnetwork.consume.units", "{item}", "Units consumed, by origin.", "flow", "origin");
			ConsumeSources = set.AddCounter("chestnetwork.consume.source", "{action}", "Consumptions served by the inventory alone or with the network.", "flow", "source");
			VanillaFallbacks = set.AddCounter("chestnetwork.consume.vanilla_fallback", "{action}", "Consumptions left to vanilla, by plan status.", "flow", "reason");
			Fills = set.AddCounter("chestnetwork.fill", "{action}", "Machine fills by machine, slot and status.", "machine", "slot", "status");
			FillAllMachines = set.AddHistogram("chestnetwork.fill_all.machines", "{machine}", "Machines of one Shift + A: filled, left short by the chests, skipped because another player held them.", new long[9] { 0L, 1L, 2L, 3L, 5L, 10L, 20L, 50L, 100L }, "result");
			StoredUnits = set.AddCounter("chestnetwork.store.units", "{item}", "Quick stack units: stored, left for lack of room, held nowhere.", "result");
			ArmorSlotsFilled = set.AddHistogram("chestnetwork.armor.slots_filled", "{slot}", "Armor stand slots dressed by one action.", new long[5] { 0L, 1L, 2L, 3L, 4L });
			OwnershipRequests = set.AddCounter("chestnetwork.ownership.request", "{request}", "Ownership requests sent, claimed, granted, refused, unanswered.", "result");
			OwnershipServed = set.AddCounter("chestnetwork.ownership.served", "{request}", "Ownership requests answered as owner, by decision.", "decision");
			OwnershipAcquire = set.AddHistogram("chestnetwork.ownership.acquire", "ms", "Delay between an ownership request and the data received.", new long[10] { 25L, 50L, 100L, 250L, 500L, 1000L, 2000L, 3000L, 5000L, 10000L }, "kind");
			DataTimeouts = set.AddCounter("chestnetwork.ownership.data_timeout", "{grant}", "Grants whose data never arrived, by action taken.", "action");
			ItemReturns = set.AddCounter("chestnetwork.item_return", "{item}", "Units given back after a refused insertion, by destination.", "destination");
			Credits = set.AddCounter("chestnetwork.credit", "{message}", "Credit messages (#46), by side and result.", "side", "result");
			CreditUnits = set.AddCounter("chestnetwork.credit.units", "{item}", "Units of credit, by side and result.", "side", "result");
			CreditOpenWait = set.AddHistogram("chestnetwork.credit.open_wait", "ms", "Wait of a menu on a chest that backs credits (#67), by how it ended: at once, answered, safety delay.", new long[11]
			{
				0L, 25L, 50L, 100L, 200L, 300L, 500L, 1000L, 2000L, 5000L,
				10000L
			}, "result");
			CreditReserved = set.AddHistogram("chestnetwork.credit.reserved", "{item}", "Units reserved by the open credits and debts, sampled every 10 s on the server.", new long[11]
			{
				0L, 1L, 5L, 10L, 25L, 50L, 100L, 250L, 500L, 1000L,
				5000L
			}, "kind");
			CreditOpen = set.AddHistogram("chestnetwork.credit.open", "{credit}", "Credits and debts open, sampled every 10 s on the server.", new long[9] { 0L, 1L, 2L, 3L, 5L, 10L, 20L, 50L, 100L }, "kind");
			CreditShare = set.AddHistogram("chestnetwork.credit.reserved_share", "%", "Share of the stock reserved, all items and the largest item, sampled every 10 s.", new long[9] { 0L, 10L, 25L, 40L, 50L, 60L, 75L, 90L, 99L }, "stat");
			CreditHeld = set.AddHistogram("chestnetwork.credit.held", "ms", "How long a credit was held, from its grant to its end.", new long[10] { 100L, 250L, 500L, 1000L, 2000L, 5000L, 10000L, 30000L, 60000L, 300000L });
			Handshakes = set.AddCounter("chestnetwork.handshake", "{connection}", "Version checks, by side and result.", "side", "result");
			ResolveTime = set.AddHistogram("chestnetwork.network.resolve", "us", "Capture of the network view of an action.", new long[9] { 50L, 100L, 250L, 500L, 1000L, 2000L, 5000L, 10000L, 20000L }, "view");
			Stations = set.AddHistogram("chestnetwork.network.stations", "{station}", "Stations in the network of an action.", new long[10] { 0L, 1L, 2L, 3L, 5L, 10L, 20L, 50L, 100L, 500L });
			Containers = set.AddHistogram("chestnetwork.network.containers", "{container}", "Containers eligible for an action, and loaded in total.", new long[11]
			{
				0L, 1L, 2L, 5L, 10L, 20L, 50L, 100L, 200L, 500L,
				2000L
			}, "kind");
			Exceptions = set.AddCounter("chestnetwork.exception", "{exception}", "Exceptions caught by the mod, by component and type.", "component", "type");
			Settings = set.AddGauge("chestnetwork.config.setting", "1", "Settings in use (booleans and choices only).", "key", "value");
			SharedPatches = set.AddGauge("chestnetwork.mods.shared_patches", "1", "Other mods patching each game method the mod patches.", "method", "others");
		}

		public void Attach(TelemetryExporter exporter)
		{
			exporter.BeforeCollect = delegate
			{
				Heartbeat.Add(1L);
			};
			exporter.AfterExport = delegate(ExportResult result)
			{
				Exports.Add(1L, Label(result));
			};
		}

		public static string Machine(string? prefab)
		{
			string text = prefab?.ToLowerInvariant();
			if (text == null || !VanillaMachines.Contains(text))
			{
				return "other";
			}
			return text;
		}

		public static string ExceptionType(Exception? exception)
		{
			if (exception == null)
			{
				return "none";
			}
			Type type = exception.GetType();
			if (!IsLibrary(type.Assembly.GetName().Name))
			{
				return "other";
			}
			return type.Name;
		}

		internal static bool IsLibrary(string? assembly)
		{
			if (!(assembly == "mscorlib") && !(assembly == "System"))
			{
				return assembly?.StartsWith("System.", StringComparison.Ordinal) ?? false;
			}
			return true;
		}

		public static string Role(bool inWorld, bool dedicated, bool server, bool openServer)
		{
			if (inWorld)
			{
				if (!dedicated)
				{
					if (!server)
					{
						return "client";
					}
					if (!openServer)
					{
						return "solo";
					}
					return "host";
				}
				return "dedicated";
			}
			return "menu";
		}

		public static bool TrySetting(string section, string key, object? value, string excludedSection, out string setting, out string label)
		{
			setting = Label(section) + "." + Label(key);
			label = ((!(value is bool)) ? Label(value) : (((bool)value) ? "true" : "false"));
			if (section != excludedSection)
			{
				if (!(value is bool))
				{
					return value is Enum;
				}
				return true;
			}
			return false;
		}

		public static string Label(object? value)
		{
			string text = value?.ToString() ?? "none";
			StringBuilder stringBuilder = new StringBuilder(text.Length + 4);
			for (int i = 0; i < text.Length; i++)
			{
				char c = text[i];
				if (char.IsUpper(c))
				{
					if (i > 0 && stringBuilder[stringBuilder.Length - 1] != '_')
					{
						stringBuilder.Append('_');
					}
					stringBuilder.Append(char.ToLowerInvariant(c));
				}
				else
				{
					stringBuilder.Append((c == ' ' || c == '-') ? '_' : c);
				}
			}
			return stringBuilder.ToString();
		}
	}
	public static class Clock
	{
		public static long UnixNanos()
		{
			return (DateTime.UtcNow.Ticks - DateTime.UnixEpoch.Ticks) * 100;
		}

		public static long Timestamp()
		{
			return Stopwatch.GetTimestamp();
		}

		public static double Seconds()
		{
			return Seconds(Stopwatch.GetTimestamp(), Stopwatch.Frequency);
		}

		public static long MicrosecondsSince(long timestamp)
		{
			return Microseconds(Stopwatch.GetTimestamp() - timestamp, Stopwatch.Frequency);
		}

		internal static long Microseconds(long ticks, long frequency)
		{
			return (long)((double)ticks * (1000000.0 / (double)frequency));
		}

		internal static double Seconds(long ticks, long frequency)
		{
			return (double)ticks / (double)frequency;
		}
	}
	public sealed class HttpTransport : ITransport
	{
		private readonly Uri _endpoint;

		private readonly int _timeoutMs;

		private readonly string _userAgent;

		public HttpTransport(Uri endpoint, TimeSpan timeout, string userAgent)
		{
			_endpoint = endpoint ?? throw new ArgumentNullException("endpoint");
			_timeoutMs = (int)Math.Max(1.0, timeout.TotalMilliseconds);
			_userAgent = userAgent ?? string.Empty;
		}

		public bool Send(byte[] body)
		{
			try
			{
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_endpoint);
				httpWebRequest.Method = "POST";
				httpWebRequest.ContentType = "application/json";
				httpWebRequest.UserAgent = _userAgent;
				httpWebRequest.Timeout = _timeoutMs;
				httpWebRequest.ReadWriteTimeout = _timeoutMs;
				httpWebRequest.ContentLength = body.Length;
				httpWebRequest.KeepAlive = false;
				httpWebRequest.AllowAutoRedirect = false;
				using (Stream stream = httpWebRequest.GetRequestStream())
				{
					stream.Write(body, 0, body.Length);
				}
				using HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				return (int)httpWebResponse.StatusCode / 100 == 2;
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
	public enum MetricKind
	{
		Counter,
		Histogram,
		Gauge
	}
	public sealed class MetricSet
	{
		public const string Overflow = "overflow";

		public const string None = "none";

		private readonly List<Instrument> _instruments = new List<Instrument>();

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

		private long _lastCollect;

		private volatile bool _disabled;

		public int MaxSeriesPerInstrument { get; }

		public bool IsEnabled => !_disabled;

		public MetricSet(long startUnixNanos, int maxSeriesPerInstrument = 64)
		{
			if (maxSeriesPerInstrument < 1)
			{
				throw new ArgumentOutOfRangeException("maxSeriesPerInstrument");
			}
			_lastCollect = startUnixNanos;
			MaxSeriesPerInstrument = maxSeriesPerInstrument;
		}

		public void Disable()
		{
			_disabled = true;
		}

		public Counter AddCounter(string name, string unit, string description, params string[] keys)
		{
			return Add(new Counter(this, name, unit, description, keys));
		}

		public Histogram AddHistogram(string name, string unit, string description, long[] bounds, params string[] keys)
		{
			return Add(new Histogram(this, name, unit, description, bounds, keys));
		}

		public Gauge AddGauge(string name, string unit, string description, params string[] keys)
		{
			return Add(new Gauge(this, name, unit, description, keys));
		}

		public MetricBatch Collect(long nowUnixNanos)
		{
			List<MetricData> list = new List<MetricData>();
			if (!_disabled)
			{
				Instrument[] array;
				lock (_instruments)
				{
					array = _instruments.ToArray();
				}
				Instrument[] array2 = array;
				foreach (Instrument instrument in array2)
				{
					List<DataPoint> list2 = instrument.Drain();
					if (list2.Count > 0)
					{
						list.Add(new MetricData(instrument, list2));
					}
				}
			}
			return new MetricBatch(Interlocked.Exchange(ref _lastCollect, nowUnixNanos), nowUnixNanos, list);
		}

		private T Add<T>(T instrument) where T : Instrument
		{
			lock (_instruments)
			{
				if (!_names.Add(instrument.Name))
				{
					throw new ArgumentException("Instrument " + instrument.Name + " already exists.", "instrument");
				}
				_instruments.Add(instrument);
				return instrument;
			}
		}
	}
	internal readonly struct Labels : IEquatable<Labels>
	{
		public static Labels Overflow { get; } = new Labels("overflow", "overflow", "overflow");

		public string A { get; }

		public string B { get; }

		public string C { get; }

		public string this[int index] => index switch
		{
			0 => A, 
			1 => B, 
			_ => C, 
		};

		public Labels(string? a, string? b, string? c)
		{
			A = a ?? "none";
			B = b ?? "none";
			C = c ?? "none";
		}

		public bool Equals(Labels other)
		{
			if (string.Equals(A, other.A, StringComparison.Ordinal) && string.Equals(B, other.B, StringComparison.Ordinal))
			{
				return string.Equals(C, other.C, StringComparison.Ordinal);
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is Labels other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (((StringComparer.Ordinal.GetHashCode(A) * 397) ^ StringComparer.Ordinal.GetHashCode(B)) * 397) ^ StringComparer.Ordinal.GetHashCode(C);
		}
	}
	public abstract class Instrument
	{
		public string Name { get; }

		public string Unit { get; }

		public string Description { get; }

		public IReadOnlyList<string> Keys { get; }

		public abstract MetricKind Kind { get; }

		public virtual IReadOnlyList<long> Bounds => Array.Empty<long>();

		private protected MetricSet Owner { get; }

		private protected Instrument(MetricSet owner, string name, string unit, string description, string[] keys)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentException("An instrument needs a name.", "name");
			}
			if (keys == null || keys.Length > 3)
			{
				throw new ArgumentException("An instrument has at most three attributes.", "keys");
			}
			Owner = owner;
			Name = name;
			Unit = unit ?? string.Empty;
			Description = description ?? string.Empty;
			Keys = keys;
		}

		internal abstract List<DataPoint> Drain();

		private protected KeyValuePair<string, string>[] Attributes(Labels labels)
		{
			KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[Keys.Count];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new KeyValuePair<string, string>(Keys[i], labels[i]);
			}
			return array;
		}
	}
	public abstract class Instrument<TCell> : Instrument where TCell : class
	{
		private readonly ConcurrentDictionary<Labels, TCell> _cells = new ConcurrentDictionary<Labels, TCell>();

		private readonly Func<Labels, TCell> _create;

		private protected Instrument(MetricSet owner, string name, string unit, string description, string[] keys, Func<TCell> create)
			: base(owner, name, unit, description, keys)
		{
			_create = (Labels _) => create();
		}

		private protected void Update<TValue>(string? a, string? b, string? c, TValue value, Action<TCell, TValue> update)
		{
			if (!base.Owner.IsEnabled)
			{
				return;
			}
			try
			{
				Labels key = new Labels(a, b, c);
				if (!_cells.TryGetValue(key, out var value2))
				{
					if (_cells.Count >= base.Owner.MaxSeriesPerInstrument)
					{
						key = Labels.Overflow;
					}
					value2 = _cells.GetOrAdd(key, _create);
				}
				update(value2, value);
			}
			catch (Exception)
			{
				base.Owner.Disable();
			}
		}

		internal void UpdateForTest(Action update)
		{
			Update(null, null, null, update, delegate(TCell _, Action action)
			{
				action();
			});
		}

		internal sealed override List<DataPoint> Drain()
		{
			List<DataPoint> list = new List<DataPoint>();
			foreach (KeyValuePair<Labels, TCell> cell in _cells)
			{
				DataPoint dataPoint = Drain(Attributes(cell.Key), cell.Value);
				if (dataPoint != null)
				{
					list.Add(dataPoint);
				}
			}
			list.Sort(DataPoint.CompareAttributes);
			return list;
		}

		private protected abstract DataPoint? Drain(KeyValuePair<string, string>[] attributes, TCell cell);
	}
	public sealed class Counter : Instrument<Counter.Cell>
	{
		public sealed class Cell
		{
			internal long Value;
		}

		private static readonly Action<Cell, long> Increment = delegate(Cell cell, long value)
		{
			Interlocked.Add(ref cell.Value, value);
		};

		public override MetricKind Kind => MetricKind.Counter;

		internal Counter(MetricSet owner, string name, string unit, string description, string[] keys)
			: base(owner, name, unit, description, keys, (Func<Cell>)(() => new Cell()))
		{
		}

		public void Add(long value, string? a = null, string? b = null, string? c = null)
		{
			if (value > 0)
			{
				Update(a, b, c, value, Increment);
			}
		}

		private protected override DataPoint? Drain(KeyValuePair<string, string>[] attributes, Cell cell)
		{
			long num = Interlocked.Exchange(ref cell.Value, 0L);
			if (num != 0L)
			{
				return DataPoint.Of(attributes, num);
			}
			return null;
		}
	}
	public sealed class Gauge : Instrument<Gauge.Cell>
	{
		public sealed class Cell
		{
			internal long Value;

			internal int IsSet;
		}

		private static readonly Action<Cell, long> Assign = delegate(Cell cell, long value)
		{
			Interlocked.Exchange(ref cell.Value, value);
			Interlocked.Exchange(ref cell.IsSet, 1);
		};

		public override MetricKind Kind => MetricKind.Gauge;

		internal Gauge(MetricSet owner, string name, string unit, string description, string[] keys)
			: base(owner, name, unit, description, keys, (Func<Cell>)(() => new Cell()))
		{
		}

		public void Set(long value, string? a = null, string? b = null, string? c = null)
		{
			Update(a, b, c, value, Assign);
		}

		private protected override DataPoint? Drain(KeyValuePair<string, string>[] attributes, Cell cell)
		{
			if (Interlocked.Exchange(ref cell.IsSet, 0) != 1)
			{
				return null;
			}
			return DataPoint.Of(attributes, Interlocked.Read(in cell.Value));
		}
	}
	public sealed class Histogram : Instrument<Histogram.Cell>
	{
		public sealed class Cell
		{
			internal readonly long[] Buckets;

			internal long Sum;

			internal Cell(int buckets)
			{
				Buckets = new long[buckets];
			}
		}

		private readonly long[] _bounds;

		private readonly Action<Cell, long> _record;

		public override MetricKind Kind => MetricKind.Histogram;

		public override IReadOnlyList<long> Bounds => _bounds;

		internal Histogram(MetricSet owner, string name, string unit, string description, long[] bounds, string[] keys)
			: base(owner, name, unit, description, keys, (Func<Cell>)(() => new Cell(bounds.Length + 1)))
		{
			Histogram histogram = this;
			for (int num = 1; num < bounds.Length; num++)
			{
				if (bounds[num] <= bounds[num - 1])
				{
					throw new ArgumentException("Histogram bounds must be strictly increasing.", "bounds");
				}
			}
			_bounds = (long[])bounds.Clone();
			_record = delegate(Cell cell, long value)
			{
				Interlocked.Increment(ref cell.Buckets[histogram.BucketOf(value)]);
				Interlocked.Add(ref cell.Sum, value);
			};
		}

		public void Record(long value, string? a = null, string? b = null, string? c = null)
		{
			Update(a, b, c, value, _record);
		}

		internal int BucketOf(long value)
		{
			for (int i = 0; i < _bounds.Length; i++)
			{
				if (value <= _bounds[i])
				{
					return i;
				}
			}
			return _bounds.Length;
		}

		private protected override DataPoint? Drain(KeyValuePair<string, string>[] attributes, Cell cell)
		{
			long[] array = new long[cell.Buckets.Length];
			long num = 0L;
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Interlocked.Exchange(ref cell.Buckets[i], 0L);
				num += array[i];
			}
			long sum = Interlocked.Exchange(ref cell.Sum, 0L);
			if (num != 0L)
			{
				return DataPoint.OfHistogram(attributes, num, sum, array);
			}
			return null;
		}
	}
	public sealed class DataPoint
	{
		public IReadOnlyList<KeyValuePair<string, string>> Attributes { get; }

		public long Value { get; }

		public long Count { get; }

		public long Sum { get; }

		public IReadOnlyList<long> BucketCounts { get; }

		private DataPoint(KeyValuePair<string, string>[] attributes, long value, long count, long sum, long[] bucketCounts)
		{
			Attributes = attributes;
			Value = value;
			Count = count;
			Sum = sum;
			BucketCounts = bucketCounts;
		}

		internal static DataPoint Of(KeyValuePair<string, string>[] attributes, long value)
		{
			return new DataPoint(attributes, value, 0L, 0L, Array.Empty<long>());
		}

		internal static DataPoint OfHistogram(KeyValuePair<string, string>[] attributes, long count, long sum, long[] buckets)
		{
			return new DataPoint(attributes, 0L, count, sum, buckets);
		}

		internal static int CompareAttributes(DataPoint x, DataPoint y)
		{
			for (int i = 0; i < x.Attributes.Count && i < y.Attributes.Count; i++)
			{
				int num = string.CompareOrdinal(x.Attributes[i].Value, y.Attributes[i].Value);
				if (num != 0)
				{
					return num;
				}
			}
			return 0;
		}
	}
	public sealed class MetricData
	{
		public Instrument Instrument { get; }

		public IReadOnlyList<DataPoint> Points { get; }

		internal MetricData(Instrument instrument, IReadOnlyList<DataPoint> points)
		{
			Instrument = instrument;
			Points = points;
		}
	}
	public sealed class MetricBatch
	{
		public long StartUnixNanos { get; }

		public long EndUnixNanos { get; }

		public IReadOnlyList<MetricData> Metrics { get; }

		public bool IsEmpty => Metrics.Count == 0;

		internal MetricBatch(long startUnixNanos, long endUnixNanos, IReadOnlyList<MetricData> metrics)
		{
			StartUnixNanos = startUnixNanos;
			EndUnixNanos = endUnixNanos;
			Metrics = metrics;
		}
	}
	public static class OtlpJson
	{
		internal const int Delta = 1;

		public static string Encode(IReadOnlyList<KeyValuePair<string, string>> resource, string scopeName, string scopeVersion, MetricBatch batch)
		{
			StringBuilder stringBuilder = new StringBuilder(1024);
			stringBuilder.Append("{\"resourceMetrics\":[{\"resource\":{\"attributes\":");
			AppendAttributes(stringBuilder, resource);
			stringBuilder.Append("},\"scopeMetrics\":[{\"scope\":{\"name\":");
			AppendString(stringBuilder, scopeName);
			stringBuilder.Append(",\"version\":");
			AppendString(stringBuilder, scopeVersion);
			stringBuilder.Append("},\"metrics\":[");
			for (int i = 0; i < batch.Metrics.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(',');
				}
				AppendMetric(stringBuilder, batch.Metrics[i], batch.StartUnixNanos, batch.EndUnixNanos);
			}
			stringBuilder.Append("]}]}]}");
			return stringBuilder.ToString();
		}

		private static void AppendMetric(StringBuilder json, MetricData metric, long start, long end)
		{
			Instrument instrument = metric.Instrument;
			json.Append("{\"name\":");
			AppendString(json, instrument.Name);
			json.Append(",\"unit\":");
			AppendString(json, instrument.Unit);
			json.Append(",\"description\":");
			AppendString(json, instrument.Description);
			switch (instrument.Kind)
			{
			case MetricKind.Counter:
				json.Append(",\"sum\":{\"aggregationTemporality\":").Append(1).Append(",\"isMonotonic\":true,\"dataPoints\":[");
				break;
			case MetricKind.Histogram:
				json.Append(",\"histogram\":{\"aggregationTemporality\":").Append(1).Append(",\"dataPoints\":[");
				break;
			default:
				json.Append(",\"gauge\":{\"dataPoints\":[");
				break;
			}
			for (int i = 0; i < metric.Points.Count; i++)
			{
				if (i > 0)
				{
					json.Append(',');
				}
				AppendPoint(json, instrument, metric.Points[i], start, end);
			}
			json.Append("]}}");
		}

		private static void AppendPoint(StringBuilder json, Instrument instrument, DataPoint point, long start, long end)
		{
			json.Append("{\"attributes\":");
			AppendAttributes(json, point.Attributes);
			if (instrument.Kind != MetricKind.Gauge)
			{
				json.Append(",\"startTimeUnixNano\":");
				AppendInteger(json, start);
			}
			json.Append(",\"timeUnixNano\":");
			AppendInteger(json, end);
			if (instrument.Kind == MetricKind.Histogram)
			{
				json.Append(",\"count\":");
				AppendInteger(json, point.Count);
				json.Append(",\"sum\":").Append(point.Sum.ToString(CultureInfo.InvariantCulture));
				json.Append(",\"bucketCounts\":[");
				for (int i = 0; i < point.BucketCounts.Count; i++)
				{
					if (i > 0)
					{
						json.Append(',');
					}
					AppendInteger(json, point.BucketCounts[i]);
				}
				json.Append("],\"explicitBounds\":[");
				for (int j = 0; j < instrument.Bounds.Count; j++)
				{
					if (j > 0)
					{
						json.Append(',');
					}
					json.Append(instrument.Bounds[j].ToString(CultureInfo.InvariantCulture));
				}
				json.Append(']');
			}
			else
			{
				json.Append(",\"asInt\":");
				AppendInteger(json, point.Value);
			}
			json.Append('}');
		}

		private static void AppendAttributes(StringBuilder json, IReadOnlyList<KeyValuePair<string, string>> attributes)
		{
			json.Append('[');
			for (int i = 0; i < attributes.Count; i++)
			{
				if (i > 0)
				{
					json.Append(',');
				}
				json.Append("{\"key\":");
				AppendString(json, attributes[i].Key);
				json.Append(",\"value\":{\"stringValue\":");
				AppendString(json, attributes[i].Value);
				json.Append("}}");
			}
			json.Append(']');
		}

		private static void AppendInteger(StringBuilder json, long value)
		{
			json.Append('"').Append(value.ToString(CultureInfo.InvariantCulture)).Append('"');
		}

		internal static void AppendString(StringBuilder json, string? value)
		{
			json.Append('"');
			string text = value ?? string.Empty;
			foreach (char c in text)
			{
				switch (c)
				{
				case '"':
					json.Append("\\\"");
					continue;
				case '\\':
					json.Append("\\\\");
					continue;
				case '\n':
					json.Append("\\n");
					continue;
				case '\r':
					json.Append("\\r");
					continue;
				case '\t':
					json.Append("\\t");
					continue;
				}
				if (c < ' ')
				{
					StringBuilder stringBuilder = json.Append("\\u");
					int num = c;
					stringBuilder.Append(num.ToString("x4", CultureInfo.InvariantCulture));
				}
				else
				{
					json.Append(c);
				}
			}
			json.Append('"');
		}
	}
	public sealed class PendingWait
	{
		private readonly double _maximumSeconds;

		private object? _key;

		private double _since;

		public PendingWait(TimeSpan maximum)
		{
			if (maximum <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("maximum", maximum, "Must be positive.");
			}
			_maximumSeconds = maximum.TotalSeconds;
		}

		public void Blocked(object key, double now)
		{
			if (key != null && (key != _key || now - _since > _maximumSeconds))
			{
				_key = key;
				_since = now;
			}
		}

		public long? Committed(object key, double now)
		{
			bool num = key != null && key == _key;
			double num2 = now - _since;
			_key = null;
			if (!num || !(num2 >= 0.0) || !(num2 <= _maximumSeconds))
			{
				return null;
			}
			return (long)Math.Round(num2 * 1000.0);
		}
	}
	public static class SessionId
	{
		public static string New()
		{
			byte[] array = new byte[10];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return Format(Clock.UnixNanos() / 1000000, array);
		}

		public static string Format(long unixMillis, byte[] random)
		{
			if (random == null || random.Length < 10)
			{
				throw new ArgumentException("Ten random bytes are needed.", "random");
			}
			byte[] array = new byte[16];
			for (int i = 0; i < 6; i++)
			{
				array[i] = (byte)(unixMillis >> 8 * (5 - i));
			}
			array[6] = (byte)(0x70 | (random[0] & 0xF));
			array[7] = random[1];
			array[8] = (byte)(0x80 | (random[2] & 0x3F));
			Array.Copy(random, 3, array, 9, 7);
			StringBuilder stringBuilder = new StringBuilder(32);
			byte[] array2 = array;
			foreach (byte b in array2)
			{
				stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}
	}
	public static class TelemetryEndpoint
	{
		public const string Production = "https://telemetry.roimarmier.xyz/valheim/chestnetwork/v1/metrics";

		public const string EndpointVariable = "CHESTNETWORK_TELEMETRY_ENDPOINT";

		public const string IntervalVariable = "CHESTNETWORK_TELEMETRY_INTERVAL";

		public static readonly TimeSpan DefaultInterval = TimeSpan.FromSeconds(60.0);

		public static readonly TimeSpan MinimumInterval = TimeSpan.FromSeconds(5.0);

		public static Uri Resolve(string? overrideValue)
		{
			if (!Uri.TryCreate(overrideValue?.Trim(), UriKind.Absolute, out Uri result) || (!(result.Scheme == Uri.UriSchemeHttp) && !(result.Scheme == Uri.UriSchemeHttps)))
			{
				return new Uri("https://telemetry.roimarmier.xyz/valheim/chestnetwork/v1/metrics");
			}
			return result;
		}

		public static TimeSpan Interval(string? overrideValue)
		{
			if (!int.TryParse(overrideValue?.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return DefaultInterval;
			}
			TimeSpan timeSpan = TimeSpan.FromSeconds(Math.Min(result, 3600));
			if (!(timeSpan < MinimumInterval))
			{
				return timeSpan;
			}
			return MinimumInterval;
		}
	}
	public interface ITransport
	{
		bool Send(byte[] body);
	}
	public enum ExportResult
	{
		Sent,
		Empty,
		Failed,
		Stopped
	}
	public sealed class TelemetryExporter
	{
		private sealed class CutBatch
		{
			public IReadOnlyList<KeyValuePair<string, string>> Resource { get; }

			public MetricBatch Batch { get; }

			public CutBatch(IReadOnlyList<KeyValuePair<string, string>> resource, MetricBatch batch)
			{
				Resource = resource;
				Batch = batch;
			}
		}

		internal const int MaxCutBatches = 4;

		private readonly ConcurrentQueue<CutBatch> _cut = new ConcurrentQueue<CutBatch>();

		private readonly MetricSet _metrics;

		private readonly Func<IReadOnlyList<KeyValuePair<string, string>>> _resource;

		private readonly string _scopeName;

		private readonly string _scopeVersion;

		private readonly ITransport _transport;

		private readonly Func<long> _clock;

		private readonly int _maxConsecutiveFailures;

		private readonly AutoResetEvent _wake = new AutoResetEvent(initialState: false);

		private readonly object _exportLock = new object();

		private Thread? _thread;

		private int _consecutiveFailures;

		private volatile bool _stopping;

		private volatile bool _stopped;

		public TimeSpan Interval { get; }

		public bool IsStopped
		{
			get
			{
				if (!_stopped)
				{
					return !_metrics.IsEnabled;
				}
				return true;
			}
		}

		public Action? BeforeCollect { get; set; }

		public Action<ExportResult>? AfterExport { get; set; }

		public TelemetryExporter(MetricSet metrics, Func<IReadOnlyList<KeyValuePair<string, string>>> resource, string scopeName, string scopeVersion, ITransport transport, Func<long> clock, TimeSpan interval, int maxConsecutiveFailures = 3)
		{
			if (interval <= TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("interval");
			}
			if (maxConsecutiveFailures < 1)
			{
				throw new ArgumentOutOfRangeException("maxConsecutiveFailures");
			}
			_metrics = metrics ?? throw new ArgumentNullException("metrics");
			_resource = resource ?? throw new ArgumentNullException("resource");
			_scopeName = scopeName ?? string.Empty;
			_scopeVersion = scopeVersion ?? string.Empty;
			_transport = transport ?? throw new ArgumentNullException("transport");
			_clock = clock ?? throw new ArgumentNullException("clock");
			Interval = interval;
			_maxConsecutiveFailures = maxConsecutiveFailures;
		}

		public void Start()
		{
			if (_thread == null)
			{
				_thread = new Thread(Run)
				{
					IsBackground = true,
					Name = "ChestNetwork telemetry"
				};
				_thread.Start();
			}
		}

		public void Cut()
		{
			try
			{
				if (!IsStopped && _cut.Count < 4)
				{
					MetricBatch metricBatch = _metrics.Collect(_clock());
					if (!metricBatch.IsEmpty)
					{
						_cut.Enqueue(new CutBatch(_resource(), metricBatch));
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public void Stop(TimeSpan timeout)
		{
			_stopping = true;
			_wake.Set();
			Thread thread = _thread;
			if (thread != null && thread != Thread.CurrentThread)
			{
				thread.Join(timeout);
			}
			_stopped = true;
		}

		public void Abandon()
		{
			_metrics.Disable();
			_stopping = true;
			_stopped = true;
			_wake.Set();
		}

		public ExportResult ExportOnce()
		{
			lock (_exportLock)
			{
				while (true)
				{
					if (!_cut.TryDequeue(out CutBatch cut))
					{
						break;
					}
					if (Send(() => cut.Resource, () => cut.Batch) == ExportResult.Stopped)
					{
						return ExportResult.Stopped;
					}
				}
				return Send(_resource, delegate
				{
					BeforeCollect?.Invoke();
					return _metrics.Collect(_clock());
				});
			}
		}

		private ExportResult Send(Func<IReadOnlyList<KeyValuePair<string, string>>> resource, Func<MetricBatch> collect)
		{
			if (IsStopped)
			{
				return ExportResult.Stopped;
			}
			ExportResult exportResult;
			try
			{
				MetricBatch metricBatch = collect();
				if (metricBatch.IsEmpty)
				{
					return ExportResult.Empty;
				}
				string s = OtlpJson.Encode(resource(), _scopeName, _scopeVersion, metricBatch);
				exportResult = ((!_transport.Send(Encoding.UTF8.GetBytes(s))) ? ExportResult.Failed : ExportResult.Sent);
			}
			catch (Exception)
			{
				exportResult = ExportResult.Failed;
			}
			if (exportResult == ExportResult.Failed && ++_consecutiveFailures >= _maxConsecutiveFailures)
			{
				_stopped = true;
				_metrics.Disable();
				return ExportResult.Stopped;
			}
			if (exportResult == ExportResult.Sent)
			{
				_consecutiveFailures = 0;
			}
			try
			{
				AfterExport?.Invoke(exportResult);
			}
			catch (Exception)
			{
			}
			return exportResult;
		}

		private void Run()
		{
			try
			{
				do
				{
					_wake.WaitOne(Interval);
				}
				while (ExportOnce() != ExportResult.Stopped && !_stopping);
			}
			catch (Exception)
			{
				_stopped = true;
			}
		}
	}
}