Decompiled source of Forteca ServerRewards v420.2.3

Forteca_ServerRewards.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Serialization;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Forteca_ServerRewards;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using fastJSON;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("304AA6D2-0783-4A5A-B05B-87001CDAF792")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Forteca_ServerRewards")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("Forteca_ServerRewards")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	public class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

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

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

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

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

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

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

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

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

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Expected O, but got Unknown
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				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;
				}
			}

			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Expected O, but got Unknown
				//IL_0048: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Expected O, but got Unknown
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Expected O, but got Unknown
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Expected O, but got Unknown
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Expected O, but got Unknown
				CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null);
				FieldInfo fieldInfo = AccessTools.Field(typeof(ZNetPeer), "m_socket");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(ZPlayFabSocket), "m_remotePlayerId");
				val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[4]
				{
					new CodeMatch((OpCode?)OpCodes.Ldloc_1, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)fieldInfo, (string)null),
					new CodeMatch((OpCode?)OpCodes.Isinst, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)fieldInfo2, (string)null)
				});
				if (val.IsInvalid)
				{
					return instructions;
				}
				val.SetAndAdvance(OpCodes.Ldstr, (object)"none");
				val.SetOpcodeAndAdvance(OpCodes.Nop);
				val.SetOpcodeAndAdvance(OpCodes.Nop);
				val.SetOpcodeAndAdvance(OpCodes.Nop);
				return val.InstructionEnumeration();
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Expected O, but got Unknown
				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()
				{
					//IL_008b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0091: Expected O, but got Unknown
					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> list = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							list.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						list.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)methodInfo == null) ? ((object)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2]
							{
								val,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section;

			public string key;

			public Type type;

			public object? value;
		}

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

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

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected;

			public string received;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

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

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

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

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

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

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool flag2;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0051;
					}
					flag2 = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					flag2 = flag == true;
				}
				if (flag2)
				{
					return !lockExempt;
				}
				goto IL_0051;
				IL_0051:
				return false;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin
		{
			get
			{
				if (!lockExempt)
				{
					return isSourceOfTruth;
				}
				return true;
			}
		}

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

		public bool InitialSyncDone { get; private set; }

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

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

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

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)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 += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

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

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((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((CustomSyncedValueBase v) => v.Priority));
			CustomSyncedValueBase customSyncedValueBase = customValue;
			customSyncedValueBase.ValueChanged = (Action)Delegate.Combine(customSyncedValueBase.ValueChanged, (Action)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_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 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((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					MemoryStream stream = new MemoryStream(package.ReadByteArray());
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				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((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null)
			{
				if (!configSync.IsLocked)
				{
					if (config == configSync.lockedConfig)
					{
						return lockExempt;
					}
					return true;
				}
				return false;
			}
			return true;
		}

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

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

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			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 val = new ZPackage();
						val.Write((byte)2);
						val.Write(packageIdentifier);
						val.Write(fragment);
						val.Write(fragments);
						val.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(val);
						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] { 5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!ValheimCompat.Exists((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = ValheimCompat.GetPeers();
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!ValheimCompat.Exists((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write((byte)4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				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 ((Object)(object)instance != (Object)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 ((Object)(object)instance != (Object)null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

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

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

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

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

		private static Type configType(Type type)
		{
			if (!type.IsEnum)
			{
				return type;
			}
			return Enum.GetUnderlyingType(type);
		}

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

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

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

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

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

		public void Update()
		{
			ValueChanged?.Invoke();
		}

		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;
			}
		}
	}
	public abstract class CustomSyncedValueBase
	{
		public Action? ValueChanged;

		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

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

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

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

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)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;
			}
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	public class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

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

		private ConfigSync? ConfigSync;

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

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

		public string MinimumRequiredVersion
		{
			get
			{
				string text = minimumRequiredVersion;
				if (text == null)
				{
					if (!ModRequired)
					{
						return "0.0.0";
					}
					text = CurrentVersion;
				}
				return text;
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return num && flag;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)))
			{
				return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".";
			}
			return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".";
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			if (rpc != null)
			{
				return ErrorServer(rpc);
			}
			return ErrorClient();
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			ValheimCompat.SetZNetConnectionStatus(3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				Debug.LogWarning((object)array2[i].Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					TMP_Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.";
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				__instance.m_connectionFailedError.ForceMeshUpdate(false, false);
				float num = __instance.m_connectionFailedError.renderedHeight + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}
namespace fastJSON
{
	internal class DataMemberAttribute : Attribute
	{
		public string Name { get; set; }
	}
	internal sealed class DatasetSchema
	{
		public List<string> Info;

		public string Name;
	}
	internal class deserializer
	{
		private JSONParameters _params;

		private bool _usingglobals;

		private Dictionary<object, int> _circobj;

		private Dictionary<int, object> _cirrev = new Dictionary<int, object>();

		public deserializer(JSONParameters param)
		{
			if (param.OverrideObjectHashCodeChecking)
			{
				_circobj = new Dictionary<object, int>(10, ReferenceEqualityComparer.Default);
			}
			else
			{
				_circobj = new Dictionary<object, int>();
			}
			param.FixValues();
			_params = param.MakeCopy();
		}

		public T ToObject<T>(string json)
		{
			Type typeFromHandle = typeof(T);
			object obj = ToObject(json, typeFromHandle);
			if (typeFromHandle.IsArray)
			{
				if ((obj as ICollection).Count == 0)
				{
					return (T)(object)Array.CreateInstance(typeFromHandle.GetElementType(), 0);
				}
				return (T)obj;
			}
			return (T)obj;
		}

		public object ToObject(string json)
		{
			return ToObject(json, null);
		}

		public object ToObject(string json, Type type)
		{
			Type type2 = null;
			if (type != null && type.IsGenericType)
			{
				type2 = Reflection.Instance.GetGenericTypeDefinition(type);
			}
			_usingglobals = _params.UsingGlobalTypes;
			if (typeof(IDictionary).IsAssignableFrom(type2) || typeof(List<>).IsAssignableFrom(type2))
			{
				_usingglobals = false;
			}
			object obj = new JsonParser(json, _params.AllowNonQuotedKeys).Decode(type);
			if (obj == null)
			{
				return null;
			}
			if (obj is IDictionary)
			{
				if (type != null && typeof(Dictionary<, >).IsAssignableFrom(type2))
				{
					return RootDictionary(obj, type);
				}
				return ParseDictionary(obj as Dictionary<string, object>, null, type, null);
			}
			if (obj is List<object>)
			{
				if (!(type != null))
				{
					List<object> list = (List<object>)obj;
					if (list.Count > 0 && list[0].GetType() == typeof(Dictionary<string, object>))
					{
						Dictionary<string, object> globaltypes = new Dictionary<string, object>();
						List<object> list2 = new List<object>();
						{
							foreach (object item in list)
							{
								list2.Add(ParseDictionary((Dictionary<string, object>)item, globaltypes, null, null));
							}
							return list2;
						}
					}
					return list.ToArray();
				}
				if (typeof(Dictionary<, >).IsAssignableFrom(type2))
				{
					return RootDictionary(obj, type);
				}
				if (type2 == typeof(List<>))
				{
					return RootList(obj, type);
				}
				if (type.IsArray)
				{
					return RootArray(obj, type);
				}
				if (type == typeof(Hashtable))
				{
					return RootHashTable((List<object>)obj);
				}
			}
			else if (type != null && obj.GetType() != type)
			{
				return ChangeType(obj, type);
			}
			return obj;
		}

		private object RootHashTable(List<object> o)
		{
			Hashtable hashtable = new Hashtable();
			foreach (Dictionary<string, object> item in o)
			{
				object obj2 = item["k"];
				object obj3 = item["v"];
				if (obj2 is Dictionary<string, object>)
				{
					obj2 = ParseDictionary((Dictionary<string, object>)obj2, null, typeof(object), null);
				}
				if (obj3 is Dictionary<string, object>)
				{
					obj3 = ParseDictionary((Dictionary<string, object>)obj3, null, typeof(object), null);
				}
				hashtable.Add(obj2, obj3);
			}
			return hashtable;
		}

		private object ChangeType(object value, Type conversionType)
		{
			if (conversionType == typeof(object))
			{
				return value;
			}
			if (conversionType == typeof(int))
			{
				if (!(value is string text))
				{
					return (int)(long)value;
				}
				if (_params.AutoConvertStringToNumbers)
				{
					return Helper.CreateInteger(text, 0, text.Length);
				}
				throw new Exception("AutoConvertStringToNumbers is disabled for converting string : " + value);
			}
			if (conversionType == typeof(long))
			{
				if (!(value is string text2))
				{
					return (long)value;
				}
				if (_params.AutoConvertStringToNumbers)
				{
					return Helper.CreateLong(text2, 0, text2.Length);
				}
				throw new Exception("AutoConvertStringToNumbers is disabled for converting string : " + value);
			}
			if (conversionType == typeof(string))
			{
				return (string)value;
			}
			if (conversionType.IsEnum)
			{
				return Helper.CreateEnum(conversionType, value);
			}
			if (conversionType == typeof(DateTime))
			{
				return Helper.CreateDateTime((string)value, _params.UseUTCDateTime);
			}
			if (conversionType == typeof(DateTimeOffset))
			{
				return Helper.CreateDateTimeOffset((string)value);
			}
			if (Reflection.Instance.IsTypeRegistered(conversionType))
			{
				return Reflection.Instance.CreateCustom((string)value, conversionType);
			}
			if (Helper.IsNullable(conversionType))
			{
				if (value == null)
				{
					return value;
				}
				conversionType = Helper.UnderlyingTypeOf(conversionType);
			}
			if (conversionType == typeof(Guid))
			{
				return Helper.CreateGuid((string)value);
			}
			if (conversionType == typeof(byte[]))
			{
				return Convert.FromBase64String((string)value);
			}
			if (conversionType == typeof(TimeSpan))
			{
				return new TimeSpan((long)value);
			}
			return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
		}

		private object RootList(object parse, Type type)
		{
			Type[] genericArguments = Reflection.Instance.GetGenericArguments(type);
			IList list = (IList)Reflection.Instance.FastCreateList(type, ((IList)parse).Count);
			DoParseList((IList)parse, genericArguments[0], list);
			return list;
		}

		private void DoParseList(IList parse, Type it, IList o)
		{
			Dictionary<string, object> globaltypes = new Dictionary<string, object>();
			foreach (object item in parse)
			{
				_usingglobals = false;
				object obj = item;
				obj = ((!(item is Dictionary<string, object> d)) ? ChangeType(item, it) : ParseDictionary(d, globaltypes, it, null));
				o.Add(obj);
			}
		}

		private object RootArray(object parse, Type type)
		{
			Type elementType = type.GetElementType();
			IList list = (IList)Reflection.Instance.FastCreateInstance(typeof(List<>).MakeGenericType(elementType));
			DoParseList((IList)parse, elementType, list);
			Array array = Array.CreateInstance(elementType, list.Count);
			list.CopyTo(array, 0);
			return array;
		}

		private object RootDictionary(object parse, Type type)
		{
			Type[] genericArguments = Reflection.Instance.GetGenericArguments(type);
			Type type2 = null;
			Type type3 = null;
			bool flag = false;
			if (genericArguments != null)
			{
				type2 = genericArguments[0];
				type3 = genericArguments[1];
				if (type3 != null)
				{
					flag = type3.Name.StartsWith("Dictionary");
				}
			}
			Type elementType = type3.GetElementType();
			if (parse is Dictionary<string, object>)
			{
				IDictionary dictionary = (IDictionary)Reflection.Instance.FastCreateInstance(type);
				{
					foreach (KeyValuePair<string, object> item in (Dictionary<string, object>)parse)
					{
						object key = ChangeType(item.Key, type2);
						object value = ((!flag) ? ((!(item.Value is Dictionary<string, object>)) ? ((type3.IsArray && type3 != typeof(byte[])) ? CreateArray((List<object>)item.Value, type3, elementType, null) : ((!(item.Value is IList)) ? ChangeType(item.Value, type3) : CreateGenericList((List<object>)item.Value, type3, type2, null))) : ParseDictionary(item.Value as Dictionary<string, object>, null, type3, null)) : RootDictionary(item.Value, type3));
						dictionary.Add(key, value);
					}
					return dictionary;
				}
			}
			if (parse is List<object>)
			{
				return CreateDictionary(parse as List<object>, type, genericArguments, null);
			}
			return null;
		}

		internal object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type, object input)
		{
			object value = "";
			if (type == typeof(NameValueCollection))
			{
				return Helper.CreateNV(d);
			}
			if (type == typeof(StringDictionary))
			{
				return Helper.CreateSD(d);
			}
			if (d.TryGetValue("$i", out value))
			{
				object value2 = null;
				_cirrev.TryGetValue((int)(long)value, out value2);
				return value2;
			}
			if (d.TryGetValue("$types", out value))
			{
				_usingglobals = true;
				if (globaltypes == null)
				{
					globaltypes = new Dictionary<string, object>();
				}
				foreach (KeyValuePair<string, object> item in (Dictionary<string, object>)value)
				{
					globaltypes.Add((string)item.Value, item.Key);
				}
			}
			if (globaltypes != null)
			{
				_usingglobals = true;
			}
			bool flag = d.TryGetValue("$type", out value);
			if (!flag && type == typeof(object))
			{
				return d;
			}
			if (flag)
			{
				if (_usingglobals)
				{
					object value3 = "";
					if (globaltypes != null && globaltypes.TryGetValue((string)value, out value3))
					{
						value = value3;
					}
				}
				type = Reflection.Instance.GetTypeFromCache((string)value, _params.BadListTypeChecking);
			}
			if (type == null)
			{
				throw new Exception("Cannot determine type : " + value);
			}
			string fullName = type.FullName;
			object obj = input;
			if (obj == null)
			{
				obj = ((!_params.ParametricConstructorOverride) ? Reflection.Instance.FastCreateInstance(type) : FormatterServices.GetUninitializedObject(type));
			}
			int value4 = 0;
			if (!_circobj.TryGetValue(obj, out value4))
			{
				value4 = _circobj.Count + 1;
				_circobj.Add(obj, value4);
				_cirrev.Add(value4, obj);
			}
			Dictionary<string, myPropInfo> dictionary = Reflection.Instance.Getproperties(type, fullName, _params.ShowReadOnlyProperties);
			foreach (KeyValuePair<string, object> item2 in d)
			{
				string key = item2.Key;
				object value5 = item2.Value;
				string text = key;
				if (text == "$map")
				{
					ProcessMap(obj, dictionary, (Dictionary<string, object>)d[text]);
				}
				else
				{
					if ((!dictionary.TryGetValue(text, out var value6) && !dictionary.TryGetValue(text.ToLowerInvariant(), out value6)) || !value6.CanWrite)
					{
						continue;
					}
					object value7 = null;
					if (value5 != null)
					{
						switch (value6.Type)
						{
						case myPropInfoType.Int:
							value7 = (int)Helper.AutoConv(value5, _params);
							break;
						case myPropInfoType.Long:
							value7 = Helper.AutoConv(value5, _params);
							break;
						case myPropInfoType.String:
							value7 = value5.ToString();
							break;
						case myPropInfoType.Bool:
							value7 = Helper.BoolConv(value5);
							break;
						case myPropInfoType.DateTime:
							value7 = Helper.CreateDateTime((string)value5, _params.UseUTCDateTime);
							break;
						case myPropInfoType.Enum:
							value7 = Helper.CreateEnum(value6.pt, value5);
							break;
						case myPropInfoType.Guid:
							value7 = Helper.CreateGuid((string)value5);
							break;
						case myPropInfoType.Array:
							if (!value6.IsValueType)
							{
								value7 = CreateArray((List<object>)value5, value6.pt, value6.bt, globaltypes);
							}
							break;
						case myPropInfoType.ByteArray:
							value7 = Convert.FromBase64String((string)value5);
							break;
						case myPropInfoType.Dictionary:
							value7 = CreateDictionary((List<object>)value5, value6.pt, value6.GenericTypes, globaltypes);
							break;
						case myPropInfoType.StringKeyDictionary:
							value7 = CreateStringKeyDictionary((Dictionary<string, object>)value5, value6.pt, value6.GenericTypes, globaltypes);
							break;
						case myPropInfoType.NameValue:
							value7 = Helper.CreateNV((Dictionary<string, object>)value5);
							break;
						case myPropInfoType.StringDictionary:
							value7 = Helper.CreateSD((Dictionary<string, object>)value5);
							break;
						case myPropInfoType.Custom:
							value7 = Reflection.Instance.CreateCustom((string)value5, value6.pt);
							break;
						default:
							value7 = ((value6.IsGenericType && !value6.IsValueType && value5 is List<object>) ? CreateGenericList((List<object>)value5, value6.pt, value6.bt, globaltypes) : (((value6.IsClass || value6.IsStruct || value6.IsInterface) && value5 is Dictionary<string, object>) ? ParseDictionary((Dictionary<string, object>)value5, globaltypes, value6.pt, null) : ((value5 is List<object>) ? CreateArray((List<object>)value5, value6.pt, typeof(object), globaltypes) : ((!value6.IsValueType) ? value5 : ChangeType(value5, value6.changeType)))));
							break;
						}
					}
					obj = value6.setter(obj, value7);
				}
			}
			return obj;
		}

		private static void ProcessMap(object obj, Dictionary<string, myPropInfo> props, Dictionary<string, object> dic)
		{
			foreach (KeyValuePair<string, object> item in dic)
			{
				myPropInfo myPropInfo2 = props[item.Key];
				object obj2 = myPropInfo2.getter(obj);
				if (Reflection.Instance.GetTypeFromCache((string)item.Value, badlistChecking: true) == typeof(Guid))
				{
					myPropInfo2.setter(obj, Helper.CreateGuid((string)obj2));
				}
			}
		}

		private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
		{
			if (bt == null)
			{
				bt = typeof(object);
			}
			Array array = Array.CreateInstance(bt, data.Count);
			Type elementType = bt.GetElementType();
			for (int i = 0; i < data.Count; i++)
			{
				object obj = data[i];
				if (obj != null)
				{
					if (obj is IDictionary)
					{
						array.SetValue(ParseDictionary((Dictionary<string, object>)obj, globalTypes, bt, null), i);
					}
					else if (obj is ICollection)
					{
						array.SetValue(CreateArray((List<object>)obj, bt, elementType, globalTypes), i);
					}
					else
					{
						array.SetValue(ChangeType(obj, bt), i);
					}
				}
			}
			return array;
		}

		private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
		{
			if (pt != typeof(object))
			{
				IList list = (IList)Reflection.Instance.FastCreateList(pt, data.Count);
				Type type = Reflection.Instance.GetGenericArguments(pt)[0];
				{
					foreach (object datum in data)
					{
						if (datum is IDictionary)
						{
							list.Add(ParseDictionary((Dictionary<string, object>)datum, globalTypes, type, null));
						}
						else if (datum is List<object>)
						{
							if (bt.IsGenericType)
							{
								list.Add((List<object>)datum);
							}
							else
							{
								list.Add(((List<object>)datum).ToArray());
							}
						}
						else
						{
							list.Add(ChangeType(datum, type));
						}
					}
					return list;
				}
			}
			return data;
		}

		private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
		{
			IDictionary dictionary = (IDictionary)Reflection.Instance.FastCreateInstance(pt);
			Type type = null;
			Type type2 = null;
			if (types != null)
			{
				type2 = types[1];
			}
			Type bt = null;
			Type[] genericArguments = Reflection.Instance.GetGenericArguments(type2);
			if (genericArguments.Length != 0)
			{
				bt = genericArguments[0];
			}
			type = type2.GetElementType();
			foreach (KeyValuePair<string, object> item in reader)
			{
				string key = item.Key;
				object obj = null;
				obj = ((!(item.Value is Dictionary<string, object>)) ? ((types != null && type2.IsArray) ? ((!(item.Value is Array)) ? CreateArray((List<object>)item.Value, type2, type, globalTypes) : item.Value) : ((!(item.Value is IList)) ? ChangeType(item.Value, type2) : CreateGenericList((List<object>)item.Value, type2, bt, globalTypes))) : ParseDictionary((Dictionary<string, object>)item.Value, globalTypes, type2, null));
				dictionary.Add(key, obj);
			}
			return dictionary;
		}

		private object CreateDictionary(List<object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
		{
			IDictionary dictionary = (IDictionary)Reflection.Instance.FastCreateInstance(pt);
			Type type = null;
			Type type2 = null;
			Type bt = null;
			if (types != null)
			{
				type = types[0];
				type2 = types[1];
			}
			Type bt2 = type2;
			if (type2 != null)
			{
				Type[] genericArguments = Reflection.Instance.GetGenericArguments(type2);
				if (genericArguments.Length != 0)
				{
					bt = genericArguments[0];
				}
				bt2 = type2.GetElementType();
			}
			bool flag = typeof(IDictionary).IsAssignableFrom(type2);
			foreach (Dictionary<string, object> item in reader)
			{
				object obj2 = item["k"];
				object obj3 = item["v"];
				obj2 = ((!(obj2 is Dictionary<string, object>)) ? ChangeType(obj2, type) : ParseDictionary((Dictionary<string, object>)obj2, globalTypes, type, null));
				obj3 = ((!flag) ? ((!(obj3 is Dictionary<string, object>)) ? ((types != null && type2.IsArray) ? CreateArray((List<object>)obj3, type2, bt2, globalTypes) : ((!(obj3 is IList)) ? ChangeType(obj3, type2) : CreateGenericList((List<object>)obj3, type2, bt, globalTypes))) : ParseDictionary((Dictionary<string, object>)obj3, globalTypes, type2, null)) : RootDictionary(obj3, type2));
				dictionary.Add(obj2, obj3);
			}
			return dictionary;
		}
	}
	internal class DynamicJson : DynamicObject, IEnumerable
	{
		private IDictionary<string, object> _dictionary { get; set; }

		private List<object> _list { get; set; }

		public DynamicJson(string json)
		{
			object obj = JSON.Parse(json);
			if (obj is IDictionary<string, object>)
			{
				_dictionary = (IDictionary<string, object>)obj;
			}
			else
			{
				_list = (List<object>)obj;
			}
		}

		private DynamicJson(object dictionary)
		{
			if (dictionary is IDictionary<string, object>)
			{
				_dictionary = (IDictionary<string, object>)dictionary;
			}
		}

		public override IEnumerable<string> GetDynamicMemberNames()
		{
			return _dictionary.Keys.ToList();
		}

		public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
		{
			object obj = indexes[0];
			if (obj is int)
			{
				result = _list[(int)obj];
			}
			else
			{
				result = _dictionary[(string)obj];
			}
			if (result is IDictionary<string, object>)
			{
				result = new DynamicJson(result as IDictionary<string, object>);
			}
			return true;
		}

		public override bool TryGetMember(GetMemberBinder binder, out object result)
		{
			if (!_dictionary.TryGetValue(binder.Name, out result) && !_dictionary.TryGetValue(binder.Name.ToLowerInvariant(), out result))
			{
				return false;
			}
			if (result is IDictionary<string, object>)
			{
				result = new DynamicJson(result as IDictionary<string, object>);
			}
			else if (result is List<object>)
			{
				List<object> list = new List<object>();
				foreach (object item in (List<object>)result)
				{
					if (item is IDictionary<string, object>)
					{
						list.Add(new DynamicJson(item as IDictionary<string, object>));
					}
					else
					{
						list.Add(item);
					}
				}
				result = list;
			}
			return _dictionary.ContainsKey(binder.Name);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			foreach (object item in _list)
			{
				yield return new DynamicJson(item as IDictionary<string, object>);
			}
		}
	}
	internal static class Formatter
	{
		private static void AppendIndent(StringBuilder sb, int count, string indent)
		{
			while (count > 0)
			{
				sb.Append(indent);
				count--;
			}
		}

		public static string PrettyPrint(string input)
		{
			return PrettyPrint(input, new string(' ', JSON.Parameters.FormatterIndentSpaces));
		}

		public static string PrettyPrint(string input, string spaces)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			int length = input.Length;
			char[] array = input.ToCharArray();
			for (int i = 0; i < length; i++)
			{
				char c = array[i];
				if (c == '"')
				{
					bool flag = true;
					while (flag)
					{
						stringBuilder.Append(c);
						c = array[++i];
						switch (c)
						{
						case '\\':
							stringBuilder.Append(c);
							c = array[++i];
							break;
						case '"':
							flag = false;
							break;
						}
					}
				}
				switch (c)
				{
				case '[':
				case '{':
					stringBuilder.Append(c);
					stringBuilder.AppendLine();
					AppendIndent(stringBuilder, ++num, spaces);
					break;
				case ']':
				case '}':
					stringBuilder.AppendLine();
					AppendIndent(stringBuilder, --num, spaces);
					stringBuilder.Append(c);
					break;
				case ',':
					stringBuilder.Append(c);
					stringBuilder.AppendLine();
					AppendIndent(stringBuilder, num, spaces);
					break;
				case ':':
					stringBuilder.Append(" : ");
					break;
				default:
					if (!char.IsWhiteSpace(c))
					{
						stringBuilder.Append(c);
					}
					break;
				}
			}
			return stringBuilder.ToString();
		}
	}
	internal struct Getters
	{
		public string Name;

		public string lcName;

		public string memberName;

		public Reflection.GenericGetter Getter;

		public bool ReadOnly;
	}
	internal class Helper
	{
		public static bool IsNullable(Type t)
		{
			if (!t.IsGenericType)
			{
				return false;
			}
			return t.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
		}

		public static Type UnderlyingTypeOf(Type t)
		{
			return Reflection.Instance.GetGenericArguments(t)[0];
		}

		public static DateTimeOffset CreateDateTimeOffset(int year, int month, int day, int hour, int min, int sec, int milli, int extraTicks, TimeSpan offset)
		{
			DateTimeOffset dateTimeOffset = new DateTimeOffset(year, month, day, hour, min, sec, milli, offset);
			if (extraTicks > 0)
			{
				return dateTimeOffset + TimeSpan.FromTicks(extraTicks);
			}
			return dateTimeOffset;
		}

		public static bool BoolConv(object v)
		{
			bool result = false;
			if (v is bool)
			{
				result = (bool)v;
			}
			else if (v is long)
			{
				result = (long)v > 0;
			}
			else if (v is string)
			{
				switch (((string)v).ToLowerInvariant())
				{
				case "1":
				case "true":
				case "yes":
				case "on":
					result = true;
					break;
				}
			}
			return result;
		}

		public static long AutoConv(object value, JSONParameters param)
		{
			if (value is string)
			{
				if (param.AutoConvertStringToNumbers)
				{
					string text = (string)value;
					return CreateLong(text, 0, text.Length);
				}
				throw new Exception("AutoConvertStringToNumbers is disabled for converting string : " + value);
			}
			if (value is long)
			{
				return (long)value;
			}
			return Convert.ToInt64(value);
		}

		public unsafe static long CreateLong(string s, int index, int count)
		{
			long num = 0L;
			int num2 = 1;
			fixed (char* ptr = s)
			{
				char* ptr2 = ptr;
				ptr2 += index;
				if (*ptr2 == '-')
				{
					num2 = -1;
					ptr2++;
					count--;
				}
				if (*ptr2 == '+')
				{
					ptr2++;
					count--;
				}
				while (count > 0)
				{
					num = num * 10 + (*ptr2 - 48);
					ptr2++;
					count--;
				}
			}
			return num * num2;
		}

		public unsafe static long CreateLong(char[] s, int index, int count)
		{
			long num = 0L;
			int num2 = 1;
			fixed (char* ptr = s)
			{
				char* ptr2 = ptr;
				ptr2 += index;
				if (*ptr2 == '-')
				{
					num2 = -1;
					ptr2++;
					count--;
				}
				if (*ptr2 == '+')
				{
					ptr2++;
					count--;
				}
				while (count > 0)
				{
					num = num * 10 + (*ptr2 - 48);
					ptr2++;
					count--;
				}
			}
			return num * num2;
		}

		public unsafe static int CreateInteger(string s, int index, int count)
		{
			int num = 0;
			int num2 = 1;
			fixed (char* ptr = s)
			{
				char* ptr2 = ptr;
				ptr2 += index;
				if (*ptr2 == '-')
				{
					num2 = -1;
					ptr2++;
					count--;
				}
				if (*ptr2 == '+')
				{
					ptr2++;
					count--;
				}
				while (count > 0)
				{
					num = num * 10 + (*ptr2 - 48);
					ptr2++;
					count--;
				}
			}
			return num * num2;
		}

		public static object CreateEnum(Type pt, object v)
		{
			return Enum.Parse(pt, v.ToString(), ignoreCase: true);
		}

		public static Guid CreateGuid(string s)
		{
			if (s.Length > 30)
			{
				return new Guid(s);
			}
			return new Guid(Convert.FromBase64String(s));
		}

		public static StringDictionary CreateSD(Dictionary<string, object> d)
		{
			StringDictionary stringDictionary = new StringDictionary();
			foreach (KeyValuePair<string, object> item in d)
			{
				stringDictionary.Add(item.Key, (string)item.Value);
			}
			return stringDictionary;
		}

		public static NameValueCollection CreateNV(Dictionary<string, object> d)
		{
			NameValueCollection nameValueCollection = new NameValueCollection();
			foreach (KeyValuePair<string, object> item in d)
			{
				nameValueCollection.Add(item.Key, (string)item.Value);
			}
			return nameValueCollection;
		}

		public static object CreateDateTimeOffset(string value)
		{
			int milli = 0;
			int extraTicks = 0;
			int num = 0;
			int num2 = 0;
			int year = CreateInteger(value, 0, 4);
			int month = CreateInteger(value, 5, 2);
			int day = CreateInteger(value, 8, 2);
			int hour = CreateInteger(value, 11, 2);
			int min = CreateInteger(value, 14, 2);
			int sec = CreateInteger(value, 17, 2);
			int num3 = 20;
			if (value.Length > 21 && value[19] == '.')
			{
				milli = CreateInteger(value, num3, 3);
				num3 = 23;
				if (value.Length > 25 && char.IsDigit(value[num3]))
				{
					extraTicks = CreateInteger(value, num3, 4);
					num3 = 27;
				}
			}
			if (value[num3] == 'Z')
			{
				return CreateDateTimeOffset(year, month, day, hour, min, sec, milli, extraTicks, TimeSpan.Zero);
			}
			if (value[num3] == ' ')
			{
				num3++;
			}
			num = CreateInteger(value, num3 + 1, 2);
			num2 = CreateInteger(value, num3 + 1 + 2 + 1, 2);
			if (value[num3] == '-')
			{
				num = -num;
			}
			return CreateDateTimeOffset(year, month, day, hour, min, sec, milli, extraTicks, new TimeSpan(num, num2, 0));
		}

		public static DateTime CreateDateTime(string value, bool UseUTCDateTime)
		{
			if (value.Length < 19)
			{
				return DateTime.MinValue;
			}
			bool flag = false;
			int millisecond = 0;
			int year = CreateInteger(value, 0, 4);
			int month = CreateInteger(value, 5, 2);
			int day = CreateInteger(value, 8, 2);
			int hour = CreateInteger(value, 11, 2);
			int minute = CreateInteger(value, 14, 2);
			int second = CreateInteger(value, 17, 2);
			if (value.Length > 21 && value[19] == '.')
			{
				millisecond = CreateInteger(value, 20, 3);
			}
			if (value[value.Length - 1] == 'Z')
			{
				flag = true;
			}
			if (!UseUTCDateTime && !flag)
			{
				return new DateTime(year, month, day, hour, minute, second, millisecond);
			}
			return new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Utc).ToLocalTime();
		}
	}
	internal static class JSON
	{
		public static JSONParameters Parameters = new JSONParameters();

		public static string ToNiceJSON(object obj)
		{
			return Beautify(ToJSON(obj, Parameters));
		}

		public static string ToNiceJSON(object obj, JSONParameters param)
		{
			return Beautify(ToJSON(obj, param), param.FormatterIndentSpaces);
		}

		public static string ToJSON(object obj)
		{
			return ToJSON(obj, Parameters);
		}

		public static string ToJSON(object obj, JSONParameters param)
		{
			param.FixValues();
			param = param.MakeCopy();
			Type c = null;
			if (obj == null)
			{
				return "null";
			}
			if (obj.GetType().IsGenericType)
			{
				c = Reflection.Instance.GetGenericTypeDefinition(obj.GetType());
			}
			if (typeof(IDictionary).IsAssignableFrom(c) || typeof(List<>).IsAssignableFrom(c))
			{
				param.UsingGlobalTypes = false;
			}
			if (param.EnableAnonymousTypes)
			{
				param.UseExtensions = false;
				param.UsingGlobalTypes = false;
			}
			return new JSONSerializer(param).ConvertToJSON(obj);
		}

		public static object Parse(string json)
		{
			return new JsonParser(json, Parameters.AllowNonQuotedKeys).Decode(null);
		}

		public static dynamic ToDynamic(string json)
		{
			return new DynamicJson(json);
		}

		public static T ToObject<T>(string json)
		{
			return new deserializer(Parameters).ToObject<T>(json);
		}

		public static T ToObject<T>(string json, JSONParameters param)
		{
			return new deserializer(param).ToObject<T>(json);
		}

		public static object ToObject(string json)
		{
			return new deserializer(Parameters).ToObject(json, null);
		}

		public static object ToObject(string json, JSONParameters param)
		{
			return new deserializer(param).ToObject(json, null);
		}

		public static object ToObject(string json, Type type)
		{
			return new deserializer(Parameters).ToObject(json, type);
		}

		public static object ToObject(string json, Type type, JSONParameters par)
		{
			return new deserializer(par).ToObject(json, type);
		}

		public static object FillObject(object input, string json)
		{
			if (!(new JsonParser(json, Parameters.AllowNonQuotedKeys).Decode(input.GetType()) is Dictionary<string, object> d))
			{
				return null;
			}
			return new deserializer(Parameters).ParseDictionary(d, null, input.GetType(), input);
		}

		public static object DeepCopy(object obj)
		{
			return new deserializer(Parameters).ToObject(ToJSON(obj));
		}

		public static T DeepCopy<T>(T obj)
		{
			return new deserializer(Parameters).ToObject<T>(ToJSON(obj));
		}

		public static string Beautify(string input)
		{
			string spaces = new string(' ', Parameters.FormatterIndentSpaces);
			return Formatter.PrettyPrint(input, spaces);
		}

		public static string Beautify(string input, byte spaces)
		{
			string spaces2 = new string(' ', spaces);
			return Formatter.PrettyPrint(input, spaces2);
		}

		public static void RegisterCustomType(Type type, Reflection.Serialize serializer, Reflection.Deserialize deserializer)
		{
			Reflection.Instance.RegisterCustomType(type, serializer, deserializer);
		}

		public static void ClearReflectionCache()
		{
			Reflection.Instance.ClearReflectionCache();
		}
	}
	internal sealed class JSONParameters
	{
		public bool UseOptimizedDatasetSchema = true;

		public bool UseFastGuid = true;

		public bool SerializeNullValues = true;

		public bool UseUTCDateTime = true;

		public bool ShowReadOnlyProperties;

		public bool UsingGlobalTypes = true;

		[Obsolete("Not needed anymore and will always match")]
		public bool IgnoreCaseOnDeserialize;

		public bool EnableAnonymousTypes;

		public bool UseExtensions = true;

		public bool UseEscapedUnicode = true;

		public bool KVStyleStringDictionary;

		public bool UseValuesOfEnums;

		public List<Type> IgnoreAttributes = new List<Type>
		{
			typeof(XmlIgnoreAttribute),
			typeof(NonSerializedAttribute)
		};

		public bool ParametricConstructorOverride;

		public bool DateTimeMilliseconds;

		public byte SerializerMaxDepth = 20;

		public bool InlineCircularReferences;

		public bool SerializeToLowerCaseNames;

		public byte FormatterIndentSpaces = 3;

		public bool AllowNonQuotedKeys;

		public bool AutoConvertStringToNumbers = true;

		public bool OverrideObjectHashCodeChecking;

		[Obsolete("Racist term removed, please use BadListTypeChecking")]
		public bool BlackListTypeChecking = true;

		public bool BadListTypeChecking = true;

		public bool FullyQualifiedDataSetSchema;

		public void FixValues()
		{
			if (!UseExtensions)
			{
				UsingGlobalTypes = false;
				InlineCircularReferences = true;
			}
			if (EnableAnonymousTypes)
			{
				ShowReadOnlyProperties = true;
			}
		}

		public JSONParameters MakeCopy()
		{
			return new JSONParameters
			{
				AllowNonQuotedKeys = AllowNonQuotedKeys,
				DateTimeMilliseconds = DateTimeMilliseconds,
				EnableAnonymousTypes = EnableAnonymousTypes,
				FormatterIndentSpaces = FormatterIndentSpaces,
				IgnoreAttributes = new List<Type>(IgnoreAttributes),
				InlineCircularReferences = InlineCircularReferences,
				KVStyleStringDictionary = KVStyleStringDictionary,
				ParametricConstructorOverride = ParametricConstructorOverride,
				SerializeNullValues = SerializeNullValues,
				SerializerMaxDepth = SerializerMaxDepth,
				SerializeToLowerCaseNames = SerializeToLowerCaseNames,
				ShowReadOnlyProperties = ShowReadOnlyProperties,
				UseEscapedUnicode = UseEscapedUnicode,
				UseExtensions = UseExtensions,
				UseFastGuid = UseFastGuid,
				UseOptimizedDatasetSchema = UseOptimizedDatasetSchema,
				UseUTCDateTime = UseUTCDateTime,
				UseValuesOfEnums = UseValuesOfEnums,
				UsingGlobalTypes = UsingGlobalTypes,
				AutoConvertStringToNumbers = AutoConvertStringToNumbers,
				OverrideObjectHashCodeChecking = OverrideObjectHashCodeChecking,
				FullyQualifiedDataSetSchema = FullyQualifiedDataSetSchema,
				BadListTypeChecking = BadListTypeChecking
			};
		}
	}
	internal sealed class JsonParser
	{
		private enum Token
		{
			None = -1,
			Curly_Open,
			Curly_Close,
			Squared_Open,
			Squared_Close,
			Colon,
			Comma,
			String,
			Number,
			True,
			False,
			Null,
			PosInfinity,
			NegInfinity,
			NaN
		}

		private readonly char[] json;

		private readonly StringBuilder s = new StringBuilder();

		private Token lookAheadToken = Token.None;

		private int index;

		private bool allownonquotedkey;

		private int _len;

		private SafeDictionary<string, bool> _lookup;

		private SafeDictionary<Type, bool> _seen;

		private bool _parseJsonType;

		private bool _parseType;

		internal JsonParser(string json, bool AllowNonQuotedKeys)
		{
			allownonquotedkey = AllowNonQuotedKeys;
			this.json = json.ToCharArray();
			_len = json.Length;
		}

		private void SetupLookup()
		{
			_lookup = new SafeDictionary<string, bool>();
			_seen = new SafeDictionary<Type, bool>();
			_lookup.Add("$types", value: true);
			_lookup.Add("$type", value: true);
			_lookup.Add("$i", value: true);
			_lookup.Add("$map", value: true);
			_lookup.Add("$schema", value: true);
			_lookup.Add("k", value: true);
			_lookup.Add("v", value: true);
		}

		public unsafe object Decode(Type objtype)
		{
			fixed (char* p = json)
			{
				if (objtype != null && !CheckForTypeInJson(p))
				{
					_parseJsonType = true;
					SetupLookup();
					BuildLookup(objtype);
					if (!_parseJsonType || _lookup.Count() == 7)
					{
						_lookup = null;
					}
				}
				return ParseValue(p);
			}
		}

		private unsafe bool CheckForTypeInJson(char* p)
		{
			int i = 0;
			for (int num = ((_len > 1000) ? 1000 : _len); i < num; i++)
			{
				if (p[i] == '$' && p[i + 1] == 't' && p[i + 2] == 'y' && p[i + 3] == 'p' && p[i + 4] == 'e' && p[i + 5] == 's')
				{
					return true;
				}
			}
			return false;
		}

		private void BuildGenericTypeLookup(Type t)
		{
			if (_seen.TryGetValue(t, out var _))
			{
				return;
			}
			Type[] genericArguments = t.GetGenericArguments();
			foreach (Type type in genericArguments)
			{
				if (!type.IsPrimitive)
				{
					bool flag = type.IsValueType && !type.IsEnum;
					if ((type.IsClass || flag || type.IsAbstract) && type != typeof(string) && type != typeof(DateTime) && type != typeof(Guid))
					{
						BuildLookup(type);
					}
				}
			}
		}

		private void BuildArrayTypeLookup(Type t)
		{
			if (!_seen.TryGetValue(t, out var _))
			{
				bool flag = t.IsValueType && !t.IsEnum;
				if ((t.IsClass || flag) && t != typeof(string) && t != typeof(DateTime) && t != typeof(Guid))
				{
					BuildLookup(t.GetElementType());
				}
			}
		}

		private void BuildLookup(Type objtype)
		{
			if (objtype == null || objtype == typeof(NameValueCollection) || objtype == typeof(StringDictionary) || typeof(IDictionary).IsAssignableFrom(objtype) || _seen.TryGetValue(objtype, out var _))
			{
				return;
			}
			if (objtype.IsGenericType)
			{
				BuildGenericTypeLookup(objtype);
				return;
			}
			if (objtype.IsArray)
			{
				BuildArrayTypeLookup(objtype);
				return;
			}
			_seen.Add(objtype, value: true);
			foreach (KeyValuePair<string, myPropInfo> item in Reflection.Instance.Getproperties(objtype, objtype.FullName, ShowReadOnlyProperties: true))
			{
				Type pt = item.Value.pt;
				_lookup.Add(item.Key, value: true);
				if (pt.IsArray)
				{
					BuildArrayTypeLookup(pt);
				}
				if (pt.IsGenericType)
				{
					if (typeof(IDictionary).IsAssignableFrom(pt))
					{
						_parseJsonType = false;
						break;
					}
					BuildGenericTypeLookup(pt);
				}
				if (pt.FullName.IndexOf("System.") == -1)
				{
					BuildLookup(pt);
				}
			}
		}

		private bool InLookup(string name)
		{
			if (_lookup == null)
			{
				return true;
			}
			bool value;
			return _lookup.TryGetValue(name.ToLowerInvariant(), out value);
		}

		private unsafe Dictionary<string, object> ParseObject(char* p)
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			ConsumeToken();
			while (true)
			{
				switch (LookAhead(p))
				{
				case Token.Comma:
					ConsumeToken();
					continue;
				case Token.Curly_Close:
					ConsumeToken();
					return dictionary;
				}
				string text = ParseKey(p);
				if (NextToken(p) != Token.Colon)
				{
					throw new Exception("Expected colon at index " + index);
				}
				if (_parseJsonType)
				{
					if (text == "$types")
					{
						_parseType = true;
						Dictionary<string, object> dictionary2 = (Dictionary<string, object>)ParseValue(p);
						_parseType = false;
						if (_lookup == null)
						{
							SetupLookup();
						}
						foreach (string key in dictionary2.Keys)
						{
							BuildLookup(Reflection.Instance.GetTypeFromCache(key, badlistChecking: true));
						}
						dictionary[text] = dictionary2;
					}
					else if (text == "$schema")
					{
						_parseType = true;
						object value = ParseValue(p);
						_parseType = false;
						dictionary[text] = value;
					}
					else if (_parseType || InLookup(text))
					{
						dictionary[text] = ParseValue(p);
					}
					else
					{
						SkipValue(p);
					}
				}
				else
				{
					dictionary[text] = ParseValue(p);
				}
			}
		}

		private unsafe void SkipValue(char* p)
		{
			switch (LookAhead(p))
			{
			case Token.Number:
				ParseNumber(p, skip: true);
				break;
			case Token.String:
				SkipString(p);
				break;
			case Token.Curly_Open:
				SkipObject(p);
				break;
			case Token.Squared_Open:
				SkipArray(p);
				break;
			case Token.True:
			case Token.False:
			case Token.Null:
			case Token.PosInfinity:
			case Token.NegInfinity:
			case Token.NaN:
				ConsumeToken();
				break;
			case Token.Curly_Close:
			case Token.Squared_Close:
			case Token.Colon:
			case Token.Comma:
				break;
			}
		}

		private unsafe void SkipObject(char* p)
		{
			ConsumeToken();
			while (true)
			{
				switch (LookAhead(p))
				{
				case Token.Comma:
					ConsumeToken();
					continue;
				case Token.Curly_Close:
					ConsumeToken();
					return;
				}
				SkipString(p);
				if (NextToken(p) != Token.Colon)
				{
					throw new Exception("Expected colon at index " + index);
				}
				SkipValue(p);
			}
		}

		private unsafe void SkipArray(char* p)
		{
			ConsumeToken();
			while (true)
			{
				switch (LookAhead(p))
				{
				case Token.Comma:
					ConsumeToken();
					break;
				case Token.Squared_Close:
					ConsumeToken();
					return;
				default:
					SkipValue(p);
					break;
				}
			}
		}

		private unsafe void SkipString(char* p)
		{
			ConsumeToken();
			int len = _len;
			while (index < len)
			{
				switch (p[index++])
				{
				case '"':
					return;
				case '\\':
					if (p[index++] == 'u')
					{
						index += 4;
					}
					break;
				}
			}
		}

		private unsafe List<object> ParseArray(char* p)
		{
			List<object> list = new List<object>();
			ConsumeToken();
			while (true)
			{
				switch (LookAhead(p))
				{
				case Token.Comma:
					ConsumeToken();
					break;
				case Token.Squared_Close:
					ConsumeToken();
					return list;
				default:
					list.Add(ParseValue(p));
					break;
				}
			}
		}

		private unsafe object ParseValue(char* p)
		{
			switch (LookAhead(p))
			{
			case Token.Number:
				return ParseNumber(p, skip: false);
			case Token.String:
				return ParseString(p);
			case Token.Curly_Open:
				return ParseObject(p);
			case Token.Squared_Open:
				return ParseArray(p);
			case Token.True:
				ConsumeToken();
				return true;
			case Token.False:
				ConsumeToken();
				return false;
			case Token.Null:
				ConsumeToken();
				return null;
			case Token.PosInfinity:
				ConsumeToken();
				return double.PositiveInfinity;
			case Token.NegInfinity:
				ConsumeToken();
				return double.NegativeInfinity;
			case Token.NaN:
				ConsumeToken();
				return double.NaN;
			default:
				throw new Exception("Unrecognized token at index " + index);
			}
		}

		private unsafe string ParseKey(char* p)
		{
			if (!allownonquotedkey || p[index - 1] == '"')
			{
				return ParseString(p);
			}
			ConsumeToken();
			int len = _len;
			int num = 0;
			while (index + num < len)
			{
				if (p[index + num++] == ':')
				{
					string result = UnsafeSubstring(p, index, num - 1).Trim();
					index += num - 1;
					return result;
				}
			}
			throw new Exception("Unable to read key");
		}

		private unsafe string ParseString(char* p)
		{
			char c = p[index - 1];
			ConsumeToken();
			if (s.Length > 0)
			{
				s.Length = 0;
			}
			int len = _len;
			int num = 0;
			while (index + num < len)
			{
				char c2 = p[index + num++];
				if (c2 == '\\')
				{
					break;
				}
				if (c2 == c)
				{
					string result = UnsafeSubstring(p, index, num - 1);
					index += num;
					return result;
				}
			}
			while (index < len)
			{
				char c3 = p[index++];
				if (c3 == c)
				{
					return s.ToString();
				}
				if (c3 != '\\')
				{
					s.Append(c3);
					continue;
				}
				c3 = p[index++];
				switch (c3)
				{
				case 'b':
					s.Append('\b');
					continue;
				case 'f':
					s.Append('\f');
					continue;
				case 'n':
					s.Append('\n');
					continue;
				case 'r':
					s.Append('\r');
					continue;
				case 't':
					s.Append('\t');
					continue;
				case 'u':
				{
					uint num2 = ParseUnicode(p[index], p[index + 1], p[index + 2], p[index + 3]);
					s.Append((char)num2);
					index += 4;
					continue;
				}
				}
				if (c3 == '\r' || c3 == '\n' || c3 == ' ' || c3 == '\t')
				{
					while (c3 == '\r' || c3 == '\n' || c3 == ' ' || c3 == '\t')
					{
						index++;
						c3 = p[index];
						if (c3 == '\r' || c3 == '\n')
						{
							c3 = p[index + 1];
							if (c3 == '\r' || c3 == '\n')
							{
								index += 2;
								c3 = p[index];
							}
							break;
						}
					}
				}
				else
				{
					s.Append(c3);
				}
			}
			return s.ToString();
		}

		private unsafe string ParseJson5String(char* p)
		{
			throw new NotImplementedException();
		}

		private uint ParseSingleChar(char c1, uint multipliyer)
		{
			uint result = 0u;
			if (c1 >= '0' && c1 <= '9')
			{
				result = (uint)(c1 - 48) * multipliyer;
			}
			else if (c1 >= 'A' && c1 <= 'F')
			{
				result = (uint)(c1 - 65 + 10) * multipliyer;
			}
			else if (c1 >= 'a' && c1 <= 'f')
			{
				result = (uint)(c1 - 97 + 10) * multipliyer;
			}
			return result;
		}

		private uint ParseUnicode(char c1, char c2, char c3, char c4)
		{
			uint num = ParseSingleChar(c1, 4096u);
			uint num2 = ParseSingleChar(c2, 256u);
			uint num3 = ParseSingleChar(c3, 16u);
			uint num4 = ParseSingleChar(c4, 1u);
			return num + num2 + num3 + num4;
		}

		private unsafe object ParseNumber(char* p, bool skip)
		{
			ConsumeToken();
			int num = index - 1;
			bool flag = false;
			bool flag2 = false;
			bool flag3 = true;
			if (p[num] == '.')
			{
				flag = true;
			}
			while (index != _len)
			{
				switch (p[index])
				{
				case 'X':
				case 'x':
					index++;
					return ReadHexNumber(p);
				case '+':
				case '-':
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					index++;
					break;
				case 'E':
				case 'e':
					flag2 = true;
					index++;
					break;
				case '.':
					index++;
					flag = true;
					break;
				case 'N':
				case 'n':
					index += 3;
					return double.NaN;
				default:
					flag3 = false;
					break;
				}
				if (index == _len)
				{
					flag3 = false;
				}
				if (!flag3)
				{
					break;
				}
			}
			if (skip)
			{
				return 0;
			}
			int num2 = index - num;
			if (flag2 || num2 > 31)
			{
				return double.Parse(UnsafeSubstring(p, num, num2), NumberFormatInfo.InvariantInfo);
			}
			if (!flag && num2 < 20)
			{
				return Helper.CreateLong(json, num, num2);
			}
			return decimal.Parse(UnsafeSubstring(p, num, num2), NumberFormatInfo.InvariantInfo);
		}

		private unsafe object ReadHexNumber(char* p)
		{
			long num = 0L;
			bool flag = true;
			while (flag && index < _len)
			{
				char c = p[index];
				switch (c)
				{
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					index++;
					num = (num << 4) + (c - 48);
					break;
				case 'a':
				case 'b':
				case 'c':
				case 'd':
				case 'e':
				case 'f':
					index++;
					num = (num << 4) + (c - 97) + 10;
					break;
				case 'A':
				case 'B':
				case 'C':
				case 'D':
				case 'E':
				case 'F':
					index++;
					num = (num << 4) + (c - 65) + 10;
					break;
				default:
					flag = false;
					break;
				}
			}
			return num;
		}

		private unsafe Token LookAhead(char* p)
		{
			if (lookAheadToken != Token.None)
			{
				return lookAheadToken;
			}
			return lookAheadToken = NextTokenCore(p);
		}

		private void ConsumeToken()
		{
			lookAheadToken = Token.None;
		}

		private unsafe Token NextToken(char* p)
		{
			Token result = ((lookAheadToken != Token.None) ? lookAheadToken : NextTokenCore(p));
			lookAheadToken = Token.None;
			return result;
		}

		private unsafe void SkipWhitespace(char* p)
		{
			char c;
			do
			{
				c = p[index];
				if (c == '/' && p[index + 1] == '/')
				{
					index++;
					index++;
					do
					{
						c = p[index];
					}
					while (c != '\r' && c != '\n' && ++index < _len);
				}
				if (c != '/' || p[index + 1] != '*')
				{
					continue;
				}
				index++;
				index++;
				do
				{
					c = p[index];
					if (c == '*' && p[index + 1] == '/')
					{
						index += 2;
						c = p[index];
						break;
					}
				}
				while (++index < _len);
			}
			while ((c == ' ' || c == '\t' || c == '\n' || c == '\r') && ++index < _len);
		}

		private unsafe Token NextTokenCore(char* p)
		{
			int len = _len;
			SkipWhitespace(p);
			if (index == len)
			{
				throw new Exception("Reached end of string unexpectedly");
			}
			char c = p[index];
			index++;
			switch (c)
			{
			case '{':
				return Token.Curly_Open;
			case '}':
				return Token.Curly_Close;
			case '[':
				return Token.Squared_Open;
			case ']':
				return Token.Squared_Close;
			case ',':
				return Token.Comma;
			case '"':
			case '\'':
				return Token.String;
			case '-':
				if (p[index] == 'i' || p[index] == 'I')
				{
					index += 8;
					return Token.NegInfinity;
				}
				return Token.Number;
			case '+':
				if (p[index] == 'i' || p[index] == 'I')
				{
					index += 8;
					return Token.PosInfinity;
				}
				return Token.Number;
			case '.':
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				return Token.Number;
			case ':':
				return Token.Colon;
			case 'I':
			case 'i':
				index += 7;
				return Token.PosInfinity;
			case 'f':
				if (len - index >= 4 && p[index] == 'a' && p[index + 1] == 'l' && p[index + 2] == 's' && p[index + 3] == 'e')
				{
					index += 4;
					return Token.False;
				}
				break;
			case 't':
				if (len - index >= 3 && p[index] == 'r' && p[index + 1] =