Decompiled source of RapidLoadouts v1.0.4

RapidLoadouts.dll

Decompiled 6 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using RapidLoadouts;
using RapidLoadouts.UI;
using RapidLoadouts.YAMLStuff;
using ServerSync;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: AssemblyFileVersion("1.0.4")]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("RapidLoadouts")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("RapidLoadouts")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.4.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<1a6f2a3a-effd-4b15-85e0-b1198506355f>Embedded]
	internal sealed class <1a6f2a3a-effd-4b15-85e0-b1198506355f>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<1a6f2a3a-effd-4b15-85e0-b1198506355f>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <056847de-81f4-4335-9b65-6e0b5bd4ae59>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <056847de-81f4-4335-9b65-6e0b5bd4ae59>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <056847de-81f4-4335-9b65-6e0b5bd4ae59>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<1a6f2a3a-effd-4b15-85e0-b1198506355f>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Recycle_N_Reclaim.GamePatches
{
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("RapidLoadouts_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_Recycle_N_Reclaim_Version);
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("1.0.4");
			val.Write(RpcHandlers.ComputeHashForMod().Replace("-", ""));
			peer.m_rpc.Invoke("RapidLoadouts_VersionCheck", new object[1] { val });
		}
	}
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	public static class VerifyClient
	{
		private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance)
		{
			if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc))
			{
				return true;
			}
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting"));
			rpc.Invoke("Error", new object[1] { 3 });
			return false;
		}

		private static void Postfix(ZNet __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RapidLoadouts_RequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	public class ShowConnectionError
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
		private static void Postfix(FejdStartup __instance)
		{
			if (__instance.m_connectionFailedPanel.activeSelf)
			{
				__instance.m_connectionFailedError.fontSizeMax = 25f;
				__instance.m_connectionFailedError.fontSizeMin = 15f;
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + RapidLoadoutsPlugin.ConnectionError;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"));
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_Recycle_N_Reclaim_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = ComputeHashForMod().Replace("-", "");
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogInfo((object)("Hash/Version check, local: 1.0.4 " + text3 + " remote: " + text + " " + text2));
			if (text2 != text3 || text != "1.0.4")
			{
				RapidLoadoutsPlugin.ConnectionError = "RapidLoadouts Installed: 1.0.4 " + text3 + "\n Needed: " + text + " " + text2;
				if (ZNet.instance.IsServer())
				{
					RapidLoadoutsPlugin.RapidLoadoutsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting..."));
					rpc.Invoke("Error", new object[1] { 3 });
				}
			}
			else if (!ZNet.instance.IsServer())
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogInfo((object)"Received same version from server!");
			}
			else
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"));
				ValidatedPeers.Add(rpc);
			}
		}

		public static string ComputeHashForMod()
		{
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(File.ReadAllBytes(Assembly.GetExecutingAssembly().Location));
			StringBuilder stringBuilder = new StringBuilder();
			byte[] array2 = array;
			foreach (byte b in array2)
			{
				stringBuilder.Append(b.ToString("X2"));
			}
			return stringBuilder.ToString();
		}
	}
}
namespace RapidLoadouts
{
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	[PublicAPI]
	public class Localizer
	{
		private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors;

		private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts;

		private static readonly ConditionalWeakTable<Localization, string> localizationLanguage;

		private static readonly List<WeakReference<Localization>> localizationObjects;

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static readonly List<string> fileExtensions;

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Expected O, but got Unknown
				if (_plugin == null)
				{
					IEnumerable<TypeInfo> source;
					try
					{
						source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = from t in ex.Types
							where t != null
							select t.GetTypeInfo();
					}
					_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				}
				return _plugin;
			}
		}

		private static void UpdatePlaceholderText(Localization localization, string key)
		{
			localizationLanguage.TryGetValue(localization, out var value);
			string text = loadedTexts[value][key];
			if (PlaceholderProcessors.TryGetValue(key, out var value2))
			{
				text = value2.Aggregate(text, [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (string current, KeyValuePair<string, Func<string>> kv) => current.Replace("{" + kv.Key + "}", kv.Value()));
			}
			localization.AddWord(key, text);
		}

		public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, [<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(new byte[] { 2, 1, 1 })] Func<T, string> convertConfigValue = null)
		{
			if (convertConfigValue == null)
			{
				convertConfigValue = [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] [return: <056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(1)] (T val) => val.ToString();
			}
			if (!PlaceholderProcessors.ContainsKey(key))
			{
				PlaceholderProcessors[key] = new Dictionary<string, Func<string>>();
			}
			config.SettingChanged += [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (object _, EventArgs _) =>
			{
				UpdatePlaceholder();
			};
			if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage()))
			{
				UpdatePlaceholder();
			}
			void UpdatePlaceholder()
			{
				PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value);
				UpdatePlaceholderText(Localization.instance, key);
			}
		}

		public static void AddText(string key, string text)
		{
			List<WeakReference<Localization>> list = new List<WeakReference<Localization>>();
			foreach (WeakReference<Localization> localizationObject in localizationObjects)
			{
				if (localizationObject.TryGetTarget(out var target))
				{
					Dictionary<string, string> dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)];
					if (!target.m_translations.ContainsKey(key))
					{
						dictionary[key] = text;
						target.AddWord(key, text);
					}
				}
				else
				{
					list.Add(localizationObject);
				}
			}
			foreach (WeakReference<Localization> item in list)
			{
				localizationObjects.Remove(item);
			}
		}

		public static void Load()
		{
			LoadLocalization(Localization.instance, Localization.instance.GetSelectedLanguage());
		}

		private static void LoadLocalization(Localization __instance, string language)
		{
			if (!localizationLanguage.Remove(__instance))
			{
				localizationObjects.Add(new WeakReference<Localization>(__instance));
			}
			localizationLanguage.Add(__instance, language);
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories)
				where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0
				select f)
			{
				string text = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' })[1];
				if (dictionary.ContainsKey(text))
				{
					Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped."));
				}
				else
				{
					dictionary[text] = item;
				}
			}
			byte[] array = LoadTranslationFromAssembly("English");
			if (array == null)
			{
				throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml.");
			}
			Dictionary<string, string> dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(Encoding.UTF8.GetString(array));
			if (dictionary2 == null)
			{
				throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty.");
			}
			string text2 = null;
			if (language != "English")
			{
				if (dictionary.ContainsKey(language))
				{
					text2 = File.ReadAllText(dictionary[language]);
				}
				else
				{
					byte[] array2 = LoadTranslationFromAssembly(language);
					if (array2 != null)
					{
						text2 = Encoding.UTF8.GetString(array2);
					}
				}
			}
			if (text2 == null && dictionary.ContainsKey("English"))
			{
				text2 = File.ReadAllText(dictionary["English"]);
			}
			if (text2 != null)
			{
				foreach (KeyValuePair<string, string> item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(text2) ?? new Dictionary<string, string>())
				{
					dictionary2[item2.Key] = item2.Value;
				}
			}
			loadedTexts[language] = dictionary2;
			foreach (KeyValuePair<string, string> item3 in dictionary2)
			{
				UpdatePlaceholderText(__instance, item3.Key);
			}
		}

		static Localizer()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			PlaceholderProcessors = new Dictionary<string, Dictionary<string, Func<string>>>();
			loadedTexts = new Dictionary<string, Dictionary<string, string>>();
			localizationLanguage = new ConditionalWeakTable<Localization, string>();
			localizationObjects = new List<WeakReference<Localization>>();
			fileExtensions = new List<string> { ".json", ".yml" };
			new Harmony("org.bepinex.helpers.LocalizationManager").Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		[return: <056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		private static byte[] LoadTranslationFromAssembly(string language)
		{
			foreach (string fileExtension in fileExtensions)
			{
				byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension);
				if (array != null)
				{
					return array;
				}
			}
			return null;
		}

		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(2)]
		public static byte[] ReadEmbeddedFileBytes([<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(1)] string resourceFileName, Assembly containingAssembly = null)
		{
			using MemoryStream memoryStream = new MemoryStream();
			if ((object)containingAssembly == null)
			{
				containingAssembly = Assembly.GetCallingAssembly();
			}
			string text = containingAssembly.GetManifestResourceNames().FirstOrDefault([<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal));
			if (text != null)
			{
				containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream);
			}
			return (memoryStream.Length == 0L) ? null : memoryStream.ToArray();
		}
	}
	[BepInPlugin("Azumatt.RapidLoadouts", "RapidLoadouts", "1.0.4")]
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public class RapidLoadoutsPlugin : BaseUnityPlugin
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)]
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			public bool? Browsable = false;
		}

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
		private class AcceptableShortcuts : AcceptableValueBase
		{
			public AcceptableShortcuts()
				: base(typeof(KeyboardShortcut))
			{
			}

			public override object Clamp(object value)
			{
				return value;
			}

			public override bool IsValid(object value)
			{
				return true;
			}

			public override string ToDescriptionString()
			{
				return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes);
			}
		}

		internal const string ModName = "RapidLoadouts";

		internal const string ModVersion = "1.0.4";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.RapidLoadouts";

		private static string ConfigFileName = "Azumatt.RapidLoadouts.cfg";

		private static string ConfigFileFullPath;

		public static bool HasAuga;

		internal static string ConnectionError;

		private readonly Harmony _harmony = new Harmony("Azumatt.RapidLoadouts");

		private ItemSetsButtonHolder _itemSetsButton;

		public static readonly ManualLogSource RapidLoadoutsLogger;

		private static readonly ConfigSync ConfigSync;

		internal static readonly string yamlFileName;

		internal static readonly string yamlPath;

		internal static readonly CustomSyncedValue<string> AzuRL_yamlData;

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(new byte[] { 1, 2 })]
		internal static List<ItemSet> RL_yamlData;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		public static ConfigEntry<string> itemSetCostPrefab;

		public static ConfigEntry<Vector3> InventoryItemSetButtonPosition;

		public static ConfigEntry<Vector3> ItemSetWindow;

		public void Awake()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			Localizer.Load();
			_serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			itemSetCostPrefab = config("1 - General", "ItemSetCostPrefab", "Coins", "Default Currency. This is the fallback currency that will be used when buying ItemSets from the ItemSet Window.");
			InventoryItemSetButtonPosition = config<Vector3>("2 - UI", "ItemSetButtonPosition", new Vector3(63f, -316f, -1f), "The last saved ItemSet Button's screen position.");
			ItemSetWindow = config<Vector3>("2 - UI", "ItemSetWindow", new Vector3(428f, -276f, -1f), "The last saved ItemSet Window's screen position.");
			if (!File.Exists(yamlPath))
			{
				YAMLUtils.WriteConfigFileFromResource(yamlPath);
			}
			AzuRL_yamlData.ValueChanged += OnValChangedUpdate;
			AzuRL_yamlData.AssignLocalValue(File.ReadAllText(yamlPath));
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void Start()
		{
			_itemSetsButton = ((Component)this).gameObject.AddComponent<ItemSetsButtonHolder>();
			if (Chainloader.PluginInfos.ContainsKey("randyknapp.mods.auga"))
			{
				HasAuga = true;
			}
		}

		public static string SanitizeFileName(string fileName)
		{
			return Path.GetInvalidFileNameChars().Aggregate(fileName, [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (string current, char c) => current.Replace(c.ToString(), string.Empty));
		}

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

		private void AutoDoc()
		{
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
			FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, yamlFileName);
			fileSystemWatcher2.Changed += ReadYamlFiles;
			fileSystemWatcher2.Created += ReadYamlFiles;
			fileSystemWatcher2.Renamed += ReadYamlFiles;
			fileSystemWatcher2.IncludeSubdirectories = true;
			fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher2.EnableRaisingEvents = true;
		}

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

		private void ReadYamlFiles(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(yamlPath))
			{
				return;
			}
			try
			{
				RapidLoadoutsLogger.LogDebug((object)"ReadConfigValues called");
				AzuRL_yamlData.AssignLocalValue(File.ReadAllText(yamlPath));
			}
			catch
			{
				RapidLoadoutsLogger.LogError((object)("There was an issue loading your " + yamlFileName));
				RapidLoadoutsLogger.LogError((object)"Please check your entries for spelling and format!");
			}
		}

		private static void OnValChangedUpdate()
		{
			RapidLoadoutsLogger.LogDebug((object)"OnValChanged called");
			try
			{
				YAMLUtils.ReadYaml(AzuRL_yamlData.Value);
				ItemSetHelper.AddCreateItemSets(((Object)(object)ItemSets.instance != (Object)null) ? ItemSets.instance : null);
				if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)ItemSets.instance != (Object)null)
				{
					ItemSetGui.FillList();
				}
			}
			catch (Exception arg)
			{
				RapidLoadoutsLogger.LogError((object)$"Failed to deserialize {yamlFileName}: {arg}");
			}
		}

		private ConfigEntry<T> config<[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = 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 + (synchronizedSetting ? " [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 = synchronizedSetting;
			return val2;
		}

		private ConfigEntry<T> config<[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		static RapidLoadoutsPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			RapidLoadoutsLogger = Logger.CreateLogSource("RapidLoadouts");
			ConfigSync = new ConfigSync("Azumatt.RapidLoadouts")
			{
				DisplayName = "RapidLoadouts",
				CurrentVersion = "1.0.4",
				MinimumRequiredVersion = "1.0.4"
			};
			yamlFileName = SanitizeFileName("Azumatt.RapidLoadouts_ItemSets.yml");
			string configPath2 = Paths.ConfigPath;
			directorySeparatorChar = Path.DirectorySeparatorChar;
			yamlPath = configPath2 + directorySeparatorChar + yamlFileName;
			AzuRL_yamlData = new CustomSyncedValue<string>(ConfigSync, "AzuRL_yamlData", "");
			RL_yamlData = new List<ItemSet>();
			_serverConfigLocked = null;
			itemSetCostPrefab = null;
			InventoryItemSetButtonPosition = null;
			ItemSetWindow = null;
		}
	}
}
namespace RapidLoadouts.YAMLStuff
{
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	public static class ItemSetHelper
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(2)]
		public static void AddCreateItemSets(ItemSets __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Dictionary<string, ItemSet> dictionary = ConvertToGameItemSets(RapidLoadoutsPlugin.RL_yamlData).ToDictionary([<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (ItemSet set) => set.m_name, [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)] (ItemSet set) => set);
			for (int i = 0; i < __instance.m_sets.Count; i++)
			{
				ItemSet val = __instance.m_sets[i];
				if (dictionary.ContainsKey(val.m_name))
				{
					__instance.m_sets[i] = dictionary[val.m_name];
					dictionary.Remove(val.m_name);
				}
			}
			__instance.m_sets.AddRange(dictionary.Values);
		}

		public static List<ItemSet> ConvertToGameItemSets([<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(new byte[] { 1, 2 })] List<ItemSet> customItemSets)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			List<ItemSet> list = new List<ItemSet>();
			foreach (ItemSet customItemSet in customItemSets)
			{
				if (customItemSet == null)
				{
					continue;
				}
				ItemSet val = new ItemSet
				{
					m_name = RegexUtilities.TrimInvalidCharacters(customItemSet.m_name),
					m_items = new List<SetItem>(),
					m_skills = new List<SetSkill>()
				};
				foreach (SetItem item3 in customItemSet.m_items)
				{
					SetItem item = new SetItem
					{
						m_item = ConvertToItemDrop(item3.m_item),
						m_quality = item3.m_quality,
						m_stack = item3.m_stack,
						m_use = item3.m_use,
						m_hotbarSlot = item3.m_hotbarSlot
					};
					val.m_items.Add(item);
				}
				foreach (SetSkill skill in customItemSet.m_skills)
				{
					SetSkill item2 = new SetSkill
					{
						m_skill = ConvertToSkillType(skill.m_skill),
						m_level = skill.m_level
					};
					val.m_skills.Add(item2);
				}
				list.Add(val);
			}
			return list;
		}

		[return: <056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		internal static ItemDrop ConvertToItemDrop(string itemName)
		{
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemName);
			if ((Object)(object)itemPrefab != (Object)null)
			{
				return itemPrefab.GetComponent<ItemDrop>();
			}
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)("ItemSetHelper.ConvertToItemDrop: Prefab for " + itemName + " not found in the ObjectDB! Can't convert to ItemDrop!"));
			return null;
		}

		internal static SkillType ConvertToSkillType(string skillName)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (Enum.TryParse<SkillType>(skillName, ignoreCase: true, out SkillType result))
			{
				return result;
			}
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)("ItemSetHelper.ConvertToSkillType: " + skillName + " is not a valid skill name or isn't a vanilla skill! Can't convert to Skills.SkillType!"));
			return (SkillType)0;
		}

		public static bool TryGetSet(string name, bool dropCurrentItems = false)
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null || !ItemSets.instance.GetSetDictionary().TryGetValue(name, out var value))
			{
				return false;
			}
			if (dropCurrentItems)
			{
				DropCurrentItems();
			}
			PopulateInventoryWithSetItems(value);
			ResetAndRaiseSkills(value);
			return true;
		}

		private static void DropCurrentItems()
		{
			Skills skills = ((Character)Player.m_localPlayer).GetSkills();
			Player.m_localPlayer.CreateTombStone();
			Player.m_localPlayer.ClearFood();
			Player.m_localPlayer.ClearHardDeath();
			((Character)Player.m_localPlayer).GetSEMan().RemoveAllStatusEffects(false);
			foreach (SkillDef skill in skills.m_skills)
			{
				skills.CheatResetSkill(((object)(SkillType)(ref skill.m_skill)).ToString());
			}
		}

		private static void PopulateInventoryWithSetItems(ItemSet itemSet)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
			InventoryGui.instance.m_playerGrid.UpdateInventory(inventory, Player.m_localPlayer, (ItemData)null);
			foreach (SetItem item in itemSet.m_items)
			{
				if ((Object)(object)item.m_item == (Object)null || (item.m_item.m_itemData.m_shared.m_dlc.Length > 0 && !DLCMan.instance.IsDLCInstalled(item.m_item.m_itemData.m_shared.m_dlc)))
				{
					continue;
				}
				int num = Math.Max(1, item.m_stack);
				ItemData val = inventory.AddItem(((Object)((Component)item.m_item).gameObject).name, num, Math.Max(1, item.m_quality), 0, 0L, "Thor", false);
				if (val != null)
				{
					if (item.m_use)
					{
						((Humanoid)Player.m_localPlayer).UseItem(inventory, val, false);
					}
					if (item.m_hotbarSlot > 0)
					{
						InventoryGui.instance.m_playerGrid.DropItem(inventory, val, num, new Vector2i(item.m_hotbarSlot - 1, 0));
					}
				}
			}
		}

		internal static void SetAnyGuardianPower(string setEffect)
		{
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)("Setting effect to " + setEffect));
			Player.m_localPlayer.SetGuardianPower(setEffect);
			Player.m_localPlayer.m_guardianPowerCooldown = 0f;
		}

		private static void ResetAndRaiseSkills(ItemSet itemSet)
		{
			Skills skills = ((Character)Player.m_localPlayer).GetSkills();
			foreach (SetSkill skill in itemSet.m_skills)
			{
				skills.CheatResetSkill(((object)(SkillType)(ref skill.m_skill)).ToString());
				((Character)Player.m_localPlayer).GetSkills().CheatRaiseSkill(((object)(SkillType)(ref skill.m_skill)).ToString(), (float)skill.m_level, true);
			}
		}

		public static string Repeat(string value, int count)
		{
			return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
		}
	}
	[Serializable]
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public class ItemSet
	{
		[YamlMember(Alias = "name")]
		public string m_name;

		[YamlMember(Alias = "items")]
		public List<SetItem> m_items = new List<SetItem>();

		[YamlMember(Alias = "skills")]
		public List<SetSkill> m_skills = new List<SetSkill>();

		[YamlMember(Alias = "dropCurrent")]
		public bool m_dropCurrent;

		[YamlMember(Alias = "price")]
		public int m_price;

		[YamlMember(Alias = "costPrefab")]
		public string m_prefabCost;

		[YamlMember(Alias = "setEffect")]
		public string m_setEffect;

		[YamlMember(Alias = "setEffectAsGP")]
		public bool m_setEffectAsGP;
	}
	[Serializable]
	public class SetItem
	{
		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(1)]
		[YamlMember(Alias = "item")]
		public string m_item;

		[YamlMember(Alias = "quality")]
		public int m_quality = 1;

		[YamlMember(Alias = "stack")]
		public int m_stack = 1;

		[YamlMember(Alias = "use")]
		public bool m_use = true;

		[YamlMember(Alias = "hotbarSlot")]
		public int m_hotbarSlot;
	}
	[Serializable]
	public class SetSkill
	{
		[YamlMember(Alias = "skill")]
		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(1)]
		public string m_skill;

		[YamlMember(Alias = "level")]
		public int m_level;
	}
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public class YAMLUtils
	{
		internal static void WriteConfigFileFromResource(string configFilePath)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text = "RapidLoadouts.YAMLStuff.Example.yml";
			using Stream stream = executingAssembly.GetManifestResourceStream(text);
			if (stream == null)
			{
				throw new FileNotFoundException("Resource '" + text + "' not found in the assembly.");
			}
			using StreamReader streamReader = new StreamReader(stream);
			string contents = streamReader.ReadToEnd();
			File.WriteAllText(configFilePath, contents);
		}

		internal static void ReadYaml(string yamlInput)
		{
			RapidLoadoutsPlugin.RL_yamlData = new DeserializerBuilder().Build().Deserialize<List<ItemSet>>(yamlInput);
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)("yamlData:\n" + yamlInput));
		}

		internal void LoadCustomItemSets()
		{
			if (!File.Exists(RapidLoadoutsPlugin.yamlPath))
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogWarning((object)("Could not find " + RapidLoadoutsPlugin.yamlFileName + " at " + RapidLoadoutsPlugin.yamlPath));
				return;
			}
			try
			{
				new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).Build().Deserialize<List<ItemSet>>(File.ReadAllText(RapidLoadoutsPlugin.yamlPath));
			}
			catch (Exception ex)
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)("Failed to load custom item sets: " + ex.Message));
			}
		}
	}
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public static class RegexUtilities
	{
		private static readonly Regex AlphanumericRegex = new Regex("[^a-zA-Z0-9]", RegexOptions.Compiled);

		public static string TrimInvalidCharacters(string input)
		{
			return AlphanumericRegex.Replace(input, string.Empty);
		}
	}
}
namespace RapidLoadouts.UI
{
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public class ItemSetsButtonHolder : MonoBehaviour
	{
		private Button _itemSetsButton;

		private TMP_Text _textComponent;

		private void Start()
		{
			((MonoBehaviour)this).InvokeRepeating("EnsureRecyclingButtonExistsIfPossible", 0f, 5f);
		}

		public void EnsureRecyclingButtonExistsIfPossible()
		{
			if (!((Object)(object)InventoryGui.instance == (Object)null))
			{
				if ((Object)(object)_itemSetsButton == (Object)null)
				{
					SetupButton();
				}
				Button itemSetsButton = _itemSetsButton;
				if (itemSetsButton != null)
				{
					((Component)itemSetsButton).gameObject.SetActive(true);
				}
			}
		}

		private void OnDestroy()
		{
			try
			{
				Object.Destroy((Object)(object)((Component)_itemSetsButton).gameObject);
			}
			catch
			{
			}
		}

		private void SetupButton()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			if (!((Object)(object)_itemSetsButton != (Object)null))
			{
				if (RapidLoadoutsPlugin.HasAuga)
				{
					_itemSetsButton = Object.Instantiate<Button>(((Component)((Transform)InventoryGui.instance.m_container).Find("TakeAll")).GetComponent<Button>(), ((Component)InventoryGui.instance.m_player).transform);
				}
				else
				{
					_itemSetsButton = Object.Instantiate<Button>(InventoryGui.instance.m_takeAllButton, ((Component)InventoryGui.instance.m_player).transform);
				}
				((Component)_itemSetsButton).transform.SetParent(((Component)InventoryGui.instance.m_player).transform);
				((Object)_itemSetsButton).name = "ItemSetsButton";
				Vector3 savedButtonPosition = GetSavedButtonPosition();
				((Component)_itemSetsButton).transform.localPosition = savedButtonPosition;
				_itemSetsButton.onClick = new ButtonClickedEvent();
				((UnityEvent)_itemSetsButton.onClick).AddListener(new UnityAction(ItemSetGui.ToggleUI));
				_textComponent = ((Component)_itemSetsButton).GetComponentInChildren<TMP_Text>();
				_textComponent.text = Localization.instance.Localize("$azu_rl_itemSets");
				((Component)_itemSetsButton).gameObject.AddComponent<UIDragger>().OnUIDropped += delegate(object source, Vector3 position)
				{
					//IL_0005: Unknown result type (might be due to invalid IL or missing references)
					RapidLoadoutsPlugin.InventoryItemSetButtonPosition.Value = position;
				};
			}
		}

		private Vector3 GetSavedButtonPosition()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return RapidLoadoutsPlugin.InventoryItemSetButtonPosition.Value;
		}
	}
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	public class ItemSetGui : MonoBehaviour
	{
		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		public static ItemSetGui m_instance = null;

		public static GameObject m_rootPanel = null;

		public Button m_chooseButton;

		public Button m_sellButton;

		public static RectTransform m_listRoot = null;

		public static GameObject m_listElement = null;

		public Scrollbar m_listScroll;

		public static ScrollRectEnsureVisible m_itemEnsureVisible = null;

		public TMP_Text m_coinText;

		public Image m_coinIcon;

		public TMP_Text m_topicText;

		public EffectList m_buyEffects = new EffectList();

		public EffectList m_sellEffects = new EffectList();

		public float m_hideDistance = 5f;

		public static float m_itemSpacing = 64f;

		public static ItemDrop m_coinPrefab = null;

		public static List<GameObject> m_itemList = new List<GameObject>();

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		public static ItemSet m_selectedItem;

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		public static Player m_LocalPlayerRef;

		public static float m_itemlistBaseSize;

		public List<ItemData> m_tempItems = new List<ItemData>();

		public static bool PanelActive;

		[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(2)]
		public static ItemSetGui instance
		{
			[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(2)]
			get
			{
				return m_instance;
			}
		}

		public void Awake()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			m_instance = this;
			if ((Object)(object)m_rootPanel != (Object)null)
			{
				m_rootPanel.SetActive(false);
			}
			if ((Object)(object)m_listRoot != (Object)null)
			{
				Rect rect = m_listRoot.rect;
				m_itemlistBaseSize = ((Rect)(ref rect)).height;
			}
			m_chooseButton.onClick = new ButtonClickedEvent();
			((UnityEvent)m_chooseButton.onClick).AddListener(new UnityAction(OnChooseItemSet));
			m_sellButton.onClick = new ButtonClickedEvent();
			m_topicText.text = Localization.instance.Localize("$azu_rl_itemSets");
		}

		public void OnDestroy()
		{
			if ((Object)(object)m_instance == (Object)(object)this)
			{
				m_instance = null;
			}
		}

		private void Update()
		{
			if (m_rootPanel.activeSelf && PanelActive)
			{
				if (ShouldHide() || ShouldClose())
				{
					Hide();
				}
				else
				{
					UpdateUI();
				}
			}
		}

		private bool ShouldHide()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || ((Character)localPlayer).InCutscene())
			{
				return true;
			}
			if (!InventoryGui.IsVisible() || Minimap.IsOpen())
			{
				return true;
			}
			return false;
		}

		private static bool ShouldClose()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || Menu.IsVisible() || ((Object)(object)TextViewer.instance != (Object)null && TextViewer.instance.IsVisible()) || ((Character)localPlayer).InCutscene()) && (ZInput.GetButtonDown("JoyButtonB") || Input.GetKeyDown((KeyCode)27) || ZInput.GetButtonDown("Use")))
			{
				ZInput.ResetButtonStatus("JoyButtonB");
				return true;
			}
			return false;
		}

		private void UpdateUI()
		{
			UpdateBuyButton();
			UpdateRecipeGamepadInput();
			m_coinText.text = GetPlayerCoins().ToString();
			try
			{
				m_coinPrefab = ObjectDB.instance.GetItemPrefab(m_selectedItem?.m_prefabCost).GetComponent<ItemDrop>();
			}
			catch
			{
				m_coinPrefab = ObjectDB.instance.GetItemPrefab(RapidLoadoutsPlugin.itemSetCostPrefab.Value).GetComponent<ItemDrop>();
			}
			m_coinIcon.sprite = m_coinPrefab.m_itemData.GetIcon();
		}

		public static void Show()
		{
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null || IsVisible())
			{
				return;
			}
			m_LocalPlayerRef = Player.m_localPlayer;
			((Component)InventoryGui.instance.m_dropButton).gameObject.SetActive(false);
			if (!RapidLoadoutsPlugin.HasAuga)
			{
				if ((Object)(object)((Component)Utils.FindChild(m_rootPanel.transform, "border (1)", (IterativeSearchType)0)).GetComponent<Image>() != (Object)(object)((Component)Utils.FindChild(((Component)StoreGui.instance).transform, "border (1)", (IterativeSearchType)0)).GetComponent<Image>().sprite)
				{
					((Component)Utils.FindChild(m_rootPanel.transform, "border (1)", (IterativeSearchType)0)).GetComponent<Image>().sprite = ((Component)Utils.FindChild(((Component)StoreGui.instance).transform, "border (1)", (IterativeSearchType)0)).GetComponent<Image>().sprite;
				}
				((Graphic)((Component)Utils.FindChild(m_rootPanel.transform, "border (1)", (IterativeSearchType)0)).GetComponent<Image>()).color = ((Graphic)((Component)Utils.FindChild(((Component)InventoryGui.instance.m_player).transform, "bkg", (IterativeSearchType)0)).GetComponent<Image>()).color;
			}
			m_rootPanel.SetActive(true);
			PanelActive = true;
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"Showing Item Set GUI");
			FillList();
		}

		public static void Hide()
		{
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"Hiding Item Set GUI");
			m_LocalPlayerRef = null;
			m_rootPanel.SetActive(false);
			PanelActive = false;
			((Component)InventoryGui.instance.m_dropButton).gameObject.SetActive(true);
		}

		public static void ToggleUI()
		{
			if (IsVisible())
			{
				Hide();
			}
			else
			{
				Show();
			}
		}

		public static bool IsVisible()
		{
			if (!Object.op_Implicit((Object)(object)m_instance) || !m_rootPanel.activeSelf)
			{
				return PanelActive;
			}
			return true;
		}

		public void OnChooseItemSet()
		{
			BuySelectedItemSet();
		}

		public void BuySelectedItemSet()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			if (m_selectedItem == null || !CanAfford(m_selectedItem))
			{
				return;
			}
			ItemSetHelper.TryGetSet(RegexUtilities.TrimInvalidCharacters(m_selectedItem.m_name), m_selectedItem.m_dropCurrent);
			if (!string.IsNullOrEmpty(m_selectedItem.m_setEffect))
			{
				if (m_selectedItem.m_setEffectAsGP)
				{
					ItemSetHelper.SetAnyGuardianPower(m_selectedItem.m_setEffect);
				}
				else
				{
					((Character)Player.m_localPlayer).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode(m_selectedItem.m_setEffect), false, 0, 0f);
				}
			}
			if (!Player.m_localPlayer.NoCostCheat())
			{
				((Humanoid)Player.m_localPlayer).GetInventory().RemoveItem(m_coinPrefab.m_itemData.m_shared.m_name, m_selectedItem.m_price, -1, true);
			}
			m_buyEffects.Create(((Component)this).transform.position, Quaternion.identity, (Transform)null, 1f, -1);
			FillList();
		}

		public static int GetPlayerCoins()
		{
			return ((Humanoid)Player.m_localPlayer).GetInventory().CountItems(m_coinPrefab.m_itemData.m_shared.m_name, -1, true);
		}

		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(2)]
		public bool CanAfford(ItemSet item)
		{
			int playerCoins = GetPlayerCoins();
			if (item != null)
			{
				if (item.m_price > playerCoins)
				{
					return Player.m_localPlayer.NoCostCheat();
				}
				return true;
			}
			return false;
		}

		[return: <056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(new byte[] { 1, 2 })]
		public static List<ItemSet> GetAvailableSets()
		{
			return RapidLoadoutsPlugin.RL_yamlData;
		}

		public static void FillList()
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Expected O, but got Unknown
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			int playerCoins = GetPlayerCoins();
			int num = GetSelectedItemIndex();
			List<ItemSet> availableSets = GetAvailableSets();
			foreach (GameObject item in m_itemList)
			{
				Object.Destroy((Object)(object)item);
			}
			m_itemList.Clear();
			m_listRoot.SetSizeWithCurrentAnchors((Axis)1, Mathf.Max(m_itemlistBaseSize, (float)availableSets.Count * m_itemSpacing));
			for (int i = 0; i < availableSets.Count; i++)
			{
				ItemSet itemSet = availableSets[i];
				GameObject element = Object.Instantiate<GameObject>(m_listElement, (Transform)(object)m_listRoot);
				element.SetActive(true);
				Transform transform = element.transform;
				((RectTransform)((transform is RectTransform) ? transform : null)).anchoredPosition = new Vector2(0f, (float)i * (0f - m_itemSpacing));
				int num2 = 0;
				if (itemSet != null && itemSet.m_price != 0)
				{
					num2 = itemSet.m_price;
				}
				bool flag = num2 <= playerCoins || Player.m_localPlayer.NoCostCheat();
				Image component = ((Component)element.transform.Find("icon")).GetComponent<Image>();
				if (itemSet?.m_items == null || itemSet.m_items.Count == 0 || (Object)(object)ItemSetHelper.ConvertToItemDrop(itemSet.m_items[0].m_item) == (Object)null)
				{
					component.sprite = ObjectDB.instance.GetItemPrefab("YagluthDrop").GetComponent<ItemDrop>().m_itemData.m_shared.m_icons[0];
				}
				else
				{
					ItemDrop obj = ItemSetHelper.ConvertToItemDrop(itemSet.m_items[0].m_item);
					object sprite;
					if (obj == null)
					{
						sprite = null;
					}
					else
					{
						ItemData itemData = obj.m_itemData;
						if (itemData == null)
						{
							sprite = null;
						}
						else
						{
							SharedData shared = itemData.m_shared;
							sprite = ((shared != null) ? shared.m_icons[0] : null);
						}
					}
					component.sprite = (Sprite)sprite;
				}
				((Graphic)component).color = (Color)(flag ? Color.white : new Color(1f, 0f, 1f, 0f));
				string text = Localization.instance.Localize(itemSet?.m_name ?? "Unknown Item Set");
				TMP_Text component2 = ((Component)element.transform.Find("name")).GetComponent<TMP_Text>();
				component2.text = text;
				((Graphic)component2).color = (flag ? Color.white : Color.grey);
				UITooltip component3 = element.GetComponent<UITooltip>();
				component3.m_topic = itemSet?.m_name ?? "Unknown Item Set";
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append($"Drop Current Items: {itemSet?.m_dropCurrent ?? false}");
				stringBuilder.Append(Environment.NewLine + "Skills: ");
				if (itemSet != null)
				{
					List<SetSkill> skills = itemSet.m_skills;
					if (skills != null && skills.Count > 0)
					{
						foreach (SetSkill skill in itemSet.m_skills)
						{
							stringBuilder.Append($"{skill.m_skill} {skill.m_level}{Environment.NewLine}");
						}
					}
				}
				if (itemSet?.m_items != null && itemSet.m_items.Count > 0)
				{
					foreach (SetItem item2 in itemSet.m_items)
					{
						string text2 = ItemSetHelper.ConvertToItemDrop(item2.m_item)?.m_itemData?.m_shared?.m_name;
						if (!string.IsNullOrEmpty(text2))
						{
							stringBuilder.Append(Environment.NewLine + Localization.instance.Localize(text2) + " x" + ItemSetHelper.Repeat("★", item2.m_quality));
						}
					}
				}
				if (!string.IsNullOrEmpty(itemSet?.m_setEffect))
				{
					stringBuilder.Append(Environment.NewLine + "Set Effect: " + itemSet?.m_setEffect);
				}
				component3.m_text = stringBuilder.ToString();
				TMP_Text component4 = ((Component)Utils.FindChild(element.transform, "price", (IterativeSearchType)0)).GetComponent<TMP_Text>();
				component4.text = (Player.m_localPlayer.NoCostCheat() ? "Free" : itemSet?.m_price.ToString());
				if (!flag)
				{
					((Graphic)component4).color = Color.grey;
				}
				((UnityEvent)element.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					OnSelectedItem(element);
				});
				m_itemList.Add(element);
			}
			if (num < 0)
			{
				num = 0;
			}
			SelectItem(num, center: false);
		}

		public static void OnSelectedItem(GameObject button)
		{
			SelectItem(FindSelectedRecipe(button), center: false);
		}

		public static int FindSelectedRecipe(GameObject button)
		{
			for (int i = 0; i < m_itemList.Count; i++)
			{
				if ((Object)(object)m_itemList[i] == (Object)(object)button)
				{
					return i;
				}
			}
			return -1;
		}

		public static void SelectItem(int index, bool center)
		{
			RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)("Setting selected recipe " + index));
			for (int i = 0; i < m_itemList.Count; i++)
			{
				bool active = i == index;
				((Component)m_itemList[i].transform.Find("selected")).gameObject.SetActive(active);
			}
			if (center && index >= 0)
			{
				? val = m_itemEnsureVisible;
				Transform transform = m_itemList[index].transform;
				((ScrollRectEnsureVisible)val).CenterOnItem((RectTransform)(object)((transform is RectTransform) ? transform : null));
			}
			m_selectedItem = ((index < 0) ? null : GetAvailableSets()[index]);
		}

		public static int GetSelectedItemIndex()
		{
			int result = 0;
			List<ItemSet> availableSets = GetAvailableSets();
			for (int i = 0; i < availableSets.Count; i++)
			{
				if (availableSets[i] == m_selectedItem)
				{
					result = i;
				}
			}
			return result;
		}

		public void UpdateBuyButton()
		{
			UITooltip component = ((Component)m_chooseButton).GetComponent<UITooltip>();
			if (m_selectedItem != null)
			{
				bool flag = CanAfford(m_selectedItem);
				bool flag2 = ((Humanoid)Player.m_localPlayer).GetInventory().HaveEmptySlot();
				((Selectable)m_chooseButton).interactable = flag && flag2;
				if (!flag)
				{
					component.m_text = Localization.instance.Localize("$msg_missingrequirement");
				}
				else if (!flag2)
				{
					component.m_text = Localization.instance.Localize("$inventory_full");
				}
				else
				{
					component.m_text = "";
				}
			}
			else
			{
				((Selectable)m_chooseButton).interactable = false;
				component.m_text = "";
			}
		}

		public void UpdateRecipeGamepadInput()
		{
			if (m_itemList.Count > 0)
			{
				if (ZInput.GetButtonDown("JoyLStickDown") || ZInput.GetButtonDown("JoyDPadDown"))
				{
					SelectItem(Mathf.Min(m_itemList.Count - 1, GetSelectedItemIndex() + 1), center: true);
				}
				if (ZInput.GetButtonDown("JoyLStickUp") || ZInput.GetButtonDown("JoyDPadUp"))
				{
					SelectItem(Mathf.Max(0, GetSelectedItemIndex() - 1), center: true);
				}
			}
		}
	}
	[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
	[<056847de-81f4-4335-9b65-6e0b5bd4ae59>Nullable(0)]
	public class UIDragger : EventTrigger
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(0)]
		public delegate void UIDroppedHandler(object source, Vector3 newLocalPosition);

		private bool _isDragging;

		public event UIDroppedHandler OnUIDropped;

		public void Update()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (_isDragging)
			{
				((Component)this).transform.position = Vector2.op_Implicit(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
			}
		}

		public override void OnPointerDown(PointerEventData eventData)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)eventData.button == 1 && Input.GetKey((KeyCode)306))
			{
				_isDragging = true;
			}
		}

		public override void OnPointerUp(PointerEventData eventData)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if ((int)eventData.button == 1)
			{
				_isDragging = false;
				this.OnUIDropped?.Invoke(this, new Vector3(((Component)this).transform.localPosition.x, ((Component)this).transform.localPosition.y, -1f));
			}
		}
	}
}
namespace RapidLoadouts.Game
{
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	internal static class ObjectDBAwakePatch
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
		private static void Postfix(ObjectDB __instance)
		{
			ItemSetHelper.AddCreateItemSets(ItemSets.instance);
		}
	}
	[HarmonyPatch(typeof(Player), "OnSpawned")]
	internal static class StoreGuiAwakePatch
	{
		[<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)]
		private static void Postfix(Player __instance)
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_038f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0394: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject gameObject;
				if (RapidLoadoutsPlugin.HasAuga)
				{
					GameObject val = GameObject.Find("_GameMain/LoadingGUI/PixelFix/IngameGui(Clone)");
					if ((Object)(object)val == (Object)null)
					{
						RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)"IngameGui not found");
						return;
					}
					Transform val2 = Utils.FindChild(val.transform, "AugaStoreScreen(Clone)", (IterativeSearchType)0);
					if ((Object)(object)val2 == (Object)null)
					{
						RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)"AugaStoreScreen not found");
						return;
					}
					gameObject = ((Component)val2).gameObject;
				}
				else
				{
					gameObject = ((Component)StoreGui.instance).gameObject;
					if ((Object)(object)gameObject == (Object)null)
					{
						RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)"StoreGui.instance is null");
						return;
					}
				}
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)("Root panel: " + ((Object)gameObject).name));
				GameObject val3 = Object.Instantiate<GameObject>(gameObject, ((Component)InventoryGui.instance.m_player).transform, false);
				((Object)val3).name = "AzuRapidLoadoutsRootPanel";
				val3.GetComponent<RectTransform>().anchoredPosition = new Vector2(550f, 150f);
				((Transform)val3.GetComponent<RectTransform>()).localPosition = RapidLoadoutsPlugin.ItemSetWindow.Value;
				ItemSetGui itemSetGui = val3.AddComponent<ItemSetGui>();
				if ((Object)(object)itemSetGui == (Object)null)
				{
					RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"ItemSetGui component not found on newRootPanel");
					return;
				}
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"ItemSetGui component found on newRootPanel");
				ItemSetGui.m_rootPanel = ((Component)Utils.FindChild(val3.transform, "Store", (IterativeSearchType)0)).gameObject;
				itemSetGui.m_chooseButton = ((Component)Utils.FindChild(val3.transform, "BuyButton", (IterativeSearchType)0)).GetComponent<Button>();
				((Component)((Component)itemSetGui.m_chooseButton).transform.Find(RapidLoadoutsPlugin.HasAuga ? "Label" : "Text")).GetComponent<TMP_Text>().text = Localization.instance.Localize("$azu_rl_buyItemSet");
				itemSetGui.m_sellButton = ((Component)Utils.FindChild(val3.transform, "SellButton", (IterativeSearchType)0)).GetComponent<Button>();
				((Component)itemSetGui.m_sellButton).GetComponent<UITooltip>().m_text = (RapidLoadoutsPlugin.HasAuga ? "Not implemented, couldn't hide this button without making the UI look unbalanced and ugly. Plus side? It makes a cool coin sound at least. Figured I'd leave the sound in." : Localization.instance.Localize("$azu_rl_equipSelected"));
				((Component)((Component)itemSetGui.m_sellButton).transform.Find("Image")).gameObject.SetActive(false);
				if (!RapidLoadoutsPlugin.HasAuga)
				{
					((Component)((Component)itemSetGui.m_sellButton).transform.Find("Image (1)")).gameObject.SetActive(true);
					((Component)((Component)itemSetGui.m_sellButton).transform.parent).gameObject.SetActive(false);
				}
				ItemSetGui.m_listRoot = ((Component)Utils.FindChild(val3.transform, "ListRoot", (IterativeSearchType)0)).GetComponent<RectTransform>();
				ItemSetGui.m_listElement = ((Component)Utils.FindChild(val3.transform, "ItemElement", (IterativeSearchType)0)).gameObject;
				itemSetGui.m_listScroll = ((Component)Utils.FindChild(val3.transform, RapidLoadoutsPlugin.HasAuga ? "ScrollBar" : "ItemScroll", (IterativeSearchType)0)).GetComponent<Scrollbar>();
				ItemSetGui.m_itemEnsureVisible = ((Component)Utils.FindChild(val3.transform, RapidLoadoutsPlugin.HasAuga ? "ItemListBkg" : "Items", (IterativeSearchType)0)).GetComponent<ScrollRectEnsureVisible>();
				itemSetGui.m_coinText = ((Component)val3.transform.Find("Store/" + (RapidLoadoutsPlugin.HasAuga ? "DividerMedium/" : "") + "coins/coins")).GetComponent<TMP_Text>();
				itemSetGui.m_coinIcon = ((Component)val3.transform.Find("Store/" + (RapidLoadoutsPlugin.HasAuga ? "DividerMedium/" : "") + "coins/coin icon" + (RapidLoadoutsPlugin.HasAuga ? "/coin icon" : ""))).GetComponent<Image>();
				if (!RapidLoadoutsPlugin.HasAuga)
				{
					RectTransform component = ((Component)val3.transform.Find("Store/coins/coin icon")).GetComponent<RectTransform>();
					component.anchoredPosition += new Vector2(0f, 5f);
					RectTransform component2 = ((Component)val3.transform.Find("Store/coins")).GetComponent<RectTransform>();
					component2.anchoredPosition += new Vector2(35f, 0f);
				}
				itemSetGui.m_topicText = ((Component)Utils.FindChild(val3.transform, RapidLoadoutsPlugin.HasAuga ? "Topic" : "topic", (IterativeSearchType)0)).GetComponent<TMP_Text>();
				itemSetGui.m_buyEffects = val3.GetComponent<StoreGui>().m_buyEffects;
				itemSetGui.m_sellEffects = val3.GetComponent<StoreGui>().m_sellEffects;
				itemSetGui.m_hideDistance = val3.GetComponent<StoreGui>().m_hideDistance;
				ItemSetGui.m_itemSpacing = val3.GetComponent<StoreGui>().m_itemSpacing;
				ItemSetGui.m_coinPrefab = val3.GetComponent<StoreGui>().m_coinPrefab;
				ItemSetGui.m_itemlistBaseSize = val3.GetComponent<StoreGui>().m_itemlistBaseSize;
				Object.DestroyImmediate((Object)(object)val3.GetComponent<StoreGui>());
				val3.AddComponent<UIDragger>().OnUIDropped += [<942ea9ad-0bda-45e1-8c54-6dcd2e77cdcd>NullableContext(1)] (object source, Vector3 position) =>
				{
					//IL_0005: Unknown result type (might be due to invalid IL or missing references)
					RapidLoadoutsPlugin.ItemSetWindow.Value = position;
				};
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogDebug((object)"ItemSetGui created successfully");
			}
			catch (Exception ex)
			{
				RapidLoadoutsPlugin.RapidLoadoutsLogger.LogError((object)("Exception: " + ex));
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<c7002a32-1b09-4227-bad3-5ed14ba5ad8a>Embedded]
	[CompilerGenerated]
	internal sealed class <c7002a32-1b09-4227-bad3-5ed14ba5ad8a>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]
	[<c7002a32-1b09-4227-bad3-5ed14ba5ad8a>Embedded]
	internal sealed class <376fb79c-ac61-4842-b97d-2e2f8ade4b21>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <376fb79c-ac61-4842-b97d-2e2f8ade4b21>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <376fb79c-ac61-4842-b97d-2e2f8ade4b21>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<c7002a32-1b09-4227-bad3-5ed14ba5ad8a>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <00455301-6e5f-4790-9988-0c3b66bc5782>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <00455301-6e5f-4790-9988-0c3b66bc5782>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[<c7002a32-1b09-4227-bad3-5ed14ba5ad8a>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
	[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
	[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
	[PublicAPI]
	internal class SyncedConfigEntry<[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)] 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;
			}
		}
	}
	[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(2)]
	[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(1)]
		public readonly string Identifier;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(1)]
		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;

		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
		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;
			};
		}
	}
	[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
	[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
	[PublicAPI]
	internal sealed class CustomSyncedValue<[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)] 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;
	}
	[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
	[PublicAPI]
	[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
	internal class ConfigSync
	{
		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
			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());
				}
				[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
				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));
					}
				}
				[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
				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")]
		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		private static class RegisterClientRPCPatch
		{
			[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
			[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);
				}
			}
		}

		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		private class ParsedConfigs
		{
			[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		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;
			}
		}

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
			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);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 2, 1, 1 })] 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)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[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(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
			public object value;
		}

		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
			[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;
			}
		}

		[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			[<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(1)]
			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;
			}
		}

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		public string DisplayName;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		public string CurrentVersion;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		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;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		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[]>>();

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 1, 0, 1 })]
		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;


		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		[method: <00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(2)]
		[field: <376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		[method: <00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(2)]
		[field: <376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		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<[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

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

		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(([<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 0, 1 })] 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 var 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([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (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([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (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)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != 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([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (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([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			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 (peer.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)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						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([<00455301-6e5f-4790-9988-0c3b66bc5782>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.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());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).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));
				}
			}
		}

		[return: <376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<376fb79c-ac61-4842-b97d-2e2f8ade4b21>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config