Decompiled source of FastLink v1.4.1

FastLink.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FastLink.Patches;
using FastLink.Util;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: Guid("089A0531-9441-424D-B144-98C1CE1D4D41")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("FastLink")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("FastLink")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.4.1")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<21b4f8c1-f088-4857-b426-ecaad9a51e9d>Embedded]
	internal sealed class <21b4f8c1-f088-4857-b426-ecaad9a51e9d>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<21b4f8c1-f088-4857-b426-ecaad9a51e9d>Embedded]
	internal sealed class <0f8534b8-2fce-4f9b-bb15-62b1c207935b>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <0f8534b8-2fce-4f9b-bb15-62b1c207935b>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <0f8534b8-2fce-4f9b-bb15-62b1c207935b>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<21b4f8c1-f088-4857-b426-ecaad9a51e9d>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace FastLink
{
	[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
	[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
	public class Definition
	{
		public string serverName;

		public ushort port { get; set; }

		public string address { get; set; }

		public bool ispvp { get; set; }

		public bool iscrossplay { get; set; }

		public string password { get; set; } = "";


		public bool iswhitelisted { get; set; }

		public static IEnumerable<Definition> Parse(string yaml)
		{
			return new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, Definition>>(yaml)
				.Select([<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)] (KeyValuePair<string, Definition> kv) =>
				{
					Definition value = kv.Value;
					value.serverName = kv.Key;
					return value;
				});
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			stringBuilder.Append(Environment.NewLine);
			if (FastLinkPlugin.HideIP.Value == FastLinkPlugin.Toggle.On)
			{
				stringBuilder.Append("Address: Hidden In Configs");
				stringBuilder.Append(Environment.NewLine);
				stringBuilder.Append("Port: Hidden In Configs");
			}
			else
			{
				stringBuilder.Append("Address: " + address);
				stringBuilder.Append(Environment.NewLine);
				stringBuilder.Append($"Port: {port}");
			}
			stringBuilder.Append(Environment.NewLine);
			stringBuilder.Append($"PvP: {ispvp}");
			stringBuilder.Append(Environment.NewLine);
			stringBuilder.Append($"Crossplay Enabled: {iscrossplay}");
			if (FastLinkPlugin.ShowPasswordInTooltip.Value == FastLinkPlugin.Toggle.On)
			{
				stringBuilder.Append(Environment.NewLine);
				stringBuilder.Append("Password: " + password);
			}
			stringBuilder.Append(Environment.NewLine);
			stringBuilder.Append($"Uses Whitelisted Player List: {iswhitelisted}");
			return stringBuilder.ToString();
		}
	}
	[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
	[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
	[BepInPlugin("Azumatt.FastLink", "FastLink", "1.4.1")]
	public class FastLinkPlugin : BaseUnityPlugin
	{
		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)]
		public enum Toggle
		{
			Off,
			On
		}

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? HideDefaultButton;

			public bool? HideSettingName;

			public string Description = "";
		}

		internal const string ModName = "FastLink";

		internal const string ModVersion = "1.4.1";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.FastLink";

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

		private static string ConfigFileFullPath;

		internal static FastLinkPlugin instance;

		internal readonly Harmony _harmony = new Harmony("Azumatt.FastLink");

		public static readonly ManualLogSource FastLinkLogger;

		public static ConfigEntry<Vector2> UIAnchor;

		public static ConfigEntry<Vector2> MerchUIAnchor;

		public static ConfigEntry<Vector3> LocalScale;

		public static ConfigEntry<Toggle> Sort;

		public static ConfigEntry<Toggle> HideIP;

		public static ConfigEntry<Toggle> ShowPasswordPrompt;

		public static ConfigEntry<Toggle> ShowPasswordInTooltip;

		private const int WindowId = -70;

		internal static Rect ScreenRect;

		internal static string EditorText;

		internal static Vector2 SettingWindowScrollPos;

		internal static bool RichTextOn;

		private Rect ContentWindowRect { get; set; }

		private void Awake()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Expected O, but got Unknown
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Expected O, but got Unknown
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Expected O, but got Unknown
			instance = this;
			((BaseUnityPlugin)this).Config.Bind<string>("General", "FastLink URL", "https://valheim.thunderstore.io/package/Azumatt/FastLink/", new ConfigDescription("Link to the mod page", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					HideSettingName = true,
					HideDefaultButton = true,
					Description = "Edit the " + Servers.ConfigFileName + " directly from the configuration manager.",
					CustomDrawer = Functions.EditServersButton
				}
			}));
			Sort = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "Sort List Alphabetically", Toggle.On, new ConfigDescription("Sorts the Server List Alphabetically. If disabled, the list will be displayed in the same order as the file. NOTE: If you are using colors in your server name, if on, it will still sort but the color you use will have an affect on on the order.", (AcceptableValueBase)null, Array.Empty<object>()));
			Sort.SettingChanged += [<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)] (object _, EventArgs _) =>
			{
				ReadNewServers(null, null);
			};
			HideIP = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "Hide the IP in the panel", Toggle.Off, new ConfigDescription("Turn on to hide the IP in the connection panel at the main menu. Also hides it in the tooltip", (AcceptableValueBase)null, Array.Empty<object>()));
			HideIP.SettingChanged += [<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)] (object _, EventArgs _) =>
			{
				ReadNewServers(null, null);
			};
			UIAnchor = ((BaseUnityPlugin)this).Config.Bind<Vector2>("UI", "Position of the UI", new Vector2(429f, 172f), new ConfigDescription("Sets the anchor position of the UI. You can drag it by left clicking on the title and dragging. Manual setting here is also available.", (AcceptableValueBase)null, Array.Empty<object>()));
			UIAnchor.SettingChanged += SaveAndReset;
			MerchUIAnchor = ((BaseUnityPlugin)this).Config.Bind<Vector2>("UI", "Position of the Merch UI", new Vector2(-121f, -89f), new ConfigDescription("Sets the anchor position of the Merch UI. You can drag it by left clicking on the title and dragging. Manual setting here is also available. Vanilla is -200, -155", (AcceptableValueBase)null, Array.Empty<object>()));
			MerchUIAnchor.SettingChanged += SaveAndReset;
			LocalScale = ((BaseUnityPlugin)this).Config.Bind<Vector3>("UI", "LocalScale of the UI", new Vector3(1f, 1f, 1f), new ConfigDescription("Sets the local scale the UI. This is overall size of the UI. Defaults to vanilla JoinGame UI size. I prefer 0.85, 0.85, 0.85", (AcceptableValueBase)null, Array.Empty<object>()));
			LocalScale.SettingChanged += SaveAndReset;
			ShowPasswordPrompt = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "Show Password Prompt", Toggle.Off, new ConfigDescription("Set to true if you want to still show the password prompt to the user. This is for servers that have a password but don't wish to use the file to keep the password.", (AcceptableValueBase)null, Array.Empty<object>()));
			ShowPasswordInTooltip = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "Show Password In Tooltip", Toggle.Off, new ConfigDescription("Set to true if you want to show the password inside the tooltip hover.", (AcceptableValueBase)null, Array.Empty<object>()));
			ShowPasswordInTooltip.SettingChanged += [<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)] (object _, EventArgs _) =>
			{
				ReadNewServers(null, null);
			};
			LoadTooltipAsset("fastlink");
			_harmony.PatchAll();
			SetupWatcher();
		}

		private void Start()
		{
			Game.isModded = true;
		}

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

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

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

		private void ReadNewServers(object sender, FileSystemEventArgs e)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!File.Exists(Servers.ConfigPath))
			{
				return;
			}
			try
			{
				FastLinkLogger.LogDebug((object)"Reloading Server List");
				SetupGui.Connecting = null;
				foreach (GameObject mServerListElement in SetupGui.MServerListElements)
				{
					Object.Destroy((Object)(object)mServerListElement);
				}
				SetupGui.MServerListElements.Clear();
				Servers.Init();
				Functions.AbortConnect();
				Functions.PopulateServerList(SetupGui.Fastlink);
				Functions.UpdateServerList();
				SetupGui.MJoinServer = null;
			}
			catch
			{
				if (!((Object)(object)Player.m_localPlayer == (Object)null))
				{
					Scene activeScene = SceneManager.GetActiveScene();
					if (!(((Scene)(ref activeScene)).name != "main"))
					{
						return;
					}
				}
				FastLinkLogger.LogError((object)("There was an issue loading your " + Servers.ConfigFileName));
				FastLinkLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private void SaveAndReset(object sender, EventArgs e)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Config.Save();
			SetupGui.FastlinkRootGo.GetComponent<RectTransform>().anchoredPosition = new Vector2(UIAnchor.Value.x, UIAnchor.Value.y);
			SetupGui.MerchRootGo.GetComponent<RectTransform>().anchoredPosition = new Vector2(MerchUIAnchor.Value.x, MerchUIAnchor.Value.y);
			SetupGui.Fastlink.gameObject.transform.localScale = LocalScale.Value;
		}

		private void LoadTooltipAsset(string bundleName)
		{
			AssetBundle assetBundleFromResources = GetAssetBundleFromResources(bundleName);
			SetupGui.FastlinkTooltip = assetBundleFromResources.LoadAsset<GameObject>("FastLinkTooltip");
			if (assetBundleFromResources != null)
			{
				assetBundleFromResources.Unload(false);
			}
		}

		private static AssetBundle GetAssetBundleFromResources(string filename)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single([<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(0)] (string str) => str.EndsWith(filename));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			return AssetBundle.LoadFromStream(stream);
		}

		private void Update()
		{
			Functions.ShouldShowCursor();
		}

		private void LateUpdate()
		{
			Functions.ShouldShowCursor();
		}

		private void OnGUI()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			if (EditorText.Length > 0)
			{
				Functions.ShouldShowCursor();
				int num = Mathf.Min(Screen.width, 1000);
				int num2 = ((Screen.height < 560) ? Screen.height : (Screen.height - 200));
				int num3 = Mathf.RoundToInt((float)(Screen.width - num) / 2f);
				int num4 = Mathf.RoundToInt((float)(Screen.height - num2) / 2f);
				ContentWindowRect = new Rect((float)num3, (float)num4, (float)num, (float)num2);
				ScreenRect = new Rect(0f, 0f, (float)Screen.width, (float)Screen.height);
				GUILayout.Window(-70, ContentWindowRect, new WindowFunction(DoServerWindow), "FastLink Servers", Array.Empty<GUILayoutOption>());
			}
		}

		private void DoServerWindow(int id)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Invalid comparison between Unknown and I4
			Functions.MakeShitDarkerInABadWay();
			bool flag = GUI.GetNameOfFocusedControl() == "FastLinkEditor";
			if (flag)
			{
				EventType type = Event.current.type;
				bool flag2 = type - 4 <= 1;
				flag = flag2;
			}
			if (flag && Event.current.isKey)
			{
				TextEditor val = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
				if ((int)Event.current.keyCode == 9)
				{
					if ((int)Event.current.type == 5)
					{
						val.text += "    ";
						val.MoveLineEnd();
						EditorText = val.text;
					}
					Event.current.Use();
				}
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUI.backgroundColor = Color.white;
			Functions.BuildContentScroller();
			GUI.backgroundColor = Color.green;
			GUI.contentColor = Color.white;
			Functions.BuildButtons();
			GUILayout.EndHorizontal();
		}

		static FastLinkPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			instance = null;
			FastLinkLogger = Logger.CreateLogSource("FastLink");
			UIAnchor = null;
			MerchUIAnchor = null;
			LocalScale = null;
			Sort = null;
			HideIP = null;
			ShowPasswordPrompt = null;
			ShowPasswordInTooltip = null;
			EditorText = "";
		}
	}
}
namespace FastLink.Util
{
	public class DragControl : MonoBehaviour, IDragHandler, IEventSystemHandler, IEndDragHandler
	{
		[SerializeField]
		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(1)]
		private RectTransform dragRectTransform = new RectTransform();

		private void Start()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			dragRectTransform = ((Component)this).GetComponent<RectTransform>();
			dragRectTransform.anchoredPosition = FastLinkPlugin.UIAnchor.Value;
		}

		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		public void OnDrag(PointerEventData eventData)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = dragRectTransform;
			obj.anchoredPosition += eventData.delta;
		}

		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		public void OnEndDrag(PointerEventData eventData)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			FastLinkPlugin.UIAnchor.Value = dragRectTransform.anchoredPosition;
		}
	}
	public class MerchAreaDragControl : MonoBehaviour, IDragHandler, IEventSystemHandler, IEndDragHandler
	{
		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(1)]
		[SerializeField]
		private RectTransform dragRectTransform = new RectTransform();

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(1)]
		[SerializeField]
		private Button button;

		private void Start()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			dragRectTransform = ((Component)this).GetComponent<RectTransform>();
			button = ((Component)this).GetComponent<Button>();
			dragRectTransform.anchoredPosition = FastLinkPlugin.MerchUIAnchor.Value;
		}

		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		public void OnDrag(PointerEventData eventData)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			((Selectable)button).interactable = false;
			RectTransform obj = dragRectTransform;
			obj.anchoredPosition += eventData.delta;
		}

		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		public void OnEndDrag(PointerEventData eventData)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			((Selectable)button).interactable = true;
			FastLinkPlugin.MerchUIAnchor.Value = dragRectTransform.anchoredPosition;
		}
	}
	[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
	[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
	public static class Functions
	{
		internal static void DestroyAll(GameObject thing)
		{
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("FilterField")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("Refresh")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("Server help")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("Back")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("Join")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("FavoriteTab")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("RecentTab")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("FriendsTab")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("CommunityTab")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("Add server")).gameObject);
			Object.DestroyImmediate((Object)(object)((Component)thing.transform.Find("FavoriteButton")).gameObject);
		}

		internal static void MerchButton()
		{
			SetupGui.MerchRootGo = GameObject.Find("GUI/StartGui/Menu/StartGui_MerchButton").gameObject;
			if ((Object)(object)SetupGui.MerchRootGo != (Object)null)
			{
				SetupGui.MerchRootGo.AddComponent<MerchAreaDragControl>();
			}
		}

		internal static void PopulateServerList(GameObject linkpanel)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			FastLinkPlugin.FastLinkLogger.LogDebug((object)"POPULATE SERVER LIST");
			SetupGui.MServerListElement = ((Component)linkpanel.transform.Find("ServerList/ServerElementSteamCrossplay")).gameObject;
			((Behaviour)((Component)linkpanel.transform.Find("ServerList")).gameObject.GetComponent<Image>()).enabled = false;
			GameObject gameObject = GameObject.Find("GuiRoot/GUI/StartGui/FastLink/JoinPanel(Clone)/ServerList/ListRoot").gameObject;
			gameObject.gameObject.transform.localScale = new Vector3(1f, 0.8f, 1f);
			SetupGui.MServerListRoot = gameObject.GetComponent<RectTransform>();
			gameObject.gameObject.GetComponent<RectTransform>().pivot = new Vector2(gameObject.gameObject.GetComponent<RectTransform>().pivot.x, 1f);
			SetupGui.MServerCount = ((Component)linkpanel.transform.Find("serverCount")).gameObject.GetComponent<TextMeshProUGUI>();
			Rect rect = SetupGui.MServerListRoot.rect;
			SetupGui.MServerListBaseSize = ((Rect)(ref rect)).height;
		}

		internal static void UpdateServerList()
		{
			FastLinkPlugin.FastLinkLogger.LogDebug((object)"UPDATE SERVER LIST");
			SetupGui.MServerList.Clear();
			if (SetupGui.Connecting != null)
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"Connecting not null");
				AbortConnect();
			}
			else if (Servers.entries.Count > 0)
			{
				foreach (Definition entry in Servers.entries)
				{
					SetupGui.MServerList.Add(entry);
				}
			}
			else
			{
				FastLinkPlugin.FastLinkLogger.LogError((object)"No servers defined");
				FastLinkPlugin.FastLinkLogger.LogError((object)("Please create this file " + Servers.ConfigPath));
			}
			if (FastLinkPlugin.Sort.Value == FastLinkPlugin.Toggle.On)
			{
				SetupGui.MServerList.Sort((Definition a, Definition b) => string.Compare(a?.serverName, b?.serverName, StringComparison.Ordinal));
			}
			if (SetupGui.MJoinServer != null && !SetupGui.MServerList.Contains(SetupGui.MJoinServer))
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"Server list does not contain selected server, clearing selected server");
				SetupGui.MJoinServer = null;
			}
			UpdateServerListGui(centerSelection: false);
		}

		private static void UpdateServerListGui(bool centerSelection)
		{
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			if (SetupGui.MServerList.Count != SetupGui.MServerListElements.Count)
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"UPDATE SERVER LIST GUI");
				foreach (GameObject mServerListElement in SetupGui.MServerListElements)
				{
					Object.DestroyImmediate((Object)(object)mServerListElement);
				}
				SetupGui.MServerListElements.Clear();
				SetupGui.MServerListRoot.SetSizeWithCurrentAnchors((Axis)1, Mathf.Max(SetupGui.MServerListBaseSize, (float)SetupGui.MServerList.Count * SetupGui.m_serverListElementStep));
				for (int i = 0; i < SetupGui.MServerList.Count; i++)
				{
					GameObject gameObject = Object.Instantiate<GameObject>(SetupGui.MServerListElement, (Transform)(object)SetupGui.MServerListRoot);
					gameObject.SetActive(true);
					Transform transform = gameObject.transform;
					((RectTransform)((transform is RectTransform) ? transform : null)).anchoredPosition = new Vector2(0f, (float)i * (0f - SetupGui.m_serverListElementStep));
					((UnityEvent)gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
					{
						OnSelectedServer(gameObject);
					});
					if (!SetupGui.MServerListElements.Contains(gameObject))
					{
						SetupGui.MServerListElements.Add(gameObject);
					}
					string text = ((SetupGui.MServerListElements.Count > 1) ? " Servers" : " Server");
					if ((Object)(object)SetupGui.MServerCount != (Object)null)
					{
						((TMP_Text)SetupGui.MServerCount).text = SetupGui.MServerListElements.Count + text;
					}
				}
			}
			FastLinkPlugin.FastLinkLogger.LogDebug((object)$"ServerList count: {SetupGui.MServerList.Count}");
			for (int j = 0; j < SetupGui.MServerList.Count; j++)
			{
				Definition definition = SetupGui.MServerList[j];
				GameObject val = SetupGui.MServerListElements?[j];
				if (!((Object)(object)val == (Object)null))
				{
					val.GetComponentInChildren<TMP_Text>().text = $"{j + 1}. {definition.serverName}";
					val.GetComponentInChildren<UITooltip>().Set(definition.serverName, definition.ToString(), (RectTransform)null, default(Vector2));
					string text2 = (((Component)val.transform.Find("players")).GetComponent<TMP_Text>().text = string.Empty);
					TMP_Text component = ((Component)val.transform.Find("modifiers")).GetComponent<TMP_Text>();
					TMP_Text component2 = ((Component)val.transform.Find("version")).GetComponent<TMP_Text>();
					if (FastLinkPlugin.HideIP.Value == FastLinkPlugin.Toggle.On)
					{
						component.text = "Hidden";
						component2.text = "";
					}
					else
					{
						component.text = definition.address;
						component2.text = definition.port.ToString();
					}
					((Component)val.transform.Find("Private")).gameObject.SetActive(definition.password.Length > 1);
					((Component)val.transform.Find("PVP")).gameObject.SetActive(definition.ispvp);
					((Component)val.transform.Find("crossplay")).gameObject.SetActive(definition.iscrossplay);
					Transform obj = val.transform.Find("selected");
					bool active = SetupGui.MJoinServer != null && SetupGui.MJoinServer.Equals(definition);
					((Component)obj).gameObject.SetActive(active);
				}
			}
		}

		private static void Connect(Definition server)
		{
			FastLinkPlugin.FastLinkLogger.LogDebug((object)"DO CONNECT");
			SetupGui.Connecting = server;
			try
			{
				if (!JoinServer(IPAddress.Parse(server.address), server.port))
				{
					SetupGui.Connecting = null;
					FastLinkPlugin.FastLinkLogger.LogError((object)"Server address was not valid");
				}
			}
			catch (FormatException)
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)("Resolving: " + server.address));
				try
				{
					SetupGui.ResolveTask = Dns.GetHostEntryAsync(server.address);
					FastLinkPlugin.FastLinkLogger.LogDebug((object)$"Resolving after task: {SetupGui.ResolveTask.Result.AddressList[0]}");
				}
				catch (Exception)
				{
					FastLinkPlugin.FastLinkLogger.LogError((object)("You are trying to resolve the IP : " + server.address + ", but something is happening causing it to not work properly."));
				}
				if (SetupGui.ResolveTask == null)
				{
					FastLinkPlugin.FastLinkLogger.LogError((object)"Your resolve task was null, fix it you idiot");
				}
				else if (SetupGui.ResolveTask.IsFaulted)
				{
					FastLinkPlugin.FastLinkLogger.LogError((object)$"Error resolving IP: {SetupGui.ResolveTask.Exception}");
					FastLinkPlugin.FastLinkLogger.LogError((object)((SetupGui.ResolveTask.Exception?.InnerException != null) ? SetupGui.ResolveTask.Exception.InnerException.Message : SetupGui.ResolveTask.Exception?.Message));
					SetupGui.ResolveTask = null;
					SetupGui.Connecting = null;
				}
				else if (SetupGui.ResolveTask.IsCanceled)
				{
					FastLinkPlugin.FastLinkLogger.LogError((object)("Error CANCELED: " + SetupGui.ResolveTask.Result.HostName));
					SetupGui.ResolveTask = null;
					SetupGui.Connecting = null;
				}
				else if (SetupGui.ResolveTask.IsCompleted)
				{
					FastLinkPlugin.FastLinkLogger.LogDebug((object)("COMPLETE: " + server.address));
					IPAddress[] addressList = SetupGui.ResolveTask.Result.AddressList;
					int num = 0;
					if (num < addressList.Length)
					{
						IPAddress iPAddress = addressList[num];
						FastLinkPlugin.FastLinkLogger.LogDebug((object)$"Resolved Completed: {iPAddress}");
						SetupGui.ResolveTask = null;
						if (!JoinServer(iPAddress, server.port))
						{
							SetupGui.Connecting = null;
							FastLinkPlugin.FastLinkLogger.LogError((object)"Server DNS resolved to invalid address");
						}
					}
				}
				else
				{
					SetupGui.ResolveTask = null;
					SetupGui.Connecting = null;
					FastLinkPlugin.FastLinkLogger.LogError((object)"Server DNS resolved to no valid addresses");
				}
			}
		}

		private static bool JoinServer(IPAddress address, ushort port)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			string text = $"{((address.AddressFamily == AddressFamily.InterNetworkV6) ? $"[{address}]" : $"{address}")}:{port}";
			FastLinkPlugin.FastLinkLogger.LogDebug((object)("Server and Port passed into JoinServer: " + text));
			if (address.AddressFamily == AddressFamily.InterNetwork)
			{
				address = address.MapToIPv6();
			}
			if (address.AddressFamily != AddressFamily.InterNetworkV6)
			{
				return false;
			}
			SteamNetworkingIPAddr val = default(SteamNetworkingIPAddr);
			((SteamNetworkingIPAddr)(ref val)).SetIPv6(address.GetAddressBytes(), port);
			ZSteamMatchmaking.instance.m_joinData = (ServerJoinData)new ServerJoinDataDedicated(((SteamNetworkingIPAddr)(ref val)).GetIPv4(), port);
			return true;
		}

		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(2)]
		public static string CurrentPass()
		{
			return SetupGui.Connecting?.password;
		}

		public static void AbortConnect()
		{
			FastLinkPlugin.FastLinkLogger.LogDebug((object)"ABORT CONNECT");
			SetupGui.Connecting = null;
			SetupGui.ResolveTask = null;
		}

		private static void OnSelectedServer(GameObject gameObject)
		{
			SetupGui.MJoinServer = SetupGui.MServerList[FindSelectedServer((Object)(object)gameObject)];
			Connect(new Definition
			{
				serverName = SetupGui.MJoinServer.serverName,
				address = SetupGui.MJoinServer.address,
				port = SetupGui.MJoinServer.port,
				password = SetupGui.MJoinServer.password
			});
			UpdateServerListGui(centerSelection: false);
		}

		private static int FindSelectedServer(Object button)
		{
			try
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"FIND SELECTED");
				for (int i = 0; i < SetupGui.MServerListElements.Count; i++)
				{
					if (i >= 0 && i < SetupGui.MServerListElements.Count && (Object)(object)SetupGui.MServerListElements[i] == button)
					{
						return i;
					}
				}
				return -1;
			}
			catch (Exception arg)
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)$"The issues were found here: {arg}");
			}
			return 1;
		}

		internal static void ShouldShowCursor()
		{
			if (FastLinkPlugin.EditorText.Length > 1)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
			}
		}

		internal static void EditServersButton(ConfigEntryBase _)
		{
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			if (File.Exists(Servers.ConfigPath) && Servers.entries.Count > 0 && GUILayout.Button("Edit Servers", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				FastLinkPlugin.EditorText = File.ReadAllText(Servers.ConfigPath);
			}
			GUILayout.EndVertical();
		}

		internal static void SaveFromEditor()
		{
			try
			{
				File.WriteAllText(Servers.ConfigPath, FastLinkPlugin.EditorText);
				FastLinkPlugin.FastLinkLogger.LogInfo((object)"Saved servers, rebuilding list");
			}
			catch (Exception arg)
			{
				FastLinkPlugin.FastLinkLogger.LogError((object)$"Error saving servers: {arg}");
			}
		}

		internal static void MakeShitDarkerInABadWay()
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < 6; i++)
			{
				GUI.Box(FastLinkPlugin.ScreenRect, (Texture)(object)Texture2D.blackTexture);
			}
		}

		internal static void BuildContentScroller()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			FastLinkPlugin.SettingWindowScrollPos = GUILayout.BeginScrollView(FastLinkPlugin.SettingWindowScrollPos, false, true, Array.Empty<GUILayoutOption>());
			GUI.SetNextControlName("FastLinkEditor");
			GUIStyle val = new GUIStyle
			{
				richText = true
			};
			val.normal.textColor = Color.white;
			val.normal.background = Texture2D.blackTexture;
			GUIStyle val2 = val;
			if (FastLinkPlugin.RichTextOn)
			{
				FastLinkPlugin.EditorText = GUILayout.TextArea(FastLinkPlugin.EditorText, val2, (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.ExpandWidth(true),
					GUILayout.ExpandHeight(true)
				});
			}
			else
			{
				FastLinkPlugin.EditorText = GUILayout.TextArea(FastLinkPlugin.EditorText, (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.ExpandWidth(true),
					GUILayout.ExpandHeight(true)
				});
			}
			GUILayout.EndScrollView();
		}

		internal static void BuildButtons()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.ExpandWidth(true),
				GUILayout.ExpandHeight(true)
			});
			if (GUILayout.Button(Localization.instance.Localize("$settings_apply"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				SaveFromEditor();
				FastLinkPlugin.EditorText = "";
			}
			GUI.backgroundColor = Color.red;
			GUI.contentColor = Color.white;
			if (GUILayout.Button("Discard", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				FastLinkPlugin.EditorText = "";
			}
			GUILayout.Space(20f);
			GUI.backgroundColor = Color.cyan;
			GUI.contentColor = Color.white;
			if (GUILayout.Button(FastLinkPlugin.RichTextOn ? "No Rich Text" : "Use Rich Text", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				FastLinkPlugin.RichTextOn = !FastLinkPlugin.RichTextOn;
			}
			GUILayout.EndVertical();
		}

		private static void DoQuickLoad(string fileName, FileSource fileSource)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			string @string = PlayerPrefs.GetString("world");
			Game.SetProfile(fileName, fileSource);
			if (string.IsNullOrEmpty(@string))
			{
				return;
			}
			FastLinkPlugin.FastLinkLogger.LogDebug((object)("got world name " + @string));
			FejdStartup.instance.UpdateCharacterList();
			FejdStartup.instance.UpdateWorldList(true);
			bool isOn = FejdStartup.instance.m_publicServerToggle.isOn;
			bool isOn2 = FejdStartup.instance.m_openServerToggle.isOn;
			string text = ((TMP_InputField)FejdStartup.instance.m_serverPassword).text;
			World val = FejdStartup.instance.FindWorld(@string);
			if (val != null)
			{
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"got world");
				ZNet.SetServer(true, isOn2, isOn, @string, text, val);
				ZNet.ResetServerHost();
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"Set server");
				try
				{
					string text2 = $"open:{isOn2},public:{isOn}";
					Gogan.LogEvent("Menu", "WorldStart", text2, 0L);
				}
				catch
				{
					FastLinkPlugin.FastLinkLogger.LogDebug((object)"Error calling Gogan... oh well");
				}
				FastLinkPlugin.FastLinkLogger.LogDebug((object)"transitioning...");
				FejdStartup.instance.TransitionToMainScene();
			}
		}
	}
}
namespace FastLink.Patches
{
	[HarmonyPatch(typeof(FejdStartup), "OnSelelectCharacterBack")]
	internal class PatchCharacterBack
	{
		private static void Postfix()
		{
			if (Object.op_Implicit((Object)(object)SetupGui.Fastlink))
			{
				Functions.AbortConnect();
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "Start")]
	internal static class FejdStartupStartPatch
	{
		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		private static void Postfix(FejdStartup __instance)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			FastLinkPlugin.instance._harmony.Patch((MethodBase)(((int)ZNet.m_onlineBackend == 1) ? AccessTools.DeclaredMethod(typeof(ZPlayFabMatchmaking), "OnFailed", (Type[])null, (Type[])null) : AccessTools.DeclaredMethod(typeof(ZSteamMatchmaking), "OnJoinServerFailed", (Type[])null, (Type[])null)), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FejdStartupStartPatch), "Failed", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void Failed()
		{
			if (Object.op_Implicit((Object)(object)SetupGui.Fastlink))
			{
				JoinServerFailed();
			}
		}

		private static void JoinServerFailed()
		{
			FastLinkPlugin.FastLinkLogger.LogError((object)"Server connection failed");
			SetupGui.Connecting = null;
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_ClientHandshake")]
	internal class PatchPasswordPrompt
	{
		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		private static bool Prefix(ZNet __instance, ZRpc rpc, bool needPassword, string serverPasswordSalt)
		{
			if (FastLinkPlugin.ShowPasswordPrompt.Value == FastLinkPlugin.Toggle.On)
			{
				return true;
			}
			string text = Functions.CurrentPass();
			if (string.IsNullOrEmpty(text))
			{
				return true;
			}
			ZNet.m_serverPasswordSalt = serverPasswordSalt;
			if (needPassword)
			{
				string text2 = text.Aggregate("", (string current, char characters) => current + "*");
				FastLinkPlugin.FastLinkLogger.LogDebug((object)("Authenticating with saved password...REDACTED: " + text2));
				((Component)__instance.m_connectingDialog).gameObject.SetActive(false);
				__instance.SendPeerInfo(rpc, text);
				return false;
			}
			FastLinkPlugin.FastLinkLogger.LogDebug((object)"Server didn't want password?");
			return true;
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "LoadMainScene")]
	internal static class FejdStartup_LoadMainScene_Patch
	{
		[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
		private static void Postfix(FejdStartup __instance)
		{
			if (SetupGui.Fastlink.activeSelf)
			{
				SetupGui.Fastlink.SetActive(false);
			}
		}
	}
	[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
	[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
	[HarmonyPatch(typeof(FejdStartup), "SetupGui")]
	internal class SetupGui
	{
		public static GameObject Fastlink = null;

		public static GameObject FastlinkTooltip = null;

		public static GameObject FastlinkRootGo = null;

		public static GameObject MerchRootGo = null;

		public static readonly List<Definition> MServerList = new List<Definition>();

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(2)]
		public static Definition MJoinServer = new Definition();

		public static readonly List<GameObject> MServerListElements = new List<GameObject>();

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(2)]
		public static TextMeshProUGUI MServerCount;

		public static GameObject MServerListElement = new GameObject();

		public static float m_serverListElementStep = 28f;

		public static RectTransform MServerListRoot = new RectTransform();

		public static float MServerListBaseSize;

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(new byte[] { 2, 1 })]
		public static Task<IPHostEntry> ResolveTask;

		[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(2)]
		public static Definition Connecting;

		private static void Postfix(FejdStartup __instance)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			Connecting = null;
			foreach (GameObject mServerListElement in MServerListElements)
			{
				Object.DestroyImmediate((Object)(object)mServerListElement);
			}
			MServerListElements.Clear();
			Servers.Init();
			FastlinkRootGo = new GameObject("FastLink");
			FastlinkRootGo.AddComponent<RectTransform>();
			FastlinkRootGo.AddComponent<DragControl>();
			FastlinkRootGo.transform.SetParent(GameObject.Find("GuiRoot/GUI/StartGui").transform);
			Fastlink = Object.Instantiate<GameObject>(GameObject.Find("GUI/StartGui/StartGame/Panel/JoinPanel").gameObject, FastlinkRootGo.transform);
			Object.DestroyImmediate((Object)(object)Fastlink.gameObject.GetComponent<TabHandler>());
			Object.DestroyImmediate((Object)(object)Fastlink.gameObject.GetComponent<ServerList>());
			Object.DestroyImmediate((Object)(object)Fastlink.gameObject.GetComponent<UIGamePad>());
			Fastlink.transform.SetParent(FastlinkRootGo.transform);
			Fastlink.gameObject.transform.localScale = FastLinkPlugin.LocalScale.Value;
			FastlinkRootGo.transform.position = Vector2.op_Implicit(new Vector2(FastLinkPlugin.UIAnchor.Value.x, FastLinkPlugin.UIAnchor.Value.y));
			if (!Fastlink.activeSelf)
			{
				Fastlink.SetActive(true);
			}
			Functions.MerchButton();
			((Component)Fastlink.transform.Find("topic")).GetComponent<TMP_Text>().text = "Fast Link";
			FastlinkTooltip.gameObject.SetActive(false);
			try
			{
				Functions.DestroyAll(Fastlink);
			}
			catch (Exception arg)
			{
				FastLinkPlugin.FastLinkLogger.LogError((object)$"Problem in the destroying of things!{arg}");
				throw;
			}
			Functions.PopulateServerList(Fastlink);
			Functions.UpdateServerList();
		}
	}
	[<a776eb29-2c8d-4b9c-9581-ea9a0ce10fdf>NullableContext(1)]
	[<0f8534b8-2fce-4f9b-bb15-62b1c207935b>Nullable(0)]
	internal class Servers
	{
		internal static string ConfigFileName = "Azumatt.FastLink_servers.yml";

		public static string ConfigPath;

		public static List<Definition> entries;

		public static void Init()
		{
			entries.Clear();
			try
			{
				if (!File.Exists(ConfigPath))
				{
					using StreamWriter streamWriter = File.CreateText(ConfigPath);
					streamWriter.Write((object?)new StringBuilder().AppendLine("# Configure your servers for Azumatt's FastLink mod in this file.").AppendLine("# Servers are automatically sorted alphabetically when shown in the list.").AppendLine("# This file live updates the in-game listing. Feel free to change it while in the main menu.")
						.AppendLine("")
						.AppendLine("Example Server:")
						.AppendLine("  address: example.com")
						.AppendLine("  port: 1234")
						.AppendLine("  password: somepassword")
						.AppendLine("")
						.AppendLine("Some IPv6 Server:")
						.AppendLine("  address: 2606:2800:220:1:248:1893:25c8:1946")
						.AppendLine("  port: 4023")
						.AppendLine("  password: a password with spaces")
						.AppendLine("")
						.AppendLine("Passwordless IPv4 Server:")
						.AppendLine("  address: 93.184.216.34")
						.AppendLine("  port: 9999")
						.AppendLine("")
						.AppendLine("# You can optionally change the color of your server name. Does not work for the address and port. Also, can show PvP status.")
						.AppendLine("<color=red>Another IPv4 Server</color>:")
						.AppendLine("  address: 192.0.2.146")
						.AppendLine("  port: 9999")
						.AppendLine("  ispvp: true")
						.AppendLine("# You can specify if a server is crossplay or not. This will show the crossplay's \"Shuffle\" icon. Please note, this is not fully supported at this time.")
						.AppendLine("Crossplay Server:")
						.AppendLine("  address: 92.183.211.42")
						.AppendLine("  port: 9999")
						.AppendLine("  password: somepassword")
						.AppendLine("  iscrossplay: true")
						.AppendLine("  ispvp: true")
						.AppendLine("# You can specify if a server uses the whitelist for players or not. This will show in the tooltip only.")
						.AppendLine("Whitelisted Server:")
						.AppendLine("  address: 92.183.211.42")
						.AppendLine("  port: 9999")
						.AppendLine("  password: somepassword")
						.AppendLine("  iscrossplay: true")
						.AppendLine("  ispvp: true")
						.AppendLine("  iswhitelisted: true"));
					streamWriter.Close();
				}
				if (File.Exists(ConfigPath))
				{
					entries.AddRange(Definition.Parse(File.ReadAllText(ConfigPath)));
					FastLinkPlugin.FastLinkLogger.LogDebug((object)$"Loaded {entries.Count} server entries");
				}
			}
			catch (Exception arg)
			{
				FastLinkPlugin.FastLinkLogger.LogError((object)$"Error loading config {arg}");
			}
		}

		static Servers()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigPath = configPath + directorySeparatorChar + ConfigFileName;
			entries = new List<Definition>();
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace YamlDotNet
{
	internal sealed class CultureInfoAdapter : CultureInfo
	{
		private readonly IFormatProvider provider;

		public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
			: base(baseCulture.LCID)
		{
			this.provider = provider;
		}

		public override object? GetFormat(Type? formatType)
		{
			return provider.GetFormat(formatType);
		}
	}
	internal static class ReflectionExtensions
	{
		private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);

		public static Type? BaseType(this Type type)
		{
			return type.BaseType;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsInterface(this Type type)
		{
			return type.IsInterface;
		}

		public static bool IsEnum(this Type type)
		{
			return type.IsEnum;
		}

		public static bool IsDbNull(this object value)
		{
			return value is DBNull;
		}

		public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors)
		{
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (allowPrivateConstructors)
			{
				bindingFlags |= BindingFlags.NonPublic;
			}
			if (!type.IsValueType)
			{
				return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null;
			}
			return true;
		}

		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static PropertyInfo? GetPublicProperty(this Type type, string name)
		{
			return type.GetProperty(name);
		}

		public static FieldInfo? GetPublicStaticField(this Type type, string name)
		{
			return type.GetField(name, BindingFlags.Static | BindingFlags.Public);
		}

		public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic)
		{
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (includeNonPublic)
			{
				bindingFlags |= BindingFlags.NonPublic;
			}
			if (!type.IsInterface)
			{
				return type.GetProperties(bindingFlags);
			}
			return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags));
		}

		public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
		{
			return type.GetProperties(includeNonPublic: false);
		}

		public static IEnumerable<FieldInfo> GetPublicFields(this Type type)
		{
			return type.GetFields(BindingFlags.Instance | BindingFlags.Public);
		}

		public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type)
		{
			return type.GetMethods(BindingFlags.Static | BindingFlags.Public);
		}

		public static MethodInfo GetPrivateStaticMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'.");
		}

		public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null);
		}

		public static MethodInfo? GetPublicInstanceMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public);
		}

		public static Exception Unwrap(this TargetInvocationException ex)
		{
			Exception innerException = ex.InnerException;
			if (innerException == null)
			{
				return ex;
			}
			if (RemoteStackTraceField != null)
			{
				RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n");
			}
			return innerException;
		}

		public static bool IsInstanceOf(this Type type, object o)
		{
			return type.IsInstanceOfType(o);
		}

		public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo property)
		{
			return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true);
		}
	}
	internal static class PropertyInfoExtensions
	{
		public static object? ReadValue(this PropertyInfo property, object target)
		{
			return property.GetValue(target, null);
		}
	}
	internal static class StandardRegexOptions
	{
		public const RegexOptions Compiled = RegexOptions.Compiled;
	}
}
namespace YamlDotNet.Serialization
{
	internal abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly YamlAttributeOverrides overrides;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories;

		internal bool ignoreFields;

		internal bool includeNonPublicProperties;

		internal Settings settings;

		protected abstract TBuilder Self { get; }

		internal BuilderSkeleton(ITypeResolver typeResolver)
		{
			overrides = new YamlAttributeOverrides();
			typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter>
			{
				{
					typeof(YamlDotNet.Serialization.Converters.GuidConverter),
					(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
				},
				{
					typeof(SystemTypeConverter),
					(Nothing _) => new SystemTypeConverter()
				}
			};
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			settings = new Settings();
		}

		public TBuilder IgnoreFields()
		{
			ignoreFields = true;
			return Self;
		}

		public TBuilder IncludeNonPublicProperties()
		{
			includeNonPublicProperties = true;
			return Self;
		}

		public TBuilder EnablePrivateConstructors()
		{
			settings.AllowPrivateConstructors = true;
			return Self;
		}

		public TBuilder WithNamingConvention(INamingConvention namingConvention)
		{
			this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention");
			return Self;
		}

		public TBuilder WithTypeResolver(ITypeResolver typeResolver)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			return Self;
		}

		public abstract TBuilder WithTagMapping(TagName tag, Type type);

		public TBuilder WithAttributeOverride<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute)
		{
			overrides.Add(propertyAccessor, attribute);
			return Self;
		}

		public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute)
		{
			overrides.Add(type, member, attribute);
			return Self;
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter)
		{
			return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			IYamlTypeConverter typeConverter2 = typeConverter;
			if (typeConverter2 == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory;
			if (typeConverterFactory2 == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter
		{
			return WithoutTypeConverter(typeof(TYamlTypeConverter));
		}

		public TBuilder WithoutTypeConverter(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			typeConverterFactories.Remove(converterType);
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector
		{
			return WithoutTypeInspector(typeof(TTypeInspector));
		}

		public TBuilder WithoutTypeInspector(Type inspectorType)
		{
			if (inspectorType == null)
			{
				throw new ArgumentNullException("inspectorType");
			}
			typeInspectorFactories.Remove(inspectorType);
			return Self;
		}

		protected IEnumerable<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	internal delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase;
	internal delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase;
	[Flags]
	internal enum DefaultValuesHandling
	{
		Preserve = 0,
		OmitNull = 1,
		OmitDefaults = 2,
		OmitEmptyCollections = 4
	}
	internal sealed class Deserializer : IDeserializer
	{
		private readonly IValueDeserializer valueDeserializer;

		public Deserializer()
			: this(new DeserializerBuilder().BuildValueDeserializer())
		{
		}

		private Deserializer(IValueDeserializer valueDeserializer)
		{
			this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer");
		}

		public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer)
		{
			return new Deserializer(valueDeserializer);
		}

		public T Deserialize<T>(string input)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize<T>(input2);
		}

		public T Deserialize<T>(TextReader input)
		{
			return Deserialize<T>(new Parser(input));
		}

		public T Deserialize<T>(IParser parser)
		{
			return (T)Deserialize(parser, typeof(T));
		}

		public object? Deserialize(string input)
		{
			return Deserialize(input, typeof(object));
		}

		public object? Deserialize(TextReader input)
		{
			return Deserialize(input, typeof(object));
		}

		public object? Deserialize(IParser parser)
		{
			return Deserialize(parser, typeof(object));
		}

		public object? Deserialize(string input, Type type)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize(input2, type);
		}

		public object? Deserialize(TextReader input, Type type)
		{
			return Deserialize(new Parser(input), type);
		}

		public object? Deserialize(IParser parser, Type type)
		{
			if (parser == null)
			{
				throw new ArgumentNullException("parser");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			YamlDotNet.Core.Events.StreamStart @event;
			bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event);
			YamlDotNet.Core.Events.DocumentStart event2;
			bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2);
			object result = null;
			if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _))
			{
				using SerializerState serializerState = new SerializerState();
				result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer);
				serializerState.OnDeserialization();
			}
			if (flag2)
			{
				parser.Consume<YamlDotNet.Core.Events.DocumentEnd>();
			}
			if (flag)
			{
				parser.Consume<YamlDotNet.Core.Events.StreamEnd>();
			}
			return result;
		}
	}
	internal sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder>
	{
		private Lazy<IObjectFactory> objectFactory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly Dictionary<Type, Type> typeMappings;

		private readonly ITypeConverter typeConverter;

		private bool ignoreUnmatched;

		private bool duplicateKeyChecking;

		private bool attemptUnknownTypeDeserialization;

		protected override DeserializerBuilder Self => this;

		public DeserializerBuilder()
			: base((ITypeResolver)new StaticTypeResolver())
		{
			typeMappings = new Dictionary<Type, Type>();
			objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true);
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					FailsafeSchema.Tags.Str,
					typeof(string)
				},
				{
					JsonSchema.Tags.Bool,
					typeof(bool)
				},
				{
					JsonSchema.Tags.Float,
					typeof(double)
				},
				{
					JsonSchema.Tags.Int,
					typeof(int)
				},
				{
					DefaultSchema.Tags.Timestamp,
					typeof(DateTime)
				}
			};
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone()));
			typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner));
			nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer>
			{
				{
					typeof(YamlConvertibleNodeDeserializer),
					(Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(YamlSerializableNodeDeserializer),
					(Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(TypeConverterNodeDeserializer),
					(Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters())
				},
				{
					typeof(NullNodeDeserializer),
					(Nothing _) => new NullNodeDeserializer()
				},
				{
					typeof(ScalarNodeDeserializer),
					(Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter)
				},
				{
					typeof(ArrayNodeDeserializer),
					(Nothing _) => new ArrayNodeDeserializer()
				},
				{
					typeof(DictionaryNodeDeserializer),
					(Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking)
				},
				{
					typeof(CollectionNodeDeserializer),
					(Nothing _) => new CollectionNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(EnumerableNodeDeserializer),
					(Nothing _) => new EnumerableNodeDeserializer()
				},
				{
					typeof(ObjectNodeDeserializer),
					(Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter)
				}
			};
			nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver>
			{
				{
					typeof(MappingNodeTypeResolver),
					(Nothing _) => new MappingNodeTypeResolver(typeMappings)
				},
				{
					typeof(YamlConvertibleTypeResolver),
					(Nothing _) => new YamlConvertibleTypeResolver()
				},
				{
					typeof(YamlSerializableTypeResolver),
					(Nothing _) => new YamlSerializableTypeResolver()
				},
				{
					typeof(TagNodeTypeResolver),
					(Nothing _) => new TagNodeTypeResolver(tagMappings)
				},
				{
					typeof(PreventUnknownTagsNodeTypeResolver),
					(Nothing _) => new PreventUnknownTagsNodeTypeResolver()
				},
				{
					typeof(DefaultContainersNodeTypeResolver),
					(Nothing _) => new DefaultContainersNodeTypeResolver()
				}
			};
			typeConverter = new ReflectionTypeConverter();
		}

		internal ITypeInspector BuildTypeInspector()
		{
			ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
			if (!ignoreFields)
			{
				typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector);
			}
			return typeInspectorFactories.BuildComponentChain(typeInspector);
		}

		public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization()
		{
			attemptUnknownTypeDeserialization = true;
			return this;
		}

		public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory)
		{
			IObjectFactory objectFactory2 = objectFactory;
			if (objectFactory2 == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true);
			return this;
		}

		public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory)
		{
			if (objectFactory == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			return WithObjectFactory(new LambdaObjectFactory(objectFactory));
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer)
		{
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			INodeDeserializer nodeDeserializer2 = nodeDeserializer;
			if (nodeDeserializer2 == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2));
			return this;
		}

		public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory;
			if (nodeDeserializerFactory2 == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer
		{
			return WithoutNodeDeserializer(typeof(TNodeDeserializer));
		}

		public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType)
		{
			if (nodeDeserializerType == null)
			{
				throw new ArgumentNullException("nodeDeserializerType");
			}
			nodeDeserializerFactories.Remove(nodeDeserializerType);
			return this;
		}

		public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action<ITypeDiscriminatingNodeDeserializerOptions> configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1)
		{
			TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions();
			configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions);
			TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength);
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> s)
			{
				s.Before<DictionaryNodeDeserializer>();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver;
			if (nodeTypeResolver2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2));
			return this;
		}

		public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory;
			if (nodeTypeResolverFactory2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver
		{
			return WithoutNodeTypeResolver(typeof(TNodeTypeResolver));
		}

		public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType)
		{
			if (nodeTypeResolverType == null)
			{
				throw new ArgumentNullException("nodeTypeResolverType");
			}
			nodeTypeResolverFactories.Remove(nodeTypeResolverType);
			return this;
		}

		public override DeserializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(tag, out Type value))
			{
				throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag");
			}
			tagMappings.Add(tag, type);
			return this;
		}

		public DeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface
		{
			Type typeFromHandle = typeof(TInterface);
			Type typeFromHandle2 = typeof(TConcrete);
			if (!typeFromHandle.IsAssignableFrom(typeFromHandle2))
			{
				throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'.");
			}
			if (typeMappings.ContainsKey(typeFromHandle))
			{
				typeMappings[typeFromHandle] = typeFromHandle2;
			}
			else
			{
				typeMappings.Add(typeFromHandle, typeFromHandle2);
			}
			return this;
		}

		public DeserializerBuilder WithoutTagMapping(TagName tag)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (!tagMappings.Remove(tag))
			{
				throw new KeyNotFoundException($"Tag '{tag}' is not registered");
			}
			return this;
		}

		public DeserializerBuilder IgnoreUnmatchedProperties()
		{
			ignoreUnmatched = true;
			return this;
		}

		public DeserializerBuilder WithDuplicateKeyChecking()
		{
			duplicateKeyChecking = true;
			return this;
		}

		public IDeserializer Build()
		{
			return Deserializer.FromValueDeserializer(BuildValueDeserializer());
		}

		public IValueDeserializer BuildValueDeserializer()
		{
			return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter));
		}
	}
	internal sealed class EmissionPhaseObjectGraphVisitorArgs
	{
		private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors;

		public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; }

		public IEventEmitter EventEmitter { get; private set; }

		public ObjectSerializer NestedObjectSerializer { get; private set; }

		public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; }

		public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer)
		{
			InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor");
			EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter");
			this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors");
			TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters");
			NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer");
		}

		public T GetPreProcessingPhaseObjectGraphVisitor<T>() where T : IObjectGraphVisitor<Nothing>
		{
			return preProcessingPhaseVisitors.OfType<T>().Single();
		}
	}
	internal abstract class EventInfo
	{
		public IObjectDescriptor Source { get; }

		protected EventInfo(IObjectDescriptor source)
		{
			Source = source ?? throw new ArgumentNullException("source");
		}
	}
	internal class AliasEventInfo : EventInfo
	{
		public AnchorName Alias { get; }

		public bool NeedsExpansion { get; set; }

		public AliasEventInfo(IObjectDescriptor source, AnchorName alias)
			: base(source)
		{
			if (alias.IsEmpty)
			{
				throw new ArgumentNullException("alias");
			}
			Alias = alias;
		}
	}
	internal class ObjectEventInfo : EventInfo
	{
		public AnchorName Anchor { get; set; }

		public TagName Tag { get; set; }

		protected ObjectEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	internal sealed class ScalarEventInfo : ObjectEventInfo
	{
		public string RenderedValue { get; set; }

		public ScalarStyle Style { get; set; }

		public bool IsPlainImplicit { get; set; }

		public bool IsQuotedImplicit { get; set; }

		public ScalarEventInfo(IObjectDescriptor source)
			: base(source)
		{
			Style = source.ScalarStyle;
			RenderedValue = string.Empty;
		}
	}
	internal sealed class MappingStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public MappingStyle Style { get; set; }

		public MappingStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	internal sealed class MappingEndEventInfo : EventInfo
	{
		public MappingEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	internal sealed class SequenceStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public SequenceStyle Style { get; set; }

		public SequenceStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	internal sealed class SequenceEndEventInfo : EventInfo
	{
		public SequenceEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	internal interface IAliasProvider
	{
		AnchorName GetAlias(object target);
	}
	internal interface IDeserializer
	{
		T Deserialize<T>(string input);

		T Deserialize<T>(TextReader input);

		T Deserialize<T>(IParser parser);

		object? Deserialize(string input);

		object? Deserialize(TextReader input);

		object? Deserialize(IParser parser);

		object? Deserialize(string input, Type type);

		object? Deserialize(TextReader input, Type type);

		object? Deserialize(IParser parser, Type type);
	}
	internal interface IEventEmitter
	{
		void Emit(AliasEventInfo eventInfo, IEmitter emitter);

		void Emit(ScalarEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingStartEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingEndEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter);
	}
	internal interface INamingConvention
	{
		string Apply(string value);
	}
	internal interface INodeDeserializer
	{
		bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value);
	}
	internal interface INodeTypeResolver
	{
		bool Resolve(NodeEvent? nodeEvent, ref Type currentType);
	}
	internal interface IObjectAccessor
	{
		void Set(string name, object target, object value);

		object? Read(string name, object target);
	}
	internal interface IObjectDescriptor
	{
		object? Value { get; }

		Type Type { get; }

		Type StaticType { get; }

		ScalarStyle ScalarStyle { get; }
	}
	internal static class ObjectDescriptorExtensions
	{
		public static object NonNullValue(this IObjectDescriptor objectDescriptor)
		{
			return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet.");
		}
	}
	internal interface IObjectFactory
	{
		object Create(Type type);

		object? CreatePrimitive(Type type);

		bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments);

		Type GetValueType(Type type);
	}
	internal interface IObjectGraphTraversalStrategy
	{
		void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context);
	}
	internal interface IObjectGraphVisitor<TContext>
	{
		bool Enter(IObjectDescriptor value, TContext context);

		bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context);

		bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context);

		void VisitScalar(IObjectDescriptor scalar, TContext context);

		void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context);

		void VisitMappingEnd(IObjectDescriptor mapping, TContext context);

		void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context);

		void VisitSequenceEnd(IObjectDescriptor sequence, TContext context);
	}
	internal interface IPropertyDescriptor
	{
		string Name { get; }

		bool CanWrite { get; }

		Type Type { get; }

		Type? TypeOverride { get; set; }

		int Order { get; set; }

		ScalarStyle ScalarStyle { get; set; }

		T? GetCustomAttribute<T>() where T : Attribute;

		IObjectDescriptor Read(object target);

		void Write(object target, object? value);
	}
	internal interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void OnTop();

		void OnBottom();
	}
	internal interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;
	}
	internal interface ISerializer
	{
		string Serialize(object? graph);

		string Serialize(object? graph, Type type);

		void Serialize(TextWriter writer, object? graph);

		void Serialize(TextWriter writer, object? graph, Type type);

		void Serialize(IEmitter emitter, object? graph);

		void Serialize(IEmitter emitter, object? graph, Type type);
	}
	internal interface ITypeInspector
	{
		IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container);

		IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched);
	}
	internal interface ITypeResolver
	{
		Type Resolve(Type staticType, object? actualValue);
	}
	internal interface IValueDeserializer
	{
		object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer);
	}
	internal interface IValuePromise
	{
		event Action<object?> ValueAvailable;
	}
	internal interface IValueSerializer
	{
		void SerializeValue(IEmitter emitter, object? value, Type? type);
	}
	internal interface IYamlConvertible
	{
		void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer);

		void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer);
	}
	internal delegate object? ObjectDeserializer(Type type);
	internal delegate void ObjectSerializer(object? value, Type? type = null);
	[Obsolete("Please use IYamlConvertible instead")]
	internal interface IYamlSerializable
	{
		void ReadYaml(IParser parser);

		void WriteYaml(IEmitter emitter);
	}
	internal interface IYamlTypeConverter
	{
		bool Accepts(Type type);

		object? ReadYaml(IParser parser, Type type);

		void WriteYaml(IEmitter emitter, object? value, Type type);
	}
	internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable
	{
		public sealed class LazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TArgument, TComponent> Factory;

			public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		public sealed class TrackingLazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TComponent, TArgument, TComponent> Factory;

			public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly LazyComponentRegistration newRegistration;

			public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries[index] = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int num = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(num + 1, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(index, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Add(newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnTop()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Insert(0, newRegistration);
			}
		}

		private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly TrackingLazyComponentRegistration newRegistration;

			public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory;
				registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg));
			}
		}

		private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>();

		public int Count => entries.Count;

		public IEnumerable<Func<TArgument, TComponent>> InReverseOrder
		{
			get
			{
				int i = entries.Count - 1;
				while (i >= 0)
				{
					yield return entries[i].Factory;
					int num = i - 1;
					i = num;
				}
			}
		}

		public LazyComponentRegistrationList<TArgument, TComponent> Clone()
		{
			LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>();
			foreach (LazyComponentRegistration entry in entries)
			{
				lazyComponentRegistrationList.entries.Add(entry);
			}
			return lazyComponentRegistrationList;
		}

		public void Clear()
		{
			entries.Clear();
		}

		public void Add(Type componentType, Func<TArgument, TComponent> factory)
		{
			entries.Add(new LazyComponentRegistration(componentType, factory));
		}

		public void Remove(Type componentType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (entries[i].ComponentType == componentType)
				{
					entries.RemoveAt(i);
					return;
				}
			}
			throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found.");
		}

		public IRegistrationLocationSelectionSyntax<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory)
		{
			return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory));
		}

		public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory)
		{
			return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory));
		}

		public IEnumerator<Func<TArgument, TComponent>> GetEnumerator()
		{
			return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		private int IndexOfRegistration(Type registrationType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (registrationType == entries[i].ComponentType)
				{
					return i;
				}
			}
			return -1;
		}

		private void EnsureNoDuplicateRegistrationType(Type componentType)
		{
			if (IndexOfRegistration(componentType) != -1)
			{
				throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered.");
			}
		}

		private int EnsureRegistrationExists<TRegistrationType>()
		{
			int num = IndexOfRegistration(typeof(TRegistrationType));
			if (num == -1)
			{
				throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered.");
			}
			return num;
		}
	}
	internal static class LazyComponentRegistrationListExtensions
	{
		public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent)
		{
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner));
		}

		public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder)
		{
			Func<TComponent, TArgument> argumentBuilder2 = argumentBuilder;
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder2(inner)));
		}

		public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations)
		{
			return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList();
		}

		public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument)
		{
			TArgument argument2 = argument;
			return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument2)).ToList();
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct Nothing
	{
	}
	internal sealed class ObjectDescriptor : IObjectDescriptor
	{
		public object? Value { get; private set; }

		public Type Type { get; private set; }

		public Type StaticType { get; private set; }

		public ScalarStyle ScalarStyle { get; private set; }

		public ObjectDescriptor(object? value, Type type, Type staticType)
			: this(value, type, staticType, ScalarStyle.Any)
		{
		}

		public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle)
		{
			Value = value;
			Type = type ?? throw new ArgumentNullException("type");
			StaticType = staticType ?? throw new ArgumentNullException("staticType");
			ScalarStyle = scalarStyle;
		}
	}
	internal delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion);
	internal sealed class PropertyDescriptor : IPropertyDescriptor
	{
		private readonly IPropertyDescriptor baseDescriptor;

		public string Name { get; set; }

		public Type Type => baseDescriptor.Type;

		public Type? TypeOverride
		{
			get
			{
				return baseDescriptor.TypeOverride;
			}
			set
			{
				baseDescriptor.TypeOverride = value;
			}
		}

		public int Order { get; set; }

		public ScalarStyle ScalarStyle
		{
			get
			{
				return baseDescriptor.ScalarStyle;
			}
			set
			{
				baseDescriptor.ScalarStyle = value;
			}
		}

		public bool CanWrite => baseDescriptor.CanWrite;

		public PropertyDescriptor(IPropertyDescriptor baseDescriptor)
		{
			this.baseDescriptor = baseDescriptor;
			Name = baseDescriptor.Name;
		}

		public void Write(object target, object? value)
		{
			baseDescriptor.Write(target, value);
		}

		public T? GetCustomAttribute<T>() where T : Attribute
		{
			return baseDescriptor.GetCustomAttribute<T>();
		}

		public IObjectDescriptor Read(object target)
		{
			return baseDescriptor.Read(target);
		}
	}
	internal sealed class Serializer : ISerializer
	{
		private readonly IValueSerializer valueSerializer;

		private readonly EmitterSettings emitterSettings;

		public Serializer()
			: this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default)
		{
		}

		private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer");
			this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings");
		}

		public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			return new Serializer(valueSerializer, emitterSettings);
		}

		public string Serialize(object? graph)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph);
			return stringWriter.ToString();
		}

		public string Serialize(object? graph, Type type)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph, type);
			return stringWriter.ToString();
		}

		public void Serialize(TextWriter writer, object? graph)
		{
			Serialize(new Emitter(writer, emitterSettings), graph);
		}

		public void Serialize(TextWriter writer, object? graph, Type type)
		{
			Serialize(new Emitter(writer, emitterSettings), graph, type);
		}

		public void Serialize(IEmitter emitter, object? graph)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			EmitDocument(emitter, graph, null);
		}

		public void Serialize(IEmitter emitter, object? graph, Type type)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			EmitDocument(emitter, graph, type);
		}

		private void EmitDocument(IEmitter emitter, object? graph, Type? type)
		{
			emitter.Emit(new YamlDotNet.Core.Events.StreamStart());
			emitter.Emit(new YamlDotNet.Core.Events.DocumentStart());
			valueSerializer.SerializeValue(emitter, graph, type);
			emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true));
			emitter.Emit(new YamlDotNet.Core.Events.StreamEnd());
		}
	}
	internal sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
	{
		private class ValueSerializer : IValueSerializer
		{
			private readonly IObjectGraphTraversalStrategy traversalStrategy;

			private readonly IEventEmitter eventEmitter;

			private readonly IEnumerable<IYamlTypeConverter> typeConverters;

			private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

			private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

			public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories)
			{
				this.traversalStrategy = traversalStrategy;
				this.eventEmitter = eventEmitter;
				this.typeConverters = typeConverters;
				this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
				this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
			}

			public void SerializeValue(IEmitter emitter, object? value, Type? type)
			{
				IEmitter emitter2 = emitter;
				Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object));
				Type staticT