Decompiled source of LazyVikings v1.0.8

LazyVikings.dll

Decompiled 4 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using LazyVikings.Functions;
using LazyVikings.Utils;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LazyVikings")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/blacks7ar/LazyVikings/")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("blacks7ar")]
[assembly: AssemblyProduct("LazyVikings")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("31ECF2E6-E44B-445E-BA1B-006232CF230B")]
[assembly: AssemblyFileVersion("1.0.8")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.8.0")]
[module: UnverifiableCode]
[module: <9c6aa9b8-8403-482e-bea4-ed4172f53069>RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<1c53f21b-4054-4af4-8e4e-52ae429b9597>Embedded]
	internal sealed class <1c53f21b-4054-4af4-8e4e-52ae429b9597>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<1c53f21b-4054-4af4-8e4e-52ae429b9597>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class <9c6aa9b8-8403-482e-bea4-ed4172f53069>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <9c6aa9b8-8403-482e-bea4-ed4172f53069>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LazyVikings
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("blacks7ar.LazyVikings", "LazyVikings", "1.0.8")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "blacks7ar.LazyVikings";

		public const string modName = "LazyVikings";

		public const string modAuthor = "blacks7ar";

		public const string modVersion = "1.0.8";

		public const string modLink = "https://valheim.thunderstore.io/package/blacks7ar/LazyVikings/";

		private static string configFileName = "blacks7ar.LazyVikings.cfg";

		private static string configFileFullPath;

		public static readonly ManualLogSource LVLogger;

		private static readonly Harmony _harmony;

		private static readonly ConfigSync _configSync;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		public static ConfigEntry<Toggle> _enableBeehive;

		public static ConfigEntry<float> _beehiveRadius;

		public static ConfigEntry<Toggle> _enableBlastFurnace;

		public static ConfigEntry<float> _blastfurnaceRadius;

		public static ConfigEntry<Automation> _blastfurnaceAutomation;

		public static ConfigEntry<Toggle> _blastfurnaceIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _blastfurnaceAllowAllOres;

		public static ConfigEntry<Toggle> _enableEitrRefinery;

		public static ConfigEntry<float> _eitrrefineryRadius;

		public static ConfigEntry<Automation> _eitrrefineryAutomation;

		public static ConfigEntry<Toggle> _eitrrefineryIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableKiln;

		public static ConfigEntry<float> _kilnRadius;

		public static ConfigEntry<Automation> _kilnAutomation;

		public static ConfigEntry<Toggle> _kilnIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _kilnProcessAllWoods;

		public static ConfigEntry<int> _kilnProductThreshold;

		public static ConfigEntry<Toggle> _enableSmelter;

		public static ConfigEntry<float> _smelterRadius;

		public static ConfigEntry<Automation> _smelterAutomation;

		public static ConfigEntry<Toggle> _smelterIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableSpinningWheel;

		public static ConfigEntry<float> _spinningwheelRadius;

		public static ConfigEntry<Automation> _spinningwheelAutomation;

		public static ConfigEntry<Toggle> _spinningwheelIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableWindmill;

		public static ConfigEntry<float> _windmillRadius;

		public static ConfigEntry<Automation> _windmillAutomation;

		public static ConfigEntry<Toggle> _windmillIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableSapCollector;

		public static ConfigEntry<float> _sapcollectorRadius;

		public static ConfigEntry<Toggle> _enableFermenter;

		public static ConfigEntry<float> _fermenterRadius;

		public static ConfigEntry<Automation> _fermenterAutomation;

		public static ConfigEntry<Toggle> _fermenterIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableSteelKiln;

		public static ConfigEntry<float> _steelKilnRadius;

		public static ConfigEntry<Automation> _steelKilnAutomation;

		public static ConfigEntry<Toggle> _steelKilnIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _enableSteelSlackTub;

		public static ConfigEntry<float> _steelSlackTubRadius;

		public static ConfigEntry<Automation> _steelSlackTubAutomation;

		public static ConfigEntry<Toggle> _steelSlackTubIgnorePrivateAreaCheck;

		public static ConfigEntry<Toggle> _leaveOne;

		public static bool _hasOdinSteelWorks;

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedConfig = true)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedConfig ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			_configSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedConfig;
			return val2;
		}

		private void ConfigWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, configFileName);
			fileSystemWatcher.Changed += OnConfigChanged;
			fileSystemWatcher.Created += OnConfigChanged;
			fileSystemWatcher.Renamed += OnConfigChanged;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void OnConfigChanged(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(configFileFullPath))
			{
				return;
			}
			try
			{
				Logging.LogDebug("OnConfigChanged called..");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				Logging.LogError("There was an issue loading your " + configFileName);
				Logging.LogError("Please check your config entries for spelling and format!");
			}
		}

		public void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Expected O, but got Unknown
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Expected O, but got Unknown
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Expected O, but got Unknown
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Expected O, but got Unknown
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Expected O, but got Unknown
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Expected O, but got Unknown
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Expected O, but got Unknown
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Expected O, but got Unknown
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Expected O, but got Unknown
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Expected O, but got Unknown
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Expected O, but got Unknown
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0429: Expected O, but got Unknown
			//IL_0445: Unknown result type (might be due to invalid IL or missing references)
			//IL_0450: Expected O, but got Unknown
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0477: Expected O, but got Unknown
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_049e: Expected O, but got Unknown
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d7: Expected O, but got Unknown
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Expected O, but got Unknown
			//IL_051a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0525: Expected O, but got Unknown
			//IL_0541: Unknown result type (might be due to invalid IL or missing references)
			//IL_054c: Expected O, but got Unknown
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0585: Expected O, but got Unknown
			//IL_05a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ac: Expected O, but got Unknown
			//IL_05c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d3: Expected O, but got Unknown
			//IL_05ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Expected O, but got Unknown
			//IL_0628: Unknown result type (might be due to invalid IL or missing references)
			//IL_0633: Expected O, but got Unknown
			//IL_064f: Unknown result type (might be due to invalid IL or missing references)
			//IL_065a: Expected O, but got Unknown
			//IL_068a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0695: Expected O, but got Unknown
			//IL_06b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bc: Expected O, but got Unknown
			//IL_06ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f5: Expected O, but got Unknown
			//IL_0711: Unknown result type (might be due to invalid IL or missing references)
			//IL_071c: Expected O, but got Unknown
			//IL_0738: Unknown result type (might be due to invalid IL or missing references)
			//IL_0743: Expected O, but got Unknown
			//IL_075f: Unknown result type (might be due to invalid IL or missing references)
			//IL_076a: Expected O, but got Unknown
			//IL_0798: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a3: Expected O, but got Unknown
			//IL_07bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ca: Expected O, but got Unknown
			_serverConfigLocked = config("01- ServerSync", "Lock Configuration", Toggle.On, new ConfigDescription("If On, the configuration is locked and can be changed by server admins only.", (AcceptableValueBase)null, Array.Empty<object>()));
			_configSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			_leaveOne = config("02- General", "Leave One", Toggle.On, new ConfigDescription("If On, always leaves one item of each material on the container.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableBeehive = config("03- Beehive", "Enable", Toggle.On, new ConfigDescription("Enable/Disables beehive automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_beehiveRadius = config("03- Beehive", "Radius", 5f, new ConfigDescription("Beehives container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_enableBlastFurnace = config("04- Blast Furnace", "Enable", Toggle.On, new ConfigDescription("Enable/Disables blast furnace automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_blastfurnaceAutomation = config("04- Blast Furnace", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_blastfurnaceRadius = config("04- Blast Furnace", "Radius", 5f, new ConfigDescription("Blast furnace container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_blastfurnaceIgnorePrivateAreaCheck = config("04- Blast Furnace", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for blast furnaces.", (AcceptableValueBase)null, Array.Empty<object>()));
			_blastfurnaceAllowAllOres = config("04- Blast Furnace", "Allow All Ores", Toggle.Off, new ConfigDescription("If On, all ores will be process by the blast furnace.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableEitrRefinery = config("05- Eitr Refinery", "Enable", Toggle.On, new ConfigDescription("Enable/Disables eitr refinery automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_eitrrefineryAutomation = config("05- Eitr Refinery", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_eitrrefineryRadius = config("05- Eitr Refinery", "Radius", 5f, new ConfigDescription("Eitr refinery container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_eitrrefineryIgnorePrivateAreaCheck = config("05- Eitr Refinery", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for eitr refinerys.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableKiln = config("07- Kiln", "Enable", Toggle.On, new ConfigDescription("Enable/Disables kiln automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_kilnAutomation = config("07- Kiln", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_kilnRadius = config("07- Kiln", "Radius", 5f, new ConfigDescription("Kiln container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_kilnIgnorePrivateAreaCheck = config("07- Kiln", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for kilns.", (AcceptableValueBase)null, Array.Empty<object>()));
			_kilnProcessAllWoods = config("07- Kiln", "Process All Woods", Toggle.Off, new ConfigDescription("If On, finewood and corewood will also be process into coal.", (AcceptableValueBase)null, Array.Empty<object>()));
			_kilnProductThreshold = config("07- Kiln", "Product Threshold", 0, new ConfigDescription("Kiln's product threshold before it stops auto fueling.\nNOTE: Set to 0 to disable.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
			_enableSapCollector = config("08- SapCollector", "Enable", Toggle.On, new ConfigDescription("Enable/Disables sap collector automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_sapcollectorRadius = config("08- SapCollector", "Radius", 5f, new ConfigDescription("SapCollector container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_enableSmelter = config("09- Smelter", "Enable", Toggle.On, new ConfigDescription("Enable/Disables smelter automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_smelterAutomation = config("09- Smelter", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_smelterRadius = config("09- Smelter", "Radius", 5f, new ConfigDescription("Smelter container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_smelterIgnorePrivateAreaCheck = config("09- Smelter", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for smelters.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableSpinningWheel = config("10- Spinning Wheel", "Enable", Toggle.On, new ConfigDescription("Enable/Disables spinning wheel automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_spinningwheelAutomation = config("10- Spinning Wheel", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_spinningwheelRadius = config("10- Spinning Wheel", "Radius", 5f, new ConfigDescription("Spinning wheel container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_spinningwheelIgnorePrivateAreaCheck = config("10- Spinning Wheel", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for spinning wheels.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableWindmill = config("11- Windmill", "Enable", Toggle.On, new ConfigDescription("Enable/Disables windmill automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_windmillAutomation = config("11- Windmill", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_windmillRadius = config("11- Windmill", "Radius", 5f, new ConfigDescription("Windmill container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_windmillIgnorePrivateAreaCheck = config("11- Windmill", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for windmills.", (AcceptableValueBase)null, Array.Empty<object>()));
			_enableFermenter = config("06- Fermenter", "Enable", Toggle.On, new ConfigDescription("Enable/Disables fermenter automation.", (AcceptableValueBase)null, Array.Empty<object>()));
			_fermenterAutomation = config("06- Fermenter", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
			_fermenterRadius = config("06- Fermenter", "Radius", 5f, new ConfigDescription("Fermenter container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_fermenterIgnorePrivateAreaCheck = config("06- Fermenter", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for fermenters.", (AcceptableValueBase)null, Array.Empty<object>()));
			_hasOdinSteelWorks = Helper.CheckOdinSteelWorksMod();
			if (_hasOdinSteelWorks)
			{
				_enableSteelKiln = config("12- Steel Kiln", "Enable", Toggle.On, new ConfigDescription("Enable/Disables steel kiln automation.", (AcceptableValueBase)null, Array.Empty<object>()));
				_steelKilnAutomation = config("12- Steel Kiln", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
				_steelKilnRadius = config("12- Steel Kiln", "Radius", 5f, new ConfigDescription("Steel Kiln container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
				_steelKilnIgnorePrivateAreaCheck = config("12- Steel Kiln", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for steel kiln.", (AcceptableValueBase)null, Array.Empty<object>()));
				_enableSteelSlackTub = config("13- Steel Slack Tub", "Enable", Toggle.On, new ConfigDescription("Enable/Disables steel slack tub automation.", (AcceptableValueBase)null, Array.Empty<object>()));
				_steelSlackTubAutomation = config("13- Steel Slack Tub", "Automation", Automation.Both, new ConfigDescription("Choose what to automate.", (AcceptableValueBase)null, Array.Empty<object>()));
				_steelSlackTubRadius = config("13- Steel Slack Tub", "Radius", 5f, new ConfigDescription("Steel slack tub container detection range.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
				_steelSlackTubIgnorePrivateAreaCheck = config("13- Steel Slack Tub", "Ignore Private Area Check", Toggle.On, new ConfigDescription("If On, ignores private area check for steel slack tub.", (AcceptableValueBase)null, Array.Empty<object>()));
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			ConfigWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		static Plugin()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			configFileFullPath = configPath + directorySeparatorChar + configFileName;
			LVLogger = Logger.CreateLogSource("LazyVikings");
			_harmony = new Harmony("blacks7ar.LazyVikings");
			_configSync = new ConfigSync("blacks7ar.LazyVikings")
			{
				DisplayName = "LazyVikings",
				CurrentVersion = "1.0.8",
				MinimumRequiredVersion = "1.0.8"
			};
		}
	}
}
namespace LazyVikings.Utils
{
	public static class Helper
	{
		private static readonly ConcurrentDictionary<float, Stopwatch> _stopwatches = new ConcurrentDictionary<float, Stopwatch>();

		public static bool CheckOdinSteelWorksMod()
		{
			if (!Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.odinssteelworks"))
			{
				return false;
			}
			Logging.LogInfo("OdinSteelWorks detected.. applying patch!");
			return true;
		}

		public static List<Container> GetNearbyContainers(GameObject gameObject, float radius, bool checkWard = true)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			string[] array = new string[3] { "piece", "item", "vehicle" };
			IOrderedEnumerable<Collider> orderedEnumerable = from x in Physics.OverlapSphere(gameObject.transform.position, radius, LayerMask.GetMask(array))
				orderby Vector3.Distance(((Component)x).gameObject.transform.position, gameObject.transform.position)
				select x;
			List<Container> list = new List<Container>();
			foreach (Collider item in orderedEnumerable)
			{
				try
				{
					Container componentInParent = ((Component)item).GetComponentInParent<Container>();
					bool flag = componentInParent.CheckAccess(Player.m_localPlayer.GetPlayerID());
					if (checkWard)
					{
						flag = flag && PrivateArea.CheckAccess(((Component)item).gameObject.transform.position, 0f, false, true);
					}
					Piece componentInParent2 = ((Component)componentInParent).GetComponentInParent<Piece>();
					bool flag2 = (Object)(object)((Component)componentInParent).GetComponentInParent<Vagon>() != (Object)null;
					bool flag3 = (Object)(object)((Component)componentInParent).GetComponentInParent<Ship>() != (Object)null;
					if ((Object)(object)componentInParent2 != (Object)null && flag && componentInParent.GetInventory() != null && !flag2 && !flag3 && componentInParent2.IsPlacedByPlayer())
					{
						list.Add(componentInParent);
					}
				}
				catch
				{
				}
			}
			return list;
		}

		private static float GetGameObjectPositionHash(GameObject gameObject)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = gameObject.transform.position;
			return 1000f * position.x + position.y + 0.001f * position.z;
		}

		public static Stopwatch GetGameObjectStopwatch(GameObject gameObject)
		{
			float gameObjectPositionHash = GetGameObjectPositionHash(gameObject);
			if (_stopwatches.TryGetValue(gameObjectPositionHash, out var value))
			{
				return value;
			}
			value = new Stopwatch();
			_stopwatches.TryAdd(gameObjectPositionHash, value);
			return value;
		}

		public static List<ItemData> GetNearbyItemsFromContainers(IEnumerable<Container> nearbyContainers)
		{
			return nearbyContainers.SelectMany((Container nearbyContainer) => nearbyContainer.GetInventory().GetAllItems()).ToList();
		}

		public static int GetItemAmounts(IEnumerable<ItemData> itemList, ItemData itemData)
		{
			return itemList.Where((ItemData item) => item.m_shared.m_name == itemData.m_shared.m_name).Sum((ItemData item) => item.m_stack);
		}

		private static bool ContainerContainsItem(Container container, ItemData itemData)
		{
			return container.GetInventory().GetAllItems().Any((ItemData item) => item.m_shared.m_name == itemData.m_shared.m_name);
		}

		public static int DeductItemFromContainer(Container container, ItemData itemData, int amount = 1)
		{
			if (!ContainerContainsItem(container, itemData))
			{
				return 0;
			}
			int num = 0;
			List<ItemData> allItems = container.GetInventory().GetAllItems();
			foreach (ItemData item in allItems.Where((ItemData item) => item.m_shared.m_name == itemData.m_shared.m_name))
			{
				if (Plugin._leaveOne.Value == Toggle.On && item.m_stack == 1)
				{
					return 0;
				}
				int num2 = Mathf.Min(item.m_stack, amount);
				item.m_stack -= num2;
				amount -= num2;
				num += num2;
				if (amount <= 0)
				{
					break;
				}
			}
			if (num == 0)
			{
				return 0;
			}
			allItems.RemoveAll((ItemData x) => x.m_stack <= 0);
			container.m_inventory.m_inventory = allItems;
			container.Save();
			container.GetInventory().Changed();
			return num;
		}

		public static int DeductItemFromAllNearbyContainers(GameObject gameObject, float radius, ItemData itemData, int amount, bool checkWard = true)
		{
			List<Container> nearbyContainers = GetNearbyContainers(gameObject, radius, checkWard);
			if (amount == 0)
			{
				return 0;
			}
			int num = 0;
			foreach (int item in from item in nearbyContainers
				where num != amount
				select DeductItemFromContainer(item, itemData, amount))
			{
				num += item;
				amount -= item;
			}
			return num;
		}
	}
	public static class Logging
	{
		public static void LogDebug(string debug)
		{
			Plugin.LVLogger.LogDebug((object)debug);
		}

		public static void LogInfo(string info)
		{
			Plugin.LVLogger.LogInfo((object)info);
		}

		public static void LogWarning(string warning)
		{
			Plugin.LVLogger.LogWarning((object)warning);
		}

		public static void LogError(string error)
		{
			Plugin.LVLogger.LogError((object)error);
		}
	}
	public enum Toggle
	{
		On = 1,
		Off = 0
	}
}
namespace LazyVikings.Patches
{
	[HarmonyPatch]
	public class BeehivePatch
	{
		private static readonly MethodInfo _methodInfo = AccessTools.Method(typeof(BeehivePatch), "DepositToContainers", (Type[])null, (Type[])null);

		[HarmonyPatch(typeof(Beehive), "UpdateBees")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			if (Plugin._enableBeehive.Value == Toggle.Off)
			{
				return instructions;
			}
			List<CodeInstruction> list = instructions.ToList();
			int num = list.Count - 2;
			list.Insert(++num, new CodeInstruction(OpCodes.Ldarga, (object)0));
			list.Insert(++num, new CodeInstruction(OpCodes.Call, (object)_methodInfo));
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
		[HarmonyPrefix]
		private static bool RpcExtract_Prefix(ref Beehive __instance)
		{
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			Beehive beehive = __instance;
			if (Plugin._enableBeehive.Value == Toggle.Off || !beehive.m_nview.IsOwner())
			{
				return true;
			}
			if (beehive.GetHoneyLevel() <= 0)
			{
				return true;
			}
			float radius = Math.Min(50f, Math.Max(1f, Plugin._beehiveRadius.Value));
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)beehive).gameObject, radius);
			if (nearbyContainers.Count == 0)
			{
				return true;
			}
			while (beehive.GetHoneyLevel() > 0)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)__instance.m_honeyItem).gameObject).name);
				ZNetView.m_forceDisableInit = true;
				GameObject val = Object.Instantiate<GameObject>(itemPrefab);
				ZNetView.m_forceDisableInit = false;
				bool num = SpawnInsideContainers(val.GetComponent<ItemDrop>(), mustHaveItem: true);
				Object.Destroy((Object)(object)val);
				if (!num)
				{
					return true;
				}
			}
			if (beehive.GetHoneyLevel() == 0)
			{
				beehive.m_spawnEffect.Create(beehive.m_spawnPoint.position, Quaternion.identity, (Transform)null, 1f, -1);
			}
			return true;
			bool SpawnInsideContainers(ItemDrop item, bool mustHaveItem)
			{
				using (IEnumerator<Container> enumerator = (from item2 in nearbyContainers
					let inventory = item2.GetInventory()
					where (!mustHaveItem || inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) && inventory.AddItem(item.m_itemData)
					select item2).GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						Container current = enumerator.Current;
						beehive.m_nview.GetZDO().Set("level", beehive.GetHoneyLevel() - 1);
						current.Save();
						current.GetInventory().Changed();
						return true;
					}
				}
				if (mustHaveItem)
				{
					return SpawnInsideContainers(item, mustHaveItem: false);
				}
				return false;
			}
		}

		private static void DepositToContainers(ref Beehive __instance)
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			Beehive beehive = __instance;
			float radius = Math.Min(50f, Math.Max(1f, Plugin._beehiveRadius.Value));
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)beehive).gameObject, radius);
			if (beehive.GetHoneyLevel() != beehive.m_maxHoney)
			{
				return;
			}
			while (beehive.GetHoneyLevel() > 0)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)beehive.m_honeyItem).gameObject).name);
				ZNetView.m_forceDisableInit = true;
				GameObject val = Object.Instantiate<GameObject>(itemPrefab);
				ZNetView.m_forceDisableInit = false;
				bool num = SpawnInsideContainers(val.GetComponent<ItemDrop>(), mustHaveItem: true);
				Object.Destroy((Object)(object)val);
				if (!num)
				{
					return;
				}
			}
			if (beehive.GetHoneyLevel() == 0)
			{
				beehive.m_spawnEffect.Create(beehive.m_spawnPoint.position, Quaternion.identity, (Transform)null, 1f, -1);
			}
			bool SpawnInsideContainers(ItemDrop item, bool mustHaveItem)
			{
				using (IEnumerator<Container> enumerator = (from item2 in nearbyContainers
					let inventory = item2.GetInventory()
					where (!mustHaveItem || inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) && inventory.AddItem(item.m_itemData)
					select item2).GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						Container current = enumerator.Current;
						beehive.m_nview.GetZDO().Set("level", beehive.GetHoneyLevel() - 1);
						current.Save();
						current.GetInventory().Changed();
						return true;
					}
				}
				if (mustHaveItem)
				{
					return SpawnInsideContainers(item, mustHaveItem: false);
				}
				return false;
			}
		}
	}
	[HarmonyPatch]
	public class FermenterPatch
	{
		private static readonly MethodInfo _methodDepositToContainers = AccessTools.Method(typeof(FermenterPatch), "DepositToContainers", (Type[])null, (Type[])null);

		private static readonly MethodInfo _methodSetActive = AccessTools.Method(typeof(GameObject), "SetActive", (Type[])null, (Type[])null);

		private static readonly MethodInfo _methodTap = AccessTools.Method(typeof(FermenterPatch), "Tap", (Type[])null, (Type[])null);

		private static readonly MethodInfo _methodAddItemFromNearbyContainers = AccessTools.Method(typeof(FermenterPatch), "AddItemFromNearbyContainers", (Type[])null, (Type[])null);

		[HarmonyPatch(typeof(Fermenter), "DelayedTap")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> DelayedTapTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			if (Plugin._enableFermenter.Value == Toggle.Off || Plugin._fermenterAutomation.Value == Automation.Fuel)
			{
				return instructions;
			}
			List<CodeInstruction> list = instructions.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Brfalse)
				{
					int index = i;
					list.Insert(++i, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Insert(++i, new CodeInstruction(OpCodes.Ldloca, (object)0));
					list.Insert(++i, new CodeInstruction(OpCodes.Call, (object)_methodDepositToContainers));
					list.Insert(++i, new CodeInstruction(OpCodes.Brtrue, list[index].operand));
					return list.AsEnumerable();
				}
			}
			return instructions;
		}

		[HarmonyPatch(typeof(Fermenter), "SlowUpdate")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> SlowUpdateTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			if (Plugin._enableFermenter.Value == Toggle.Off)
			{
				return instructions;
			}
			List<CodeInstruction> list = instructions.ToList();
			int num = 0;
			bool flag = false;
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], _methodSetActive))
				{
					num++;
				}
				if (num == 3)
				{
					list.Insert(++i, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Insert(++i, new CodeInstruction(OpCodes.Call, (object)_methodAddItemFromNearbyContainers));
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return instructions;
			}
			flag = false;
			for (int num2 = list.Count - 1; num2 >= 0; num2--)
			{
				if (CodeInstructionExtensions.Calls(list[num2], _methodSetActive))
				{
					list.Insert(++num2, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Insert(++num2, new CodeInstruction(OpCodes.Call, (object)_methodTap));
					return list.AsEnumerable();
				}
			}
			return instructions;
		}

		private static bool DepositToContainers(Fermenter __instance, ref ItemConversion itemConversion)
		{
			float radius = Math.Min(50f, Math.Max(1f, Plugin._fermenterRadius.Value));
			bool flag = Plugin._fermenterIgnorePrivateAreaCheck.Value == Toggle.On;
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)__instance).gameObject, radius, !flag);
			int num = 0;
			for (int i = 0; i < itemConversion.m_producedItems; i++)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)itemConversion.m_to).gameObject).name);
				ZNetView.m_forceDisableInit = true;
				GameObject val = Object.Instantiate<GameObject>(itemPrefab);
				ZNetView.m_forceDisableInit = false;
				bool num2 = SpawnInsideContainers(val.GetComponent<ItemDrop>(), mustHaveItem: true);
				Object.Destroy((Object)(object)val);
				if (!num2)
				{
					ItemConversion obj = itemConversion;
					obj.m_producedItems -= num;
					return false;
				}
				num++;
			}
			return true;
			bool SpawnInsideContainers(ItemDrop item, bool mustHaveItem)
			{
				using (IEnumerator<Container> enumerator = (from item2 in nearbyContainers
					let inventory = item2.GetInventory()
					where (!mustHaveItem || inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) && inventory.AddItem(item.m_itemData)
					select item2).GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						Container current = enumerator.Current;
						current.Save();
						current.GetInventory().Changed();
						return true;
					}
				}
				if (mustHaveItem)
				{
					return SpawnInsideContainers(item, mustHaveItem: false);
				}
				return false;
			}
		}

		private static void Tap(Fermenter __instance)
		{
			if (Plugin._fermenterAutomation.Value == Automation.Deposit || Plugin._fermenterAutomation.Value == Automation.Both)
			{
				__instance.m_nview.InvokeRPC("Tap", Array.Empty<object>());
			}
		}

		private static void AddItemFromNearbyContainers(Fermenter __instance)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin._fermenterAutomation.Value == Automation.Deposit || (int)__instance.GetStatus() != 0 || !__instance.m_nview.IsOwner())
			{
				return;
			}
			Stopwatch gameObjectStopwatch = Helper.GetGameObjectStopwatch(((Component)__instance).gameObject);
			if (gameObjectStopwatch.IsRunning && gameObjectStopwatch.ElapsedMilliseconds <= 1000)
			{
				return;
			}
			float radius = Math.Min(50f, Math.Max(1f, Plugin._fermenterRadius.Value));
			bool flag = Plugin._fermenterIgnorePrivateAreaCheck.Value == Toggle.On;
			using (IEnumerator<ItemData> enumerator = (from container in Helper.GetNearbyContainers(((Component)__instance).gameObject, radius, !flag)
				let item = __instance.FindCookableItem(container.GetInventory())
				where item != null && Helper.DeductItemFromContainer(container, item) != 0
				select item).GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					ItemData current = enumerator.Current;
					__instance.m_nview.InvokeRPC("AddItem", new object[1] { ((Object)current.m_dropPrefab).name });
				}
			}
			gameObjectStopwatch.Restart();
		}
	}
	[HarmonyPatch]
	public class SapCollectorPatch
	{
		private static readonly MethodInfo _methodInfo = AccessTools.Method(typeof(SapCollectorPatch), "DepositToContainers", (Type[])null, (Type[])null);

		[HarmonyPatch(typeof(SapCollector), "UpdateTick")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			if (Plugin._enableSapCollector.Value == Toggle.Off)
			{
				return instructions;
			}
			List<CodeInstruction> list = instructions.ToList();
			int num = list.Count - 2;
			list.Insert(++num, new CodeInstruction(OpCodes.Ldarga, (object)0));
			list.Insert(++num, new CodeInstruction(OpCodes.Call, (object)_methodInfo));
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(SapCollector), "RPC_Extract")]
		[HarmonyPrefix]
		private static bool RpcExtract_Prefix(ref SapCollector __instance)
		{
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			SapCollector sapCollector = __instance;
			if (Plugin._enableSapCollector.Value == Toggle.Off || !sapCollector.m_nview.IsOwner())
			{
				return true;
			}
			if (sapCollector.GetLevel() <= 0)
			{
				return true;
			}
			float radius = Math.Min(50f, Math.Max(1f, Plugin._sapcollectorRadius.Value));
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)sapCollector).gameObject, radius);
			if (nearbyContainers.Count == 0)
			{
				return true;
			}
			while (sapCollector.GetLevel() > 0)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)__instance.m_spawnItem).gameObject).name);
				ZNetView.m_forceDisableInit = true;
				GameObject val = Object.Instantiate<GameObject>(itemPrefab);
				ZNetView.m_forceDisableInit = false;
				bool num = SpawnInsideContainer(val.GetComponent<ItemDrop>(), mustHaveItem: true);
				Object.Destroy((Object)(object)val);
				if (!num)
				{
					return true;
				}
			}
			if (sapCollector.GetLevel() == 0)
			{
				sapCollector.m_spawnEffect.Create(sapCollector.m_spawnPoint.position, Quaternion.identity, (Transform)null, 1f, -1);
			}
			return true;
			bool SpawnInsideContainer(ItemDrop item, bool mustHaveItem)
			{
				using (IEnumerator<Container> enumerator = (from container in nearbyContainers
					let inventory = container.GetInventory()
					where (!mustHaveItem || inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) && inventory.AddItem(item.m_itemData)
					select container).GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						Container current = enumerator.Current;
						sapCollector.m_nview.GetZDO().Set("level", sapCollector.GetLevel() - 1);
						current.Save();
						current.GetInventory().Changed();
						return true;
					}
				}
				if (mustHaveItem)
				{
					return SpawnInsideContainer(item, mustHaveItem: false);
				}
				return false;
			}
		}

		private static void DepositToContainers(ref SapCollector __instance)
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			SapCollector sapCollector = __instance;
			float radius = Math.Min(50f, Math.Max(1f, Plugin._sapcollectorRadius.Value));
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)sapCollector).gameObject, radius);
			if (sapCollector.GetLevel() != sapCollector.m_maxLevel)
			{
				return;
			}
			while (sapCollector.GetLevel() > 0)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)sapCollector.m_spawnItem).gameObject).name);
				ZNetView.m_forceDisableInit = true;
				GameObject val = Object.Instantiate<GameObject>(itemPrefab);
				ZNetView.m_forceDisableInit = false;
				bool num = SpawnInsideContainers(val.GetComponent<ItemDrop>(), mustHaveItem: true);
				Object.Destroy((Object)(object)val);
				if (!num)
				{
					return;
				}
			}
			if (sapCollector.GetLevel() == 0)
			{
				sapCollector.m_spawnEffect.Create(sapCollector.m_spawnPoint.position, Quaternion.identity, (Transform)null, 1f, -1);
			}
			bool SpawnInsideContainers(ItemDrop item, bool mustHaveItem)
			{
				using (IEnumerator<Container> enumerator = (from container in nearbyContainers
					let inventory = container.GetInventory()
					where (!mustHaveItem || inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) && inventory.AddItem(item.m_itemData)
					select container).GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						Container current = enumerator.Current;
						sapCollector.m_nview.GetZDO().Set("level", sapCollector.GetLevel() - 1);
						current.Save();
						current.GetInventory().Changed();
						return true;
					}
				}
				if (mustHaveItem)
				{
					return SpawnInsideContainers(item, mustHaveItem: false);
				}
				return false;
			}
		}
	}
	[HarmonyPatch]
	public class SmelterPatch
	{
		private static readonly MethodInfo _methodInfo = AccessTools.Method(typeof(SmelterPatch), "DontProcessAllWoods", (Type[])null, (Type[])null);

		[HarmonyPatch(typeof(Smelter), "FindCookableItem")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			if (Plugin._enableKiln.Value == Toggle.Off)
			{
				return instructions;
			}
			int num = -1;
			List<CodeInstruction> list = instructions.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Stloc_1)
				{
					list.Insert(++i, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Insert(++i, new CodeInstruction(OpCodes.Ldloc_1, (object)null));
					list.Insert(++i, new CodeInstruction(OpCodes.Call, (object)_methodInfo));
					num = i;
				}
				else if (num != -1 && list[i].opcode == OpCodes.Brfalse)
				{
					list.Insert(++num, new CodeInstruction(OpCodes.Brtrue, list[i].operand));
					return list.AsEnumerable();
				}
			}
			return instructions;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Smelter), "Awake")]
		private static void Awake_Prefix(ref Smelter __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//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_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			if (!(__instance.m_name != "$piece_blastfurnace") && Plugin._enableBlastFurnace.Value == Toggle.On && Plugin._blastfurnaceAllowAllOres.Value == Toggle.On)
			{
				__instance.m_conversion.AddRange(new List<ItemConversion>
				{
					new ItemConversion
					{
						m_from = ObjectDB.instance.GetItemPrefab("CopperOre").GetComponent<ItemDrop>(),
						m_to = ObjectDB.instance.GetItemPrefab("Copper").GetComponent<ItemDrop>()
					},
					new ItemConversion
					{
						m_from = ObjectDB.instance.GetItemPrefab("IronScrap").GetComponent<ItemDrop>(),
						m_to = ObjectDB.instance.GetItemPrefab("Iron").GetComponent<ItemDrop>()
					},
					new ItemConversion
					{
						m_from = ObjectDB.instance.GetItemPrefab("SilverOre").GetComponent<ItemDrop>(),
						m_to = ObjectDB.instance.GetItemPrefab("Silver").GetComponent<ItemDrop>()
					},
					new ItemConversion
					{
						m_from = ObjectDB.instance.GetItemPrefab("TinOre").GetComponent<ItemDrop>(),
						m_to = ObjectDB.instance.GetItemPrefab("Tin").GetComponent<ItemDrop>()
					}
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Smelter), "Spawn")]
		private static bool Spawn_Prefix(string ore, int stack, ref Smelter __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return false;
			}
			Smelter smelter = __instance;
			if (!smelter.m_nview.IsOwner())
			{
				return true;
			}
			switch (__instance.m_name)
			{
			case "$piece_charcoalkiln":
				if (Plugin._enableKiln.Value == Toggle.On && (Plugin._kilnAutomation.Value == Automation.Deposit || Plugin._kilnAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._kilnRadius.Value)), Plugin._kilnIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$piece_smelter":
				if (Plugin._enableSmelter.Value == Toggle.On && (Plugin._smelterAutomation.Value == Automation.Deposit || Plugin._smelterAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._smelterRadius.Value)), Plugin._smelterIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$piece_blastfurnace":
				if (Plugin._enableBlastFurnace.Value == Toggle.On && (Plugin._blastfurnaceAutomation.Value == Automation.Deposit || Plugin._blastfurnaceAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._blastfurnaceRadius.Value)), Plugin._blastfurnaceIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$piece_spinningwheel":
				if (Plugin._enableSpinningWheel.Value == Toggle.On && (Plugin._spinningwheelAutomation.Value == Automation.Deposit || Plugin._spinningwheelAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._spinningwheelRadius.Value)), Plugin._spinningwheelIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$piece_windmill":
				if (Plugin._enableWindmill.Value == Toggle.On && (Plugin._windmillAutomation.Value == Automation.Deposit || Plugin._windmillAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._windmillRadius.Value)), Plugin._windmillIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$piece_eitrrefinery":
				if (Plugin._enableEitrRefinery.Value == Toggle.On && (Plugin._eitrrefineryAutomation.Value == Automation.Deposit || Plugin._eitrrefineryAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._eitrrefineryRadius.Value)), Plugin._eitrrefineryIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$cws_stone_kiln":
				if (Plugin._enableSteelKiln.Value == Toggle.On && (Plugin._steelKilnAutomation.Value == Automation.Deposit || Plugin._steelKilnAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._steelKilnRadius.Value)), Plugin._steelKilnIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			case "$cws_slack_tub":
				if (Plugin._enableSteelSlackTub.Value == Toggle.On && (Plugin._steelSlackTubAutomation.Value == Automation.Deposit || Plugin._steelSlackTubAutomation.Value == Automation.Both))
				{
					return Spawn(Math.Min(50f, Math.Max(1f, Plugin._steelSlackTubRadius.Value)), Plugin._steelSlackTubIgnorePrivateAreaCheck.Value == Toggle.On);
				}
				break;
			}
			return true;
			bool Spawn(float depositRadius, bool ignorePrivateAreaCheck)
			{
				List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)smelter).gameObject, depositRadius, !ignorePrivateAreaCheck);
				ItemDrop itemDrop;
				if (nearbyContainers.Count != 0)
				{
					float num = ((depositRadius > 50f) ? 50f : ((!(depositRadius < 1f)) ? depositRadius : 1f));
					depositRadius = num;
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)smelter.GetItemConversion(ore).m_to).gameObject).name);
					ZNetView.m_forceDisableInit = true;
					GameObject val = Object.Instantiate<GameObject>(itemPrefab);
					ZNetView.m_forceDisableInit = false;
					itemDrop = val.GetComponent<ItemDrop>();
					itemDrop.m_itemData.m_stack = stack;
					bool result = SpawnInsideContainer(mustHaveItem: true);
					Object.Destroy((Object)(object)val);
					return result;
				}
				return true;
				bool SpawnInsideContainer(bool mustHaveItem)
				{
					//IL_006c: 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)
					foreach (Container item in nearbyContainers)
					{
						Inventory inventory = item.GetInventory();
						if ((!mustHaveItem || inventory.HaveItem(itemDrop.m_itemData.m_shared.m_name, true)) && inventory.AddItem(itemDrop.m_itemData))
						{
							Transform transform = ((Component)smelter).transform;
							smelter.m_produceEffects.Create(transform.position, transform.rotation, (Transform)null, 1f, -1);
							item.Save();
							item.GetInventory().Changed();
							return false;
						}
					}
					if (mustHaveItem)
					{
						return SpawnInsideContainer(mustHaveItem: false);
					}
					return true;
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Smelter), "UpdateSmelter")]
		private static void UpdateSmelter_Prefix(Smelter __instance)
		{
			if ((Object)(object)__instance == (Object)null || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || (Object)(object)__instance.m_nview == (Object)null || !__instance.m_nview.IsOwner())
			{
				return;
			}
			Stopwatch gameObjectStopwatch = Helper.GetGameObjectStopwatch(((Component)__instance).gameObject);
			if (gameObjectStopwatch.IsRunning && gameObjectStopwatch.ElapsedMilliseconds < 1000)
			{
				return;
			}
			gameObjectStopwatch.Restart();
			float val = 0f;
			bool flag = false;
			bool flag2 = false;
			switch (__instance.m_name)
			{
			case "$piece_charcoalkiln":
				if (Plugin._enableKiln.Value == Toggle.Off || Plugin._kilnAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._kilnRadius.Value;
				flag = Plugin._kilnIgnorePrivateAreaCheck.Value == Toggle.On;
				flag2 = true;
				break;
			case "$piece_smelter":
				if (Plugin._enableSmelter.Value == Toggle.Off || Plugin._smelterAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._smelterRadius.Value;
				flag = Plugin._smelterIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$piece_blastfurnace":
				if (Plugin._enableBlastFurnace.Value == Toggle.Off || Plugin._blastfurnaceAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._blastfurnaceRadius.Value;
				flag = Plugin._blastfurnaceIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$piece_spinningwheel":
				if (Plugin._enableSpinningWheel.Value == Toggle.Off || Plugin._spinningwheelAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._spinningwheelRadius.Value;
				flag = Plugin._spinningwheelIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$piece_windmill":
				if (Plugin._enableWindmill.Value == Toggle.Off || Plugin._windmillAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._windmillRadius.Value;
				flag = Plugin._windmillIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$piece_eitrrefinery":
				if (Plugin._enableEitrRefinery.Value == Toggle.Off || Plugin._eitrrefineryAutomation.Value == Automation.Deposit)
				{
					return;
				}
				val = Plugin._eitrrefineryRadius.Value;
				flag = Plugin._eitrrefineryIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$cws_stone_kiln":
				if (Plugin._enableSteelKiln.Value == Toggle.Off || Plugin._steelKilnAutomation.Value == Automation.Deposit || !Plugin._hasOdinSteelWorks)
				{
					return;
				}
				val = Plugin._steelKilnRadius.Value;
				flag = Plugin._steelKilnIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			case "$cws_slack_tub":
				if (Plugin._enableSteelSlackTub.Value == Toggle.Off || Plugin._steelSlackTubAutomation.Value == Automation.Deposit || !Plugin._hasOdinSteelWorks)
				{
					return;
				}
				val = Plugin._steelSlackTubRadius.Value;
				flag = Plugin._steelSlackTubIgnorePrivateAreaCheck.Value == Toggle.On;
				break;
			}
			val = Math.Min(50f, Math.Max(1f, val));
			int num = __instance.m_maxOre - __instance.GetQueueSize();
			int num2 = __instance.m_maxFuel - (int)Math.Ceiling(__instance.GetFuel());
			if (Object.op_Implicit((Object)(object)__instance.m_fuelItem) && num2 > 0)
			{
				ItemData itemData = __instance.m_fuelItem.m_itemData;
				int num3 = Helper.DeductItemFromAllNearbyContainers(((Component)__instance).gameObject, val, itemData, 1, !flag);
				for (int i = 0; i < num3; i++)
				{
					__instance.m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
				}
			}
			if (num <= 0)
			{
				return;
			}
			List<Container> nearbyContainers = Helper.GetNearbyContainers(((Component)__instance).gameObject, val);
			foreach (Container item in nearbyContainers)
			{
				foreach (ItemConversion item2 in __instance.m_conversion)
				{
					if (flag2)
					{
						bool flag3 = Plugin._kilnProcessAllWoods.Value == Toggle.Off;
						if (flag3)
						{
							string name = item2.m_from.m_itemData.m_shared.m_name;
							bool flag4 = ((name == "$item_finewood" || name == "$item_roundlog") ? true : false);
							flag3 = flag4;
						}
						if (flag3)
						{
							continue;
						}
						int num4 = ((Plugin._kilnProductThreshold.Value >= 0) ? Plugin._kilnProductThreshold.Value : 0);
						if (num4 > 0 && Helper.GetItemAmounts(Helper.GetNearbyItemsFromContainers(nearbyContainers), item2.m_to.m_itemData) >= num4)
						{
							return;
						}
					}
					ItemData itemData2 = item2.m_from.m_itemData;
					int num5 = Helper.DeductItemFromContainer(item, itemData2);
					if (num5 > 0)
					{
						GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)item2.m_from).gameObject).name);
						for (int j = 0; j < num5; j++)
						{
							__instance.m_nview.InvokeRPC("AddOre", new object[1] { ((Object)itemPrefab).name });
						}
						num -= num5;
						if (num == 0)
						{
							return;
						}
					}
				}
			}
		}

		private static bool DontProcessAllWoods(Smelter smelter, ItemConversion itemConversion)
		{
			bool flag = smelter.m_name == "$piece_charcoalkiln" && Plugin._kilnProcessAllWoods.Value == Toggle.Off;
			if (flag)
			{
				string name = itemConversion.m_from.m_itemData.m_shared.m_name;
				bool flag2 = ((name == "$item_finewood" || name == "$item_roundlog") ? true : false);
				flag = flag2;
			}
			return flag;
		}
	}
}
namespace LazyVikings.Functions
{
	public enum Automation
	{
		Deposit,
		Fuel,
		Both
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	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]
	[Microsoft.CodeAnalysis.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;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }));
							}).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{