Decompiled source of TheGreatestPortal v1.2.0

BepInEx/plugins/TheGreatestPortal.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("TheGreatestPortal")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0+dee48ea804d4c6d6ba5884a6535f535b5d0b5915")]
[assembly: AssemblyProduct("TheGreatestPortal")]
[assembly: AssemblyTitle("TheGreatestPortal")]
[assembly: AssemblyVersion("1.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class PublicAPIAttribute : Attribute
	{
		public PublicAPIAttribute()
		{
		}

		public PublicAPIAttribute(string comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
	}
}
namespace ServerSync
{
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

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

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

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

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

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

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

		public event Action? ValueChanged;

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

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

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

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

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

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

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

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

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

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

				public volatile int versionMatchQueued = -1;

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

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private class PackageEntry
		{
			public string section;

			public string key;

			public Type type;

			public object? value;
		}

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

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

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected;

			public string received;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

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

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

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

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

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

		private static long packageCounter;

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

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

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

		public bool InitialSyncDone { get; private set; }

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

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

		private ConfigSync? ConfigSync;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

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

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

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

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

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

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

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			object obj = AccessTools.Field(typeof(FejdStartup), "m_connectionFailedError")?.GetValue(__instance);
			if (obj == null)
			{
				return;
			}
			PropertyInfo property = obj.GetType().GetProperty("text");
			if (property == null)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				property.SetValue(obj, (string)property.GetValue(obj) + "\n" + text);
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy((KeyValuePair<string, string> kv) => kv.Key))
			{
				string text2 = (string)property.GetValue(obj);
				if (!text2.Contains(item.Key))
				{
					property.SetValue(obj, text2 + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.");
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				obj.GetType().GetMethod("ForceMeshUpdate", Type.EmptyTypes)?.Invoke(obj, null);
				float num = (float)(obj.GetType().GetProperty("renderedHeight")?.GetValue(obj) ?? ((object)0f)) + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}
namespace TheGreatestPortal
{
	internal static class Access
	{
		private delegate Vector3 ScreenToWorld(Minimap map, Vector3 screen);

		private delegate void CenterMapCall(Minimap map, Vector3 point);

		internal static readonly FieldRef<Minimap, List<PinData>> Pins = AccessTools.FieldRefAccess<Minimap, List<PinData>>("m_pins");

		internal static readonly FieldRef<Minimap, bool[]> VisibleIconTypes = AccessTools.FieldRefAccess<Minimap, bool[]>("m_visibleIconTypes");

		internal static readonly FieldRef<Minimap, bool> PinUpdateRequired = AccessTools.FieldRefAccess<Minimap, bool>("m_pinUpdateRequired");

		internal static readonly FieldRef<Minimap, Vector3> MapOffset = AccessTools.FieldRefAccess<Minimap, Vector3>("m_mapOffset");

		internal static readonly FieldRef<Minimap, Vector3> MoveInertia = AccessTools.FieldRefAccess<Minimap, Vector3>("m_moveInertia");

		private static readonly ScreenToWorld _screenToWorldPoint = BindScreenToWorldPoint();

		private static Func<Color> _tgmPortalColor;

		private static bool _probedTgm;

		private static Action<string> _claimObituary;

		private static bool _probedObituaries;

		private static readonly CenterMapCall _centerMap = BindCenterMap();

		internal static bool CanPan => _centerMap != null;

		private static ScreenToWorld BindScreenToWorldPoint()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Minimap), "ScreenToWorldPoint", new Type[1] { typeof(Vector3) }, (Type[])null);
				if (methodInfo != null)
				{
					return AccessTools.MethodDelegate<ScreenToWorld>(methodInfo, (object)null, false);
				}
				TheGreatestPortalMod.Log.LogWarning((object)"[TheGreatestPortal] Minimap.ScreenToWorldPoint was not found; clicking portals on the map is disabled.");
			}
			catch (Exception ex)
			{
				TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not bind Minimap.ScreenToWorldPoint; clicking portals on the map is disabled: " + ex.Message));
			}
			return null;
		}

		internal static Vector3 ScreenToWorldPoint(Minimap map, Vector3 screen)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)map == (Object)null || _screenToWorldPoint == null)
			{
				return Vector3.zero;
			}
			return _screenToWorldPoint(map, screen);
		}

		internal static Color PortalPinColor()
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (!_probedTgm)
			{
				_probedTgm = true;
				Type type = AccessTools.TypeByName("TheGreatestMap.Portals");
				if (type != null)
				{
					MethodInfo methodInfo = AccessTools.Method(type, "CurrentColor", (Type[])null, (Type[])null);
					if (methodInfo != null && methodInfo.ReturnType == typeof(Color) && methodInfo.GetParameters().Length == 0)
					{
						try
						{
							_tgmPortalColor = AccessTools.MethodDelegate<Func<Color>>(methodInfo, (object)null, true);
						}
						catch (Exception ex)
						{
							TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not read TheGreatestMap's portal color; pins stay white: " + ex.Message));
						}
					}
					else
					{
						TheGreatestPortalMod.Log.LogInfo((object)"[TheGreatestPortal] TheGreatestMap is installed but has no portal color; pins stay white.");
					}
				}
			}
			if (_tgmPortalColor == null)
			{
				return Color.white;
			}
			try
			{
				return _tgmPortalColor();
			}
			catch
			{
				_tgmPortalColor = null;
				return Color.white;
			}
		}

		internal static void ClaimObituary(string line)
		{
			if (!_probedObituaries)
			{
				_probedObituaries = true;
				Type type = AccessTools.TypeByName("TheObituaries.Api");
				if (type != null)
				{
					MethodInfo methodInfo = AccessTools.Method(type, "NextDeath", new Type[1] { typeof(string) }, (Type[])null);
					if (methodInfo != null)
					{
						try
						{
							_claimObituary = AccessTools.MethodDelegate<Action<string>>(methodInfo, (object)null, true);
						}
						catch (Exception ex)
						{
							TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not reach TheObituaries; deaths are announced as it sees fit: " + ex.Message));
						}
					}
					else
					{
						TheGreatestPortalMod.Log.LogInfo((object)"[TheGreatestPortal] TheObituaries is installed but takes no death line; deaths are announced as it sees fit.");
					}
				}
			}
			if (_claimObituary == null)
			{
				return;
			}
			try
			{
				_claimObituary(line);
			}
			catch
			{
				_claimObituary = null;
			}
		}

		private static CenterMapCall BindCenterMap()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Minimap), "CenterMap", new Type[1] { typeof(Vector3) }, (Type[])null);
				if (methodInfo != null)
				{
					return AccessTools.MethodDelegate<CenterMapCall>(methodInfo, (object)null, false);
				}
				TheGreatestPortalMod.Log.LogWarning((object)"[TheGreatestPortal] Minimap.CenterMap was not found; the map will jump to a portal rather than pan.");
			}
			catch (Exception ex)
			{
				TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not bind Minimap.CenterMap; the map will jump rather than pan: " + ex.Message));
			}
			return null;
		}

		internal static void CenterMap(Minimap map, Vector3 point)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)map == (Object)null) && _centerMap != null)
			{
				_centerMap(map, point);
			}
		}

		internal static float PinInteractRadius(Minimap map)
		{
			float num = map.m_removeRadius * (map.LargeZoom * 2f);
			if (ZInput.IsTouchActive())
			{
				num *= 1.3f;
			}
			return num;
		}
	}
	internal sealed class PortalInfo
	{
		public long Id;

		public ZDOID ZdoId;

		public string Name = "";

		public Vector3 Pos;

		public Quaternion Rot = Quaternion.identity;

		public long TargetId;

		public bool AllowAllItems;

		public float ExitDistance = 1f;

		public string Prefab = "";

		public long Born;

		public long UsedAt;

		public string UsedBy = "";

		public string DisplayName
		{
			get
			{
				if (!string.IsNullOrEmpty(Name))
				{
					return Name;
				}
				return "Unnamed portal";
			}
		}

		public void Write(ZPackage pkg)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			pkg.Write(Id);
			pkg.Write(ZdoId);
			pkg.Write(Name ?? "");
			pkg.Write(Pos);
			pkg.Write(Rot);
			pkg.Write(TargetId);
			pkg.Write(AllowAllItems);
			pkg.Write(ExitDistance);
			pkg.Write(Prefab ?? "");
		}

		public void WriteExtra(ZPackage pkg)
		{
			pkg.Write(Born);
			pkg.Write(UsedAt);
			pkg.Write(UsedBy ?? "");
		}

		public void ReadExtra(ZPackage pkg)
		{
			Born = pkg.ReadLong();
			UsedAt = pkg.ReadLong();
			UsedBy = pkg.ReadString();
		}

		public static PortalInfo Read(ZPackage pkg)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			return new PortalInfo
			{
				Id = pkg.ReadLong(),
				ZdoId = pkg.ReadZDOID(),
				Name = pkg.ReadString(),
				Pos = pkg.ReadVector3(),
				Rot = pkg.ReadQuaternion(),
				TargetId = pkg.ReadLong(),
				AllowAllItems = pkg.ReadBool(),
				ExitDistance = pkg.ReadSingle(),
				Prefab = pkg.ReadString()
			};
		}
	}
	internal static class Catalog
	{
		private struct PrefabFacts
		{
			public bool AllowAll;

			public float Exit;

			public string Name;
		}

		private const int Version = 1;

		private const int Extra = 1;

		private static readonly Dictionary<long, PortalInfo> _byId = new Dictionary<long, PortalInfo>();

		private static readonly List<PortalInfo> _all = new List<PortalInfo>();

		private static readonly Dictionary<int, PrefabFacts> _prefabs = new Dictionary<int, PrefabFacts>();

		internal static IReadOnlyList<PortalInfo> All => _all;

		internal static int Count => _all.Count;

		internal static bool HasSnapshot { get; private set; }

		internal static event Action Changed;

		internal static PortalInfo Get(long id)
		{
			if (id == 0L || !_byId.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		internal static PortalInfo ByZdo(ZDOID id)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (id == ZDOID.None)
			{
				return null;
			}
			for (int i = 0; i < _all.Count; i++)
			{
				if (_all[i].ZdoId == id)
				{
					return _all[i];
				}
			}
			return null;
		}

		internal static PortalInfo ByName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			for (int i = 0; i < _all.Count; i++)
			{
				if (string.Equals(_all[i].Name, name, StringComparison.OrdinalIgnoreCase))
				{
					return _all[i];
				}
			}
			return null;
		}

		internal static void Clear()
		{
			_byId.Clear();
			_all.Clear();
			HasSnapshot = false;
		}

		internal static void Apply(ZPackage pkg)
		{
			int num = pkg.ReadInt();
			if (num != 1)
			{
				TheGreatestPortalMod.Log.LogWarning((object)$"[TheGreatestPortal] Ignoring a portal list of format {num}; this build speaks {1}.");
				return;
			}
			int num2 = pkg.ReadInt();
			_byId.Clear();
			_all.Clear();
			List<PortalInfo> list = new List<PortalInfo>(num2);
			for (int i = 0; i < num2; i++)
			{
				PortalInfo portalInfo = PortalInfo.Read(pkg);
				list.Add(portalInfo);
				if (portalInfo.Id != 0L && !_byId.ContainsKey(portalInfo.Id))
				{
					_byId[portalInfo.Id] = portalInfo;
					_all.Add(portalInfo);
				}
			}
			if (pkg.GetPos() < pkg.Size() && pkg.ReadInt() == 1)
			{
				for (int j = 0; j < list.Count; j++)
				{
					if (pkg.GetPos() >= pkg.Size())
					{
						break;
					}
					list[j].ReadExtra(pkg);
				}
			}
			HasSnapshot = true;
			try
			{
				Catalog.Changed?.Invoke();
			}
			catch (Exception arg)
			{
				TheGreatestPortalMod.Log.LogError((object)$"[TheGreatestPortal] Catalog listener failed: {arg}");
			}
		}

		internal static ZPackage Pack(List<PortalInfo> infos)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(1);
			val.Write(infos.Count);
			for (int i = 0; i < infos.Count; i++)
			{
				infos[i].Write(val);
			}
			val.Write(1);
			for (int j = 0; j < infos.Count; j++)
			{
				infos[j].WriteExtra(val);
			}
			return val;
		}

		internal static void PrefabFor(int hash, out bool allowAll, out float exitDistance, out string name)
		{
			if (!_prefabs.TryGetValue(hash, out var value))
			{
				value = new PrefabFacts
				{
					AllowAll = false,
					Exit = 1f,
					Name = ""
				};
				ZNetScene instance = ZNetScene.instance;
				GameObject val = (((Object)(object)instance != (Object)null) ? instance.GetPrefab(hash) : null);
				if ((Object)(object)val != (Object)null)
				{
					value.Name = ((Object)val).name;
					TeleportWorld component = val.GetComponent<TeleportWorld>();
					if ((Object)(object)component != (Object)null)
					{
						value.AllowAll = component.m_allowAllItems;
						value.Exit = component.m_exitDistance;
					}
				}
				_prefabs[hash] = value;
			}
			allowAll = value.AllowAll;
			exitDistance = value.Exit;
			name = value.Name;
		}

		internal static void ResetPrefabCache()
		{
			_prefabs.Clear();
		}
	}
	internal static class Commands
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			public static ConsoleEvent <>9__0_1;

			public static ConsoleEvent <>9__0_2;

			public static ConsoleEvent <>9__0_3;

			internal void <Register>b__0_0(ConsoleEventArgs args)
			{
				Terminal context = args.Context;
				if (context != null)
				{
					context.AddString(PortalNetwork.Status());
				}
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					Terminal context2 = args.Context;
					if (context2 != null)
					{
						context2.AddString($"picker: {MapPicker.Status()} | favorites: {Favorites.Count}, default: {DefaultName()}");
					}
				}
			}

			internal void <Register>b__0_1(ConsoleEventArgs args)
			{
				if (Catalog.Count == 0)
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString(Catalog.HasSnapshot ? "No portals in the world." : "No portal list received from the server yet.");
					}
					return;
				}
				StringBuilder stringBuilder = new StringBuilder();
				foreach (PortalInfo item in Catalog.All)
				{
					PortalInfo portalInfo = Catalog.Get(item.TargetId);
					string text = ((item.TargetId == 0L) ? "open (choose on the map)" : ((portalInfo != null) ? ("-> " + portalInfo.DisplayName) : "-> missing portal"));
					string text2 = (Favorites.IsFavorite(item.Id) ? " *" : "");
					string text3 = ((Favorites.DefaultId == item.Id) ? " (default)" : "");
					stringBuilder.AppendLine($"{item.DisplayName}{text2}{text3}  [{item.Pos.x:0},{item.Pos.z:0}]  {text}");
				}
				Terminal context2 = args.Context;
				if (context2 != null)
				{
					context2.AddString(stringBuilder.ToString().TrimEnd(Array.Empty<char>()));
				}
			}

			internal void <Register>b__0_2(ConsoleEventArgs args)
			{
				PortalNetwork.RequestCatalog();
				Terminal context = args.Context;
				if (context != null)
				{
					context.AddString("Portal list requested.");
				}
			}

			internal void <Register>b__0_3(ConsoleEventArgs args)
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("Not in a game.");
					}
					return;
				}
				string text = ((args.Length > 1) ? string.Join(" ", args.Args, 1, args.Length - 1) : "");
				if (string.IsNullOrEmpty(text))
				{
					Terminal context2 = args.Context;
					if (context2 != null)
					{
						context2.AddString("Default portal: " + DefaultName());
					}
					return;
				}
				if (text.Equals("clear", StringComparison.OrdinalIgnoreCase))
				{
					Favorites.SetDefault(0L);
					Terminal context3 = args.Context;
					if (context3 != null)
					{
						context3.AddString("Default portal cleared.");
					}
					return;
				}
				PortalInfo portalInfo = Catalog.ByName(text);
				if (portalInfo == null)
				{
					Terminal context4 = args.Context;
					if (context4 != null)
					{
						context4.AddString("No portal named '" + text + "'.");
					}
					return;
				}
				Favorites.SetDefault(portalInfo.Id);
				Terminal context5 = args.Context;
				if (context5 != null)
				{
					context5.AddString("New portals will connect to '" + portalInfo.DisplayName + "'.");
				}
			}
		}

		internal static void Register()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00de: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString(PortalNetwork.Status());
					}
					if ((Object)(object)Player.m_localPlayer != (Object)null)
					{
						Terminal context2 = args.Context;
						if (context2 != null)
						{
							context2.AddString($"picker: {MapPicker.Status()} | favorites: {Favorites.Count}, default: {DefaultName()}");
						}
					}
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("tgp_status", "The Greatest Portal: portal count, map picker state and favorites", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj2 = <>c.<>9__0_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = delegate(ConsoleEventArgs args)
				{
					if (Catalog.Count == 0)
					{
						Terminal context = args.Context;
						if (context != null)
						{
							context.AddString(Catalog.HasSnapshot ? "No portals in the world." : "No portal list received from the server yet.");
						}
					}
					else
					{
						StringBuilder stringBuilder = new StringBuilder();
						foreach (PortalInfo item in Catalog.All)
						{
							PortalInfo portalInfo = Catalog.Get(item.TargetId);
							string text = ((item.TargetId == 0L) ? "open (choose on the map)" : ((portalInfo != null) ? ("-> " + portalInfo.DisplayName) : "-> missing portal"));
							string text2 = (Favorites.IsFavorite(item.Id) ? " *" : "");
							string text3 = ((Favorites.DefaultId == item.Id) ? " (default)" : "");
							stringBuilder.AppendLine($"{item.DisplayName}{text2}{text3}  [{item.Pos.x:0},{item.Pos.z:0}]  {text}");
						}
						Terminal context2 = args.Context;
						if (context2 != null)
						{
							context2.AddString(stringBuilder.ToString().TrimEnd(Array.Empty<char>()));
						}
					}
				};
				<>c.<>9__0_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("tgp_list", "The Greatest Portal: list every portal the server knows, with destinations", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj3 = <>c.<>9__0_2;
			if (obj3 == null)
			{
				ConsoleEvent val3 = delegate(ConsoleEventArgs args)
				{
					PortalNetwork.RequestCatalog();
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("Portal list requested.");
					}
				};
				<>c.<>9__0_2 = val3;
				obj3 = (object)val3;
			}
			new ConsoleCommand("tgp_refresh", "The Greatest Portal: ask the server for the portal list again", (ConsoleEvent)obj3, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj4 = <>c.<>9__0_3;
			if (obj4 == null)
			{
				ConsoleEvent val4 = delegate(ConsoleEventArgs args)
				{
					if ((Object)(object)Player.m_localPlayer == (Object)null)
					{
						Terminal context = args.Context;
						if (context != null)
						{
							context.AddString("Not in a game.");
						}
					}
					else
					{
						string text = ((args.Length > 1) ? string.Join(" ", args.Args, 1, args.Length - 1) : "");
						if (string.IsNullOrEmpty(text))
						{
							Terminal context2 = args.Context;
							if (context2 != null)
							{
								context2.AddString("Default portal: " + DefaultName());
							}
						}
						else if (text.Equals("clear", StringComparison.OrdinalIgnoreCase))
						{
							Favorites.SetDefault(0L);
							Terminal context3 = args.Context;
							if (context3 != null)
							{
								context3.AddString("Default portal cleared.");
							}
						}
						else
						{
							PortalInfo portalInfo = Catalog.ByName(text);
							if (portalInfo == null)
							{
								Terminal context4 = args.Context;
								if (context4 != null)
								{
									context4.AddString("No portal named '" + text + "'.");
								}
							}
							else
							{
								Favorites.SetDefault(portalInfo.Id);
								Terminal context5 = args.Context;
								if (context5 != null)
								{
									context5.AddString("New portals will connect to '" + portalInfo.DisplayName + "'.");
								}
							}
						}
					}
				};
				<>c.<>9__0_3 = val4;
				obj4 = (object)val4;
			}
			new ConsoleCommand("tgp_default", "The Greatest Portal: tgp_default <portal name> sets the default portal for portals you build; tgp_default clear removes it", (ConsoleEvent)obj4, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		private static string DefaultName()
		{
			long defaultId = Favorites.DefaultId;
			if (defaultId == 0L)
			{
				return "none";
			}
			PortalInfo portalInfo = Catalog.Get(defaultId);
			if (portalInfo == null)
			{
				return "a portal that no longer exists";
			}
			return portalInfo.DisplayName;
		}
	}
	internal static class Favorites
	{
		private static readonly HashSet<long> _favs = new HashSet<long>();

		private static readonly List<long> _recents = new List<long>();

		private const int MaxRecents = 20;

		private static long _default;

		private static string _path;

		private static bool _loaded;

		internal static long DefaultId
		{
			get
			{
				Load();
				return _default;
			}
		}

		internal static int Count
		{
			get
			{
				Load();
				return _favs.Count;
			}
		}

		internal static IReadOnlyList<long> Recents
		{
			get
			{
				Load();
				return _recents;
			}
		}

		internal static void RecordTrip(long from, long to)
		{
			Load();
			PortalNetwork.SendUsed(from, to);
			bool flag = false;
			long[] array = new long[2] { from, to };
			foreach (long num in array)
			{
				if (num != 0L)
				{
					_recents.Remove(num);
					_recents.Insert(0, num);
					flag = true;
				}
			}
			if (flag)
			{
				if (_recents.Count > 20)
				{
					_recents.RemoveRange(20, _recents.Count - 20);
				}
				Save();
			}
		}

		internal static bool IsFavorite(long id)
		{
			Load();
			if (id != 0L)
			{
				return _favs.Contains(id);
			}
			return false;
		}

		internal static bool Toggle(long id)
		{
			Load();
			if (id == 0L)
			{
				return false;
			}
			bool num = !_favs.Remove(id);
			if (num)
			{
				_favs.Add(id);
			}
			Save();
			return num;
		}

		internal static void SetFavorite(long id, bool on)
		{
			Load();
			if (id != 0L && (on ? _favs.Add(id) : _favs.Remove(id)))
			{
				Save();
			}
		}

		internal static void SetDefault(long id)
		{
			Load();
			if (_default != id)
			{
				_default = id;
				Save();
				if (id == 0L)
				{
					TheGreatestPortalMod.Log.LogInfo((object)"[TheGreatestPortal] No default portal any more; portals you build will be open.");
					return;
				}
				PortalInfo portalInfo = Catalog.Get(id);
				TheGreatestPortalMod.Log.LogInfo((object)string.Format("[TheGreatestPortal] Default portal for portals you build is now '{0}' ({1}), saved in {2}.", (portalInfo != null) ? portalInfo.DisplayName : "a portal that is not in the list", id, _path));
			}
		}

		internal static void Reset()
		{
			_favs.Clear();
			_recents.Clear();
			_default = 0L;
			_path = null;
			_loaded = false;
			PortalList.Reset();
		}

		private static string PathFor()
		{
			World world = ZNet.World;
			if (world == null || string.IsNullOrEmpty(world.m_name))
			{
				return null;
			}
			StringBuilder stringBuilder = new StringBuilder();
			string name = world.m_name;
			foreach (char c in name)
			{
				stringBuilder.Append((char.IsLetterOrDigit(c) || c == '-' || c == '_') ? c : '_');
			}
			return Path.Combine(Paths.ConfigPath, "TheGreatestPortal", $"{stringBuilder}-{world.m_seed}.txt");
		}

		private static void Load()
		{
			if (_loaded)
			{
				return;
			}
			_path = PathFor();
			if (_path == null)
			{
				return;
			}
			_loaded = true;
			_favs.Clear();
			_recents.Clear();
			_default = 0L;
			try
			{
				if (!File.Exists(_path))
				{
					TheGreatestPortalMod.Log.LogInfo((object)("[TheGreatestPortal] Nothing saved for this world yet; favorites and the default portal will go in " + _path + "."));
					return;
				}
				string[] array = File.ReadAllLines(_path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					int num = text.IndexOf('=');
					if (num <= 0)
					{
						continue;
					}
					string text2 = text.Substring(0, num).Trim();
					if (!long.TryParse(text.Substring(num + 1).Trim(), out var result) || result == 0L)
					{
						continue;
					}
					switch (text2)
					{
					case "favorite":
						_favs.Add(result);
						break;
					case "default":
						_default = result;
						break;
					case "recent":
						if (!_recents.Contains(result) && _recents.Count < 20)
						{
							_recents.Add(result);
						}
						break;
					}
				}
				TheGreatestPortalMod.Log.LogInfo((object)string.Format("[TheGreatestPortal] Read {0} favorite(s), {1} recent portal(s) and default portal {2} from {3}.", _favs.Count, _recents.Count, (_default == 0L) ? "none" : _default.ToString(), _path));
			}
			catch (Exception ex)
			{
				TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not read favorites from " + _path + ": " + ex.Message));
			}
		}

		private static void Save()
		{
			if (_path == null)
			{
				TheGreatestPortalMod.Log.LogWarning((object)"[TheGreatestPortal] The world is not known yet, so favorites and the default portal cannot be saved.");
				return;
			}
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(_path));
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("# The Greatest Portal: this player's default portal, favorites and recent portals (newest first) for one world, by permanent portal id.");
				if (_default != 0L)
				{
					stringBuilder.AppendLine("default=" + _default);
				}
				foreach (long fav in _favs)
				{
					stringBuilder.AppendLine("favorite=" + fav);
				}
				foreach (long recent in _recents)
				{
					stringBuilder.AppendLine("recent=" + recent);
				}
				File.WriteAllText(_path, stringBuilder.ToString());
			}
			catch (Exception ex)
			{
				TheGreatestPortalMod.Log.LogWarning((object)("[TheGreatestPortal] Could not save favorites to " + _path + ": " + ex.Message));
			}
		}
	}
	internal static class MapPicker
	{
		internal enum Mode
		{
			None,
			Travel,
			Pick,
			Browse
		}

		private static TeleportWorld _source;

		private static ZDOID _sourceZdo;

		private static long _sourceId;

		private static bool _sourceAllowAll;

		private static Collider _trigger;

		private static Collider _playerCollider;

		private static float _lostAt;

		private static Action<PortalInfo> _onPicked;

		private static long _highlightId;

		private static string _query;

		private static bool _detour;

		private static long _hoverId;

		private static bool _hoverFromRow;

		private static string _usualDestination;

		private static GameObject _list;

		private static UiKit.Hover _listHover;

		private static RectTransform _listContent;

		private static ScrollRect _scroll;

		private static TextMeshProUGUI _header;

		private static TextMeshProUGUI _hint;

		private static TMP_InputField _search;

		private static readonly RowRename _rename;

		private static bool _panning;

		private static Vector3 _panFrom;

		private static Vector3 _panTo;

		private static Vector3 _panLast;

		private static float _panStart;

		private static Toggle _group;

		private static Button _expandAll;

		private static Button _collapseAll;

		private static RectTransform _listRt;

		private static RectTransform _listMover;

		private static float _listW;

		private static float _listH;

		private static Vector2 _listPos;

		private static List<ListEntry> _entries;

		private static readonly List<UiKit.RowHandle> _rows;

		private static readonly List<long> _rowIds;

		private static bool _catalogDirty;

		private const float HoverScale = 1.6f;

		private static GameObject _glow;

		private static Image _glowImage;

		private const float PanSeconds = 0.35f;

		private const float ListW = 380f;

		private const float ListH = 660f;

		private const float MinListW = 300f;

		private const float MaxListW = 900f;

		private const float MinListH = 240f;

		private const float MaxListH = 1400f;

		internal static Mode Current { get; private set; }

		internal static bool Active => Current != Mode.None;

		internal static bool IsSelecting
		{
			get
			{
				if (Current != Mode.Travel)
				{
					return Current == Mode.Pick;
				}
				return true;
			}
		}

		internal static bool ListPointerOver
		{
			get
			{
				if ((Object)(object)_list != (Object)null && (Object)(object)_listHover != (Object)null)
				{
					return _listHover.Over;
				}
				return false;
			}
		}

		internal static bool SearchFocused => UiKit.IsFocused(_search);

		static MapPicker()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			_sourceZdo = ZDOID.None;
			_lostAt = -1f;
			_query = "";
			_usualDestination = "";
			_rename = new RowRename();
			_entries = new List<ListEntry>();
			_rows = new List<UiKit.RowHandle>();
			_rowIds = new List<long>();
			Catalog.Changed += delegate
			{
				_catalogDirty = true;
			};
		}

		private static ZDO ZdoOf(TeleportWorld portal)
		{
			if ((Object)(object)portal == (Object)null)
			{
				return null;
			}
			ZNetView component = ((Component)portal).GetComponent<ZNetView>();
			if (!((Object)(object)component != (Object)null) || !component.IsValid())
			{
				return null;
			}
			return component.GetZDO();
		}

		internal static bool IsOpenPortal(TeleportWorld portal)
		{
			if (TgpConfig.UntargetedOpensMap == null || !TgpConfig.UntargetedOpensMap.Value)
			{
				return false;
			}
			return PortalData.IsOpen(ZdoOf(portal));
		}

		internal static string BlockedReason(TeleportWorld portal)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			ZDO val = ZdoOf(portal);
			if (val == null)
			{
				return null;
			}
			long target = PortalData.GetTarget(val);
			if (target == 0L || PortalData.Connection(val) != ZDOID.None)
			{
				return null;
			}
			if (Catalog.HasSnapshot && Catalog.Get(target) == null)
			{
				return "The destination portal is gone";
			}
			return "The portal is still connecting; step in again in a moment";
		}

		internal static void BeginTravel(TeleportWorld portal, Collider trigger, Collider playerCollider, bool detour = false)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)Minimap.instance == (Object)null || (Object)(object)portal == (Object)null)
			{
				return;
			}
			if (Active)
			{
				End();
			}
			if (Travel.CanTeleport(localPlayer, portal.m_allowAllItems))
			{
				ZDO val = ZdoOf(portal);
				_detour = detour;
				_usualDestination = "";
				if (detour)
				{
					PortalInfo portalInfo = Catalog.Get(PortalData.GetTarget(val));
					_usualDestination = ((portalInfo != null) ? portalInfo.DisplayName : "");
				}
				_source = portal;
				_sourceZdo = val?.m_uid ?? ZDOID.None;
				_sourceId = PortalData.GetId(val);
				_sourceAllowAll = portal.m_allowAllItems;
				_trigger = trigger;
				_playerCollider = playerCollider;
				_lostAt = -1f;
				_onPicked = null;
				_highlightId = 0L;
				_query = "";
				Current = Mode.Travel;
				if (!Catalog.HasSnapshot)
				{
					PortalNetwork.RequestCatalog();
				}
				OpenMapAt(((Component)portal).transform.position);
				Refresh();
				if (Catalog.HasSnapshot && Catalog.Count <= 1)
				{
					TheGreatestPortalMod.Message("No other portals to travel to", always: true);
				}
			}
		}

		internal static void BeginPick(ZDOID sourceZdo, long sourceId, Vector3 center, Action<PortalInfo> onPicked)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Minimap.instance == (Object)null))
			{
				if (Active)
				{
					End();
				}
				_source = null;
				_sourceZdo = sourceZdo;
				_sourceId = sourceId;
				_sourceAllowAll = false;
				_onPicked = onPicked;
				_highlightId = 0L;
				_query = "";
				_detour = false;
				Current = Mode.Pick;
				OpenMapAt(center);
				Refresh();
			}
		}

		internal static void BeginBrowse(Vector3? center)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (Active)
				{
					End();
				}
				_source = null;
				_sourceZdo = ZDOID.None;
				_sourceId = 0L;
				_onPicked = null;
				_highlightId = 0L;
				_query = "";
				_detour = false;
				Current = Mode.Browse;
				if (center.HasValue)
				{
					OpenMapAt(center.Value);
				}
				else if ((int)instance.m_mode != 2)
				{
					instance.SetMapMode((MapMode)2);
				}
				Refresh();
			}
		}

		internal static void End()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			bool num = Active || (Object)(object)_list != (Object)null || PortalPins.Count > 0;
			Current = Mode.None;
			_source = null;
			_sourceZdo = ZDOID.None;
			_sourceId = 0L;
			_trigger = null;
			_playerCollider = null;
			_lostAt = -1f;
			_onPicked = null;
			_highlightId = 0L;
			_query = "";
			_detour = false;
			_usualDestination = "";
			ClearHover();
			DestroyGlow();
			if (num)
			{
				PortalPins.Clear();
				DestroyList();
			}
		}

		internal static void Update()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			if ((Object)(object)instance == (Object)null)
			{
				if (Active)
				{
					End();
				}
				return;
			}
			if ((int)instance.m_mode == 2 && Keys.CanTakeInput() && Keys.IsDown(TgpConfig.TogglePinsKey.Value))
			{
				if (Current == Mode.Browse)
				{
					End();
				}
				else if (Current == Mode.None)
				{
					BeginBrowse(null);
				}
			}
			if (!Active)
			{
				return;
			}
			if ((int)instance.m_mode != 2)
			{
				End();
				return;
			}
			UpdatePan(instance);
			if (UiKit.ContextMenu.IsOpen)
			{
				UiKit.ContextMenu.Update();
				return;
			}
			if (_rename.Active && ZInput.GetKeyDown((KeyCode)27, true))
			{
				_rename.Cancel();
			}
			else if (SearchFocused && ZInput.GetKeyDown((KeyCode)27, true))
			{
				_search.DeactivateInputField(false);
			}
			if (_catalogDirty)
			{
				_catalogDirty = false;
				Refresh();
			}
			UpdateHover(instance);
			if (Current == Mode.Travel)
			{
				UpdateAutoClose(instance);
			}
		}

		private static void UpdateAutoClose(Minimap map)
		{
			float value = TgpConfig.AutoCloseGraceSeconds.Value;
			if (!(value <= 0f) && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				if (InsideSource())
				{
					_lostAt = -1f;
				}
				else if (_lostAt < 0f)
				{
					_lostAt = Time.time;
				}
				else if (!(Time.time - _lostAt < value))
				{
					map.SetMapMode((MapMode)1);
					End();
				}
			}
		}

		private static bool InsideSource()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			if ((Object)(object)_trigger != (Object)null && (Object)(object)_playerCollider != (Object)null && _trigger.enabled && _playerCollider.enabled)
			{
				Bounds bounds = _trigger.bounds;
				if (((Bounds)(ref bounds)).Intersects(_playerCollider.bounds))
				{
					return true;
				}
				return Vector3.Distance(_trigger.ClosestPoint(position), position) <= 0.05f;
			}
			if ((Object)(object)_source != (Object)null)
			{
				return Vector3.Distance(((Component)_source).transform.position, position) < 3f;
			}
			return false;
		}

		internal static void OnMapModeChanged(MapMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)mode == 2)
			{
				if (!Active && TgpConfig.ShowPinsOnMap != null && TgpConfig.ShowPinsOnMap.Value)
				{
					BeginBrowse(null);
				}
			}
			else
			{
				End();
			}
		}

		private static void UpdateHover(Minimap map)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (ListPointerOver)
			{
				if (!_hoverFromRow)
				{
					SetHover(map, 0L, fromRow: false);
				}
			}
			else
			{
				SetHover(map, PortalUnderPointer(map)?.Id ?? 0, fromRow: false);
			}
			Color val = Access.PortalPinColor();
			PortalPins.Tint(val);
			if (_hoverId != 0L)
			{
				Decorate(map, _hoverId, on: true, val);
			}
			else
			{
				HideGlow();
			}
		}

		private static void SetHover(Minimap map, long id, bool fromRow)
		{
			if (_hoverId != id)
			{
				Decorate(map, _hoverId, on: false);
				_hoverId = id;
			}
			_hoverFromRow = id != 0 && fromRow;
		}

		private static void ClearHover()
		{
			_hoverId = 0L;
			_hoverFromRow = false;
			HideGlow();
		}

		private static void Decorate(Minimap map, long id, bool on, Color? tint = null)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			if (id == 0L || (Object)(object)map == (Object)null)
			{
				return;
			}
			PinData val = PortalPins.PinFor(id);
			if (val == null || (Object)(object)val.m_uiElement == (Object)null)
			{
				if (on)
				{
					HideGlow();
				}
				return;
			}
			Color color = (Color)(((??)tint) ?? Access.PortalPinColor());
			((Transform)val.m_uiElement).localScale = (on ? (Vector3.one * 1.6f) : Vector3.one);
			if ((Object)(object)val.m_iconElement != (Object)null)
			{
				((Graphic)val.m_iconElement).color = color;
			}
			if (on)
			{
				ShowGlow(map, val, color);
			}
			else
			{
				HideGlow();
			}
			PinNameData namePinData = val.m_NamePinData;
			if (namePinData != null && !((Object)(object)namePinData.PinNameGameObject == (Object)null))
			{
				if ((Object)(object)namePinData.PinNameText != (Object)null)
				{
					((Graphic)namePinData.PinNameText).color = (on ? UiKit.Gold : Color.white);
				}
				namePinData.PinNameGameObject.SetActive(on || (!string.IsNullOrEmpty(val.m_name) && map.LargeZoom < map.m_showNamesZoom));
			}
		}

		private static void ShowGlow(Minimap map, PinData pin, Color color)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_00c5: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			Transform parent = ((Transform)pin.m_uiElement).parent;
			RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			if ((Object)(object)val == (Object)null)
			{
				HideGlow();
				return;
			}
			if ((Object)(object)_glow == (Object)null)
			{
				_glow = new GameObject("TGP_PinGlow", new Type[3]
				{
					typeof(RectTransform),
					typeof(CanvasRenderer),
					typeof(Image)
				});
				_glowImage = _glow.GetComponent<Image>();
				_glowImage.sprite = UiKit.Glow();
				((Graphic)_glowImage).raycastTarget = false;
			}
			RectTransform val2 = (RectTransform)_glow.transform;
			if ((Object)(object)((Transform)val2).parent != (Object)(object)val)
			{
				((Transform)val2).SetParent((Transform)(object)val, false);
				((Transform)val2).SetAsFirstSibling();
			}
			val2.anchorMin = pin.m_uiElement.anchorMin;
			val2.anchorMax = pin.m_uiElement.anchorMax;
			val2.pivot = pin.m_uiElement.pivot;
			val2.anchoredPosition = pin.m_uiElement.anchoredPosition;
			float num = map.m_pinSizeLarge * 2.6f;
			val2.sizeDelta = new Vector2(num, num);
			float num2 = (Mathf.Sin(Time.unscaledTime * 3.2f) + 1f) * 0.5f;
			color.a = Mathf.Lerp(0.32f, 0.62f, num2);
			((Graphic)_glowImage).color = color;
			if (!_glow.activeSelf)
			{
				_glow.SetActive(true);
			}
		}

		private static void HideGlow()
		{
			if ((Object)(object)_glow != (Object)null && _glow.activeSelf)
			{
				_glow.SetActive(false);
			}
		}

		private static void DestroyGlow()
		{
			if ((Object)(object)_glow != (Object)null)
			{
				Object.Destroy((Object)(object)_glow);
			}
			_glow = null;
			_glowImage = null;
		}

		internal static bool HandleLeftClick(Minimap map)
		{
			if (!Active || (Object)(object)map == (Object)null)
			{
				return false;
			}
			PortalInfo portalInfo = PortalUnderPointer(map);
			if (portalInfo != null)
			{
				Select(portalInfo);
				return true;
			}
			return IsSelecting;
		}

		internal static bool HandleRightClick(Minimap map)
		{
			if (!Active || (Object)(object)map == (Object)null)
			{
				return false;
			}
			PortalInfo portalInfo = PortalUnderPointer(map);
			if (portalInfo != null)
			{
				RowMenu(map, portalInfo);
				return true;
			}
			return IsSelecting;
		}

		private static PortalInfo PortalUnderPointer(Minimap map)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return PortalPins.Closest(Access.ScreenToWorldPoint(map, ZInput.pointerPosition), Access.PinInteractRadius(map));
		}

		private static void Select(PortalInfo p)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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)
			Minimap instance = Minimap.instance;
			if (p == null || (Object)(object)instance == (Object)null)
			{
				return;
			}
			switch (Current)
			{
			case Mode.Travel:
				if (p.Id == _sourceId || p.ZdoId == _sourceZdo)
				{
					TheGreatestPortalMod.Message("You are standing in that portal", always: true);
				}
				else if (Travel.Go(p, _sourceAllowAll, _sourceId))
				{
					instance.SetMapMode((MapMode)1);
					End();
				}
				break;
			case Mode.Pick:
			{
				if (p.Id == _sourceId || p.ZdoId == _sourceZdo)
				{
					TheGreatestPortalMod.Message("A portal cannot lead to itself", always: true);
					break;
				}
				Action<PortalInfo> onPicked = _onPicked;
				instance.SetMapMode((MapMode)1);
				End();
				onPicked?.Invoke(p);
				break;
			}
			default:
				CenterOn(p);
				break;
			}
		}

		private static UiKit.RowHandle RowFor(long id)
		{
			for (int i = 0; i < _rowIds.Count; i++)
			{
				if (_rowIds[i] == id)
				{
					return _rows[i];
				}
			}
			return null;
		}

		private static void CenterOn(PortalInfo p)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (p != null)
			{
				_highlightId = p.Id;
				PanTo(p.Pos);
				for (int i = 0; i < _rows.Count; i++)
				{
					_rows[i].SetSelected(_rowIds[i] == p.Id);
				}
			}
		}

		private static void PanTo(Vector3 worldPos)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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)
			Minimap instance = Minimap.instance;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)instance == (Object)null || (Object)(object)localPlayer == (Object)null || !Access.CanPan)
			{
				OpenMapAt(worldPos);