Decompiled source of MySix Core v1.0.18

MySix.Core.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Splatform;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("MySix.TestHarness")]
[assembly: InternalsVisibleTo("MySix.SelfTest")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace MySix
{
	internal static class ModVersion
	{
		public const string Value = "1.0.18";
	}
}
namespace MySix.Core
{
	public static class Compat
	{
		public static bool TakeOwnership(ZDO zdo)
		{
			if (zdo == null)
			{
				return false;
			}
			zdo.SetOwner(ZDOMan.GetSessionID());
			return zdo.IsOwner();
		}
	}
	internal static class ConfigSync
	{
		private const string RpcRequest = "MySix_ConfigRequest";

		private const string RpcValues = "MySix_ConfigValues";

		private const string RpcSet = "MySix_ConfigSet";

		private const string RpcReply = "MySix_ConfigReply";

		private static bool _registered;

		private static bool _requested;

		private static int _broadcasts;

		internal static int ValuesReceived;

		private static ZRpc _delivering;

		internal const string NotFromYou = "Your setting change was refused: it did not say it came from you.";

		internal static int Replies;

		internal static string LastReply = "";

		internal static bool SenderHooked { get; private set; }

		internal static void Register()
		{
			if (!_registered && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.Register<ZPackage>("MySix_ConfigRequest", (Action<long, ZPackage>)OnRequest);
				ZRoutedRpc.instance.Register<ZPackage>("MySix_ConfigValues", (Action<long, ZPackage>)OnValues);
				ZRoutedRpc.instance.Register<ZPackage>("MySix_ConfigSet", (Action<long, ZPackage>)OnSet);
				ZRoutedRpc.instance.Register<string>("MySix_ConfigReply", (Action<long, string>)OnReply);
				_registered = true;
			}
		}

		internal static void Reset()
		{
			_registered = false;
			_requested = false;
			Settings.ClearRemoteValues();
		}

		internal static void RequestIfNeeded()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			if (!_requested && _registered && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer())
			{
				ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
				if (serverPeer != null)
				{
					_requested = true;
					ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer.m_uid, "MySix_ConfigRequest", new object[1] { (object)new ZPackage() });
					CorePlugin.Log.LogInfo((object)"Asked the server for MySix settings");
				}
			}
		}

		private static void OnRequest(long sender, ZPackage _)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				SendValuesTo(sender);
			}
		}

		internal static void BroadcastValues()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			_broadcasts++;
			foreach (ZNetPeer item in from p in ZNet.instance.GetPeers()
				where p != null && !p.m_server && p.IsReady()
				select p)
			{
				SendValuesTo(item.m_uid);
			}
		}

		private static void SendValuesTo(long peerId)
		{
			//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();
			List<SettingBase> list = Settings.ServerOwned.ToList();
			val.Write(list.Count);
			foreach (SettingBase item in list)
			{
				val.Write(item.FullName);
				val.Write(item.ValueText);
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "MySix_ConfigValues", new object[1] { val });
		}

		private static void OnValues(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || pkg == null)
			{
				return;
			}
			int num = pkg.ReadInt();
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				string fullName = pkg.ReadString();
				string text = pkg.ReadString();
				SettingBase settingBase = Settings.Find(fullName);
				if (settingBase != null)
				{
					settingBase.ApplyRemoteText(text);
					num2++;
				}
			}
			ValuesReceived++;
			CorePlugin.Log.LogInfo((object)$"Applied {num2} server setting(s)");
		}

		internal static bool RequestSet(string fullName, string value, out string error)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			error = null;
			if (!_registered || (Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
			{
				error = "not connected to a server";
				return false;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer == null)
			{
				error = "no server connection";
				return false;
			}
			ZPackage val = new ZPackage();
			val.Write(fullName);
			val.Write(value);
			ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer.m_uid, "MySix_ConfigSet", new object[1] { val });
			return true;
		}

		private static void OnSet(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || pkg == null)
			{
				return;
			}
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			if (!FromSender(sender, out var from))
			{
				CorePlugin.Log.LogWarning((object)((from == 0L) ? $"Refused a setting change: the sender id {sender} did not come in on a player's connection: {text} = {text2}" : $"Refused a setting change: the sender id {sender} does not match the connection it came from (peer {from}): {text} = {text2}"));
				if (from != 0L)
				{
					Reply(from, "Your setting change was refused: it did not say it came from you.");
				}
				return;
			}
			if (!IsAdmin(sender))
			{
				CorePlugin.Log.LogWarning((object)$"Refused setting change from non-admin peer {sender}: {text} = {text2}");
				Reply(sender, "You must be a server admin to change MySix settings.");
				return;
			}
			SettingBase settingBase = Settings.Find(text);
			if (settingBase == null)
			{
				Reply(sender, "Unknown setting: " + text);
				return;
			}
			if (settingBase.Scope != Scope.Server)
			{
				Reply(sender, settingBase.FullName + " is a per-player setting; change it locally.");
				return;
			}
			int broadcasts = _broadcasts;
			if (!settingBase.TrySetFromText(text2, out var error))
			{
				Reply(sender, "Invalid value for " + settingBase.FullName + ": " + error);
				return;
			}
			CorePlugin.Log.LogInfo((object)$"Admin peer {sender} set {settingBase.FullName} = {settingBase.ValueText}");
			Reply(sender, settingBase.FullName + " = " + settingBase.ValueText);
			foreach (string item in JoinCheck.WarningsAbout(settingBase))
			{
				Reply(sender, item);
			}
			if (_broadcasts == broadcasts)
			{
				BroadcastValues();
			}
		}

		private static bool IsAdmin(long peerId)
		{
			ZNetPeer peer = ZNet.instance.GetPeer(peerId);
			if (peer?.m_socket == null)
			{
				return false;
			}
			return ZNet.instance.IsAdmin(peer.m_socket.GetHostName());
		}

		internal static void Install(Harmony harmony)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_0084: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(ZRoutedRpc), "RPC_RoutedRPC", new Type[2]
				{
					typeof(ZRpc),
					typeof(ZPackage)
				}, (Type[])null);
				if (methodInfo == null)
				{
					CorePlugin.Log.LogError((object)"MySix: the game has no ZRoutedRpc.RPC_RoutedRPC, so no setting for everyone can be changed with 'mysix set' from a player's game");
					return;
				}
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ConfigSync), "BeforeRouted", (Type[])null), new HarmonyMethod(typeof(ConfigSync), "AfterRouted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				SenderHooked = true;
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix: could not hook ZRoutedRpc.RPC_RoutedRPC, so no setting for everyone can be changed with 'mysix set' from a player's game: " + ex.Message));
			}
		}

		private static void BeforeRouted(ZRpc __0)
		{
			_delivering = __0;
		}

		private static void AfterRouted()
		{
			_delivering = null;
		}

		private static bool FromSender(long sender, out long from)
		{
			from = 0L;
			ZRpc rpc = _delivering;
			if (rpc == null)
			{
				return false;
			}
			from = ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p != null && p.m_rpc == rpc))?.m_uid ?? 0;
			if (from != 0L)
			{
				return from == sender;
			}
			return false;
		}

		private static void Reply(long peerId, string message)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "MySix_ConfigReply", new object[1] { message });
		}

		private static void OnReply(long sender, string message)
		{
			Replies++;
			LastReply = message ?? "";
			CorePlugin.Log.LogInfo((object)("Server: " + message));
			if ((Object)(object)Console.instance != (Object)null)
			{
				((Terminal)Console.instance).AddString("MySix: " + message);
			}
		}
	}
	internal static class ConsoleCommands
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEventFailable <>9__2_0;

			public static ConsoleOptionsFetcher <>9__2_1;

			public static Func<SettingBase, string> <>9__3_0;

			public static Func<SettingBase, string> <>9__5_0;

			public static Func<IGrouping<string, SettingBase>, string> <>9__5_1;

			internal object <RegisterIfNeeded>b__2_0(ConsoleEventArgs args)
			{
				return Run(args);
			}

			internal List<string> <RegisterIfNeeded>b__2_1()
			{
				return Options();
			}

			internal string <Options>b__3_0(SettingBase s)
			{
				return s.ShortName;
			}

			internal string <PrintList>b__5_0(SettingBase s)
			{
				return s.Feature;
			}

			internal string <PrintList>b__5_1(IGrouping<string, SettingBase> g)
			{
				return g.Key;
			}
		}

		private static bool _registered;

		private static readonly FieldRef<bool> TerminalInitialized = AccessTools.StaticFieldRefAccess<bool>(AccessTools.Field(typeof(Terminal), "m_terminalInitialized"));

		internal static void RegisterIfNeeded()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			if (_registered || !TerminalInitialized.Invoke())
			{
				return;
			}
			_registered = true;
			object obj = <>c.<>9__2_0;
			if (obj == null)
			{
				ConsoleEventFailable val = (ConsoleEventArgs args) => Run(args);
				<>c.<>9__2_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__2_1;
			if (obj2 == null)
			{
				ConsoleOptionsFetcher val2 = () => Options();
				<>c.<>9__2_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("mysix", "MySix mods: list settings, or 'get <setting>' / 'set <setting> <value>'", (ConsoleEventFailable)obj, false, false, false, false, true, false, (ConsoleOptionsFetcher)obj2, false, false, false);
			CorePlugin.Log.LogInfo((object)"Console command 'mysix' registered");
		}

		private static List<string> Options()
		{
			List<string> list = new List<string>();
			list.Add("get");
			list.Add("set");
			list.Add("list");
			list.AddRange(Settings.Known.Select((SettingBase s) => s.ShortName));
			return list;
		}

		private static object Run(ConsoleEventArgs args)
		{
			Terminal context = args.Context;
			switch ((args.Length > 1) ? args[1].ToLowerInvariant() : "list")
			{
			case "list":
				PrintList(context);
				return true;
			case "get":
			{
				if (args.Length < 3)
				{
					return Print(context, "usage: mysix get <setting>");
				}
				SettingBase settingBase2 = Settings.Find(args[2]);
				if (settingBase2 == null)
				{
					return Print(context, "unknown setting: " + args[2]);
				}
				return Print(context, Describe(settingBase2));
			}
			case "set":
			{
				if (args.Length < 4)
				{
					return Print(context, "usage: mysix set <setting> <value>");
				}
				SettingBase settingBase = Settings.Find(args[2]);
				if (settingBase == null)
				{
					return Print(context, "unknown setting: " + args[2]);
				}
				string text = string.Join(" ", args.Args.Skip(3).ToArray());
				bool flag = (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer();
				if (settingBase.Scope == Scope.Server && flag)
				{
					if (!ConfigSync.RequestSet(settingBase.FullName, text, out var error))
					{
						return Print(context, "could not reach the server: " + error);
					}
					return Print(context, "asked the server to set " + settingBase.FullName + " to " + text);
				}
				if (!settingBase.TrySetFromText(text, out var error2))
				{
					return Print(context, "invalid value for " + settingBase.FullName + ": " + error2);
				}
				if (settingBase.Scope == Scope.Server)
				{
					ConfigSync.BroadcastValues();
				}
				Print(context, settingBase.FullName + " = " + settingBase.ValueText);
				if (WorldSettings.HostOnly.Contains(settingBase.FullName))
				{
					Print(context, "this changes this computer's settings file only; a running server is switched by an admin who is connected, or with joincheck.txt");
				}
				return true;
			}
			default:
				return Print(context, "usage: mysix [list | get <setting> | set <setting> <value>]");
			}
		}

		private static void PrintList(Terminal ctx)
		{
			List<SettingBase> list = Settings.Known.ToList();
			if (list.Count == 0)
			{
				Print(ctx, "MySix: no features registered any settings");
				return;
			}
			Print(ctx, string.Format("MySix {0} - {1} setting(s):", "1.0.18", list.Count));
			foreach (IGrouping<string, SettingBase> item in (from s in list
				group s by s.Feature).OrderBy<IGrouping<string, SettingBase>, string>((IGrouping<string, SettingBase> g) => g.Key, StringComparer.OrdinalIgnoreCase))
			{
				Print(ctx, "  " + item.Key);
				foreach (SettingBase item2 in item)
				{
					Print(ctx, "    " + item2.ShortName + " = " + item2.ValueText + (item2.IsRemote ? "  (from server)" : ""));
				}
			}
			Print(ctx, "use 'mysix get <setting>' for details, 'mysix set <setting> <value>' to change one");
		}

		private static string Describe(SettingBase s)
		{
			return s.FullName + " = " + s.ValueText + "  [" + s.TypeHint + ", default " + s.DefaultText + ", " + ((s.Scope == Scope.Server) ? "server-owned" : "per-player") + (s.IsRemote ? ", currently from the server" : "") + "]" + (string.IsNullOrEmpty(s.Description) ? "" : (Environment.NewLine + "   " + s.Description));
		}

		private static bool Print(Terminal ctx, string text)
		{
			if ((Object)(object)ctx != (Object)null)
			{
				ctx.AddString(text);
			}
			else
			{
				CorePlugin.Log.LogInfo((object)text);
			}
			return true;
		}
	}
	public enum Role
	{
		Unknown,
		DedicatedServer,
		Host,
		Client
	}
	[BepInPlugin("com.mysix.core", "MySix Core", "1.0.18")]
	public class CorePlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.mysix.core";

		public const string PluginName = "MySix Core";

		public const string PluginVersion = "1.0.18";

		public const int ApiVersion = 3;

		private static bool _readyRaised;

		private ConfigEntry<float> _cycleSeconds;

		private ConfigEntry<int> _maxObjectsPerFrame;

		private ConfigEntry<bool> _requireMods;

		private ConfigEntry<string> _notRequired;

		internal static readonly HashSet<string> RefusedFeatures = new HashSet<string>(StringComparer.Ordinal);

		private readonly Restart _restart = new Restart();

		public static CorePlugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		public static Role Role { get; private set; } = Role.Unknown;

		public static bool IsServerSide
		{
			get
			{
				if (Role != Role.DedicatedServer)
				{
					return Role == Role.Host;
				}
				return true;
			}
		}

		public static bool IsPlayerSide
		{
			get
			{
				if (Role != Role.Host)
				{
					return Role == Role.Client;
				}
				return true;
			}
		}

		public static bool IsRemoteClient => Role == Role.Client;

		public WorldScanner Scanner { get; } = new WorldScanner();

		public static event Action<Role> Ready;

		private void Awake()
		{
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			_cycleSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Scanner", "CycleSeconds", 600f, "How long one full pass over the world takes on the server. Work is spread evenly across it.");
			_maxObjectsPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>("Scanner", "MaxObjectsPerFrame", 2000, "Safety cap on objects inspected in a single frame (only matters if a pass falls behind).");
			Settings.Register<float>("MySix Core", _cycleSeconds, Scope.Server, "Seconds for one full world pass on the server.");
			Settings.Register<int>("MySix Core", _maxObjectsPerFrame, Scope.Server, "Maximum objects inspected per frame.");
			_requireMods = ((BaseUnityPlugin)this).Config.Bind<bool>("JoinCheck", "RequireMods", false, "On a dedicated server: turn away players who lack a mod the server needs, or have an older version of one. Off: nobody is turned away; the server only logs whom it would turn away. Can also be switched with a file named joincheck.txt in BepInEx\\config\\MySix.Core whose first line is on or off.");
			_notRequired = ((BaseUnityPlugin)this).Config.Bind<string>("JoinCheck", "NotRequired", "", "Mods never asked of players, separated by commas: their GUIDs, or their names as the join check's log lines show them (or as the mod or its package calls itself).");
			JoinCheck.RequireMods = Settings.Register<bool>("MySix Core", _requireMods, Scope.Server, "Turn away players who lack a mod this dedicated server needs, or have an older one (off: only logged).");
			JoinCheck.NotRequired = Settings.Register<string>("MySix Core", _notRequired, Scope.Server, "Mods never asked of players: GUIDs, or names as the join check's log shows them, separated by commas.");
			WorldSettings.HostOnly.Add(JoinCheck.RequireMods.FullName);
			WorldSettings.HostOnly.Add(JoinCheck.NotRequired.FullName);
			JoinCheck.RequireMods.Changed += delegate
			{
				JoinCheck.SettingChanged();
			};
			JoinCheck.NotRequired.Changed += delegate
			{
				JoinCheck.SettingChanged();
			};
			Harmony val = new Harmony("com.mysix.core.world");
			val.PatchAll(typeof(LoadWorldSettings));
			val.PatchAll(typeof(SaveWorldSettings));
			Texts.Load(typeof(CorePlugin).Assembly, "Texts.txt");
			Harmony harmony = new Harmony("com.mysix.core.joincheck");
			try
			{
				JoinCheck.Install(harmony);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("The join check could not be set up: " + ex));
			}
			try
			{
				ConfigSync.Install(harmony);
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("The check on who changes a setting could not be set up: " + ex2));
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0} {1} loaded (API {2})", "MySix Core", "1.0.18", 3));
		}

		public static bool RequireApi(string featureName, int requiredApiVersion)
		{
			if (requiredApiVersion <= 3)
			{
				return true;
			}
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogError((object)($"{featureName} needs MySix Core API {requiredApiVersion}, but this is Core " + string.Format("{0} (API {1}). Update MySix.Core.dll; {2} is disabled.", "1.0.18", 3, featureName)));
			}
			if (featureName != null)
			{
				RefusedFeatures.Add(featureName);
			}
			return false;
		}

		private void Update()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				if (Role != Role.Unknown)
				{
					Role = Role.Unknown;
					_readyRaised = false;
					ConfigSync.Reset();
					WorldSettings.Unload();
					WorldPlayerSettings.Unload();
					WorldPlayerSettings.Reset();
				}
				return;
			}
			if (Role == Role.Unknown)
			{
				Role = (instance.IsDedicated() ? Role.DedicatedServer : (instance.IsServer() ? Role.Host : Role.Client));
			}
			ConfigSync.Register();
			ConsoleCommands.RegisterIfNeeded();
			if (!_readyRaised)
			{
				_readyRaised = true;
				try
				{
					CorePlugin.Ready?.Invoke(Role);
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Ready handler failed: " + ex));
				}
			}
			if (IsRemoteClient)
			{
				ConfigSync.RequestIfNeeded();
			}
			try
			{
				WorldPlayerSettings.Tick();
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Player settings failed: " + ex2));
			}
			if (Role == Role.DedicatedServer)
			{
				try
				{
					_restart.Tick(Time.realtimeSinceStartup);
				}
				catch (Exception ex3)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Restart failed: " + ex3));
				}
				try
				{
					JoinCheck.Tick(Time.realtimeSinceStartup);
				}
				catch (Exception ex4)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Join check failed: " + ex4));
				}
			}
			if (!IsServerSide || !Scanner.HasConsumers)
			{
				return;
			}
			try
			{
				Scanner.Tick(Time.realtimeSinceStartup, _cycleSeconds.Value, _maxObjectsPerFrame.Value);
			}
			catch (Exception ex5)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("World scan failed: " + ex5));
			}
		}

		public static void PushSettingsToPlayers()
		{
			ConfigSync.BroadcastValues();
		}

		internal static bool TakeOwnership(ZDO zdo)
		{
			zdo.SetOwner(ZDOMan.GetSessionID());
			return zdo.IsOwner();
		}
	}
	internal static class JoinCheck
	{
		internal sealed class Mod
		{
			public string Guid = "";

			public string Name = "";

			public string Version;

			public string Why;

			public override string ToString()
			{
				return Name + (string.IsNullOrEmpty(Version) ? "" : (" " + Version));
			}
		}

		internal sealed class Report
		{
			public string Core = "";

			public readonly Dictionary<string, string> Loaded = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

			public readonly Dictionary<string, string> NotRunning = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

			public string Unreadable;
		}

		internal enum Kind
		{
			Missing,
			Older,
			Unreadable,
			NotRunning
		}

		internal sealed class Problem
		{
			public Kind Kind;

			public string Guid = "";

			public string Name = "";

			public string Needed = "";

			public string Theirs = "";

			public string English()
			{
				return Kind switch
				{
					Kind.Missing => "missing " + Name + " " + Needed + " (" + Guid + ")", 
					Kind.Older => "older " + Name + " " + Theirs + ", needs " + Needed + " (" + Guid + ")", 
					Kind.NotRunning => "installed but not running " + Name + " " + Theirs + " (" + Guid + ")", 
					_ => "its report could not be read (" + Theirs + ")", 
				};
			}
		}

		private sealed class Visit
		{
			public Report Report;

			public bool Passed;

			public bool Refused;

			public float RefusedAt;

			public string Who = "?";
		}

		private sealed class PeerInfo
		{
			public bool VersionReadable;

			public bool Complete;

			public uint Network;

			public string Name;

			public string Password;

			public string InviteKey;
		}

		private sealed class Layout
		{
			public RectTransform Box;

			public RectTransform Text;

			public RectTransform Ok;

			public Vector2 BoxSize;

			public Vector2 TextMin;

			public Vector2 TextMax;

			public Vector2 OkMin;

			public Vector2 OkMax;
		}

		private const string RpcReport = "MySix_JoinReport";

		private const string RpcRefused = "MySix_JoinRefused";

		private const int Format = 1;

		private const int MaxLines = 8;

		private const int MaxGuid = 200;

		private const float CloseAfter = 10f;

		internal static Setting<bool> RequireMods;

		internal static Setting<string> NotRequired;

		private static readonly HashSet<string> NeverAsked = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "com.mysix.modsnotcheating", "com.mysix.accessibilityshield", "com.mysix.selftest", "com.mysix.probe", "com.mysix.testharness", "com.mysix.admindevcommands", "com.mysix.lightfuel", "com.mysix.feedback" };

		internal static List<Mod> Required = new List<Mod>();

		internal static List<Mod> NotAsked = new List<Mod>();

		internal static List<string> Warnings = new List<string>();

		private static string _builtFrom;

		private static readonly ConditionalWeakTable<ZRpc, Visit> Visits = new ConditionalWeakTable<ZRpc, Visit>();

		private static readonly List<KeyValuePair<ZRpc, Visit>> Closing = new List<KeyValuePair<ZRpc, Visit>>();

		private static bool _started;

		private static bool _loggedOn;

		private static MethodInfo _getPeer;

		private static MethodInfo _isAllowed;

		private static FieldInfo _serverPassword;

		private static uint? _network;

		private static readonly HashSet<string> Warned = new HashSet<string>();

		private static float _nextLook;

		private static bool _hookConnection;

		private static bool _hookPeerInfo;

		private static bool _hookMenu;

		internal static int Attempts;

		private static List<Problem> _refusal;

		private static string _gameText;

		private static Layout _gameLayout;

		internal static List<Problem> LastRefusal = new List<Problem>();

		internal static string LastShown = "";

		internal static int LastLines;

		internal static bool LastOverflowing;

		internal static bool PretendPlain;

		internal static readonly HashSet<string> PretendMissing = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		internal static readonly Dictionary<string, string> PretendVersions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		internal static readonly HashSet<string> PretendRefusedFeature = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		internal static bool PretendGarbageReport;

		private const float MinFontSize = 12f;

		private static string SwitchFile => Path.Combine(Paths.ConfigPath, "MySix.Core", "joincheck.txt");

		internal static bool HooksInPlace
		{
			get
			{
				if (_hookConnection && _hookPeerInfo && _hookMenu)
				{
					return ConfigSync.SenderHooked;
				}
				return false;
			}
		}

		internal static void Build()
		{
			List<Mod> list = new List<Mod>();
			List<Mod> list2 = new List<Mod>();
			List<string> warnings = new List<string>();
			string text = NotRequired?.Value ?? "";
			HashSet<string> hashSet = LeftOut(text, warnings);
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.Where((PluginInfo i) => ((i != null) ? i.Metadata : null) != null).OrderBy<PluginInfo, string>((PluginInfo i) => i.Metadata.GUID, StringComparer.Ordinal))
			{
				if (!((Object)(object)item.Instance == (Object)null))
				{
					Mod mod = new Mod
					{
						Guid = item.Metadata.GUID,
						Name = NameOf(item),
						Version = item.Metadata.Version?.ToString()
					};
					mod.Why = (CorePlugin.RefusedFeatures.Contains(item.Metadata.Name) ? "turned away by this server's Core" : (ServerOnly(item) ? "runs only in valheim_server" : (NeverAsked.Contains(mod.Guid) ? "optional for players (Core's own list)" : (TaggedOptional(item) ? "optional for players" : (hashSet.Contains(mod.Guid) ? "left out by Core.NotRequired" : null)))));
					((mod.Why == null) ? list : list2).Add(mod);
				}
			}
			Required = list;
			NotAsked = list2;
			Warnings = warnings;
			_builtFrom = text;
		}

		private static HashSet<string> LeftOut(string text, List<string> warnings)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = text.Split(new char[1] { ',' });
			foreach (string text2 in array)
			{
				string entry = text2.Trim();
				if (entry.Length == 0)
				{
					continue;
				}
				string text3 = Chainloader.PluginInfos.Keys.FirstOrDefault((string g) => string.Equals(g, entry, StringComparison.OrdinalIgnoreCase));
				if (text3 != null)
				{
					hashSet.Add(text3);
					continue;
				}
				List<PluginInfo> list = Chainloader.PluginInfos.Values.Where((PluginInfo val) => ((val != null) ? val.Metadata : null) != null && NamesOf(val).Contains(entry)).ToList();
				if (list.Count == 1)
				{
					hashSet.Add(list[0].Metadata.GUID);
					continue;
				}
				if (list.Count == 0)
				{
					warnings.Add("Core.NotRequired: '" + entry + "' matches no loaded mod, so it leaves nothing out; name a mod by its GUID, or as this log names it");
					continue;
				}
				warnings.Add(string.Format("Core.NotRequired: '{0}' matches {1} mods ({2}), ", entry, list.Count, string.Join(", ", list.Select((PluginInfo val) => val.Metadata.GUID))) + "so it leaves nothing out; name one by its GUID");
			}
			return hashSet;
		}

		private static List<string> NamesOf(PluginInfo info)
		{
			string text = NameOf(info);
			List<string> list = new List<string>
			{
				info.Metadata.Name,
				text
			};
			if (IsMySix(info.Metadata.GUID))
			{
				list.Add(text.Replace(' ', '_'));
			}
			return list;
		}

		private static string NameOf(PluginInfo info)
		{
			if (IsMySix(info.Metadata.GUID) && (Object)(object)info.Instance != (Object)null)
			{
				string name = ((object)info.Instance).GetType().Assembly.GetName().Name;
				if (name.StartsWith("MySix.", StringComparison.Ordinal))
				{
					return name.Replace('.', ' ');
				}
			}
			return info.Metadata.Name;
		}

		internal static List<string> WarningsAbout(SettingBase setting)
		{
			if (!_started || setting == null || setting != NotRequired)
			{
				return new List<string>();
			}
			return Warnings;
		}

		internal static bool IsMySix(string guid)
		{
			return (guid ?? "").StartsWith("com.mysix.", StringComparison.OrdinalIgnoreCase);
		}

		private static bool ServerOnly(PluginInfo info)
		{
			List<string> list = (from p in info.Processes ?? Enumerable.Empty<BepInProcess>()
				where p != null
				select p.ProcessName ?? "").ToList();
			if (list.Count > 0)
			{
				return !list.Any((string p) => Path.GetFileNameWithoutExtension(p).Equals("valheim", StringComparison.OrdinalIgnoreCase));
			}
			return false;
		}

		private static bool TaggedOptional(PluginInfo info)
		{
			return ((object)info.Instance).GetType().Assembly.GetCustomAttributes(typeof(AssemblyMetadataAttribute), inherit: false).OfType<AssemblyMetadataAttribute>().Any((AssemblyMetadataAttribute a) => a.Key == "MySix.Players" && string.Equals(a.Value, "optional", StringComparison.OrdinalIgnoreCase));
		}

		internal static ZPackage BuildReport(out int count)
		{
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			List<KeyValuePair<string, string>> list2 = new List<KeyValuePair<string, string>>();
			foreach (PluginInfo value3 in Chainloader.PluginInfos.Values)
			{
				if (((value3 != null) ? value3.Metadata : null) != null && !((Object)(object)value3.Instance == (Object)null))
				{
					string gUID = value3.Metadata.GUID;
					if (!PretendMissing.Contains(gUID))
					{
						string value2;
						string value = (PretendVersions.TryGetValue(gUID, out value2) ? value2 : (value3.Metadata.Version?.ToString() ?? ""));
						((!CorePlugin.RefusedFeatures.Contains(value3.Metadata.Name) && !PretendRefusedFeature.Contains(gUID)) ? list : list2).Add(new KeyValuePair<string, string>(gUID, value));
					}
				}
			}
			ZPackage val = new ZPackage();
			val.Write(1);
			val.Write("1.0.18");
			count = list.Count;
			if (PretendGarbageReport)
			{
				val.Write(list.Count + 5);
				Write(val, list.Take(1));
				return val;
			}
			val.Write(list.Count);
			Write(val, list);
			val.Write(list2.Count);
			Write(val, list2);
			return val;
		}

		private static void Write(ZPackage pkg, IEnumerable<KeyValuePair<string, string>> pairs)
		{
			foreach (KeyValuePair<string, string> pair in pairs)
			{
				pkg.Write(pair.Key);
				pkg.Write(pair.Value ?? "");
			}
		}

		internal static Report ReadReport(ZPackage pkg)
		{
			Report report = new Report();
			try
			{
				int num = pkg.ReadInt();
				if (num < 1)
				{
					throw new InvalidDataException("format " + num);
				}
				report.Core = Clean(pkg.ReadString());
				ReadPairs(pkg, report.Loaded);
				ReadPairs(pkg, report.NotRunning);
			}
			catch (Exception ex)
			{
				report.Unreadable = ex.GetType().Name + ": " + ex.Message;
			}
			return report;
		}

		private static void ReadPairs(ZPackage pkg, Dictionary<string, string> into)
		{
			int num = pkg.ReadInt();
			if (num < 0 || num > 2000)
			{
				throw new InvalidDataException("a list of " + num);
			}
			for (int i = 0; i < num; i++)
			{
				string key = Clean(pkg.ReadString(), 200);
				into[key] = Clean(pkg.ReadString());
			}
		}

		internal static List<Problem> Compare(Report report)
		{
			List<Problem> list = new List<Problem>();
			if (report.Unreadable != null)
			{
				list.Add(new Problem
				{
					Kind = Kind.Unreadable,
					Needed = "1.0.18",
					Theirs = report.Unreadable
				});
				return list;
			}
			foreach (Mod item in Required)
			{
				string needed = item.Version ?? "";
				string value2;
				if (report.NotRunning.TryGetValue(item.Guid, out var value))
				{
					list.Add(new Problem
					{
						Kind = Kind.NotRunning,
						Guid = item.Guid,
						Name = item.Name,
						Needed = needed,
						Theirs = (value ?? "")
					});
				}
				else if (!report.Loaded.TryGetValue(item.Guid, out value2))
				{
					list.Add(new Problem
					{
						Kind = Kind.Missing,
						Guid = item.Guid,
						Name = item.Name,
						Needed = needed
					});
				}
				else if (IsOlder(value2, item.Version))
				{
					list.Add(new Problem
					{
						Kind = Kind.Older,
						Guid = item.Guid,
						Name = item.Name,
						Needed = needed,
						Theirs = (value2 ?? "")
					});
				}
			}
			return list;
		}

		internal static bool IsOlder(string theirs, string needed)
		{
			int[] array = Numbers(needed);
			if (array == null)
			{
				return false;
			}
			int[] array2 = Numbers(theirs);
			if (array2 == null)
			{
				return true;
			}
			for (int i = 0; i < Math.Max(array.Length, array2.Length); i++)
			{
				int num = ((i < array2.Length) ? array2[i] : 0);
				int num2 = ((i < array.Length) ? array[i] : 0);
				if (num != num2)
				{
					return num < num2;
				}
			}
			return false;
		}

		private static int[] Numbers(string version)
		{
			if (string.IsNullOrWhiteSpace(version))
			{
				return null;
			}
			string[] array = version.Trim().Split(new char[1] { '.' });
			int[] array2 = new int[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				if (!int.TryParse(array[i], NumberStyles.None, CultureInfo.InvariantCulture, out array2[i]))
				{
					return null;
				}
			}
			return array2;
		}

		private static void OnReport(ZRpc rpc, ZPackage pkg)
		{
			if (rpc != null && pkg != null)
			{
				Visits.GetOrCreateValue(rpc).Report = ReadReport(pkg);
			}
		}

		private static bool BeforePeerInfo(ZNet __instance, ZRpc __0, ZPackage __1)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || __0 == null || __1 == null || !__instance.IsServer() || !__instance.IsDedicated())
				{
					return true;
				}
				ZNetPeer val = PeerOf(__instance, __0);
				if (val == null)
				{
					return true;
				}
				Visit orCreateValue = Visits.GetOrCreateValue(__0);
				if (orCreateValue.Refused)
				{
					return false;
				}
				PeerInfo peerInfo = Read(__1);
				if (peerInfo != null && GameRefusesFirst(__instance, val, peerInfo))
				{
					return true;
				}
				orCreateValue.Who = Who(val, peerInfo?.Name);
				List<Problem> list = null;
				bool flag = false;
				string text;
				try
				{
					if (_builtFrom == null)
					{
						Build();
					}
					if (orCreateValue.Report == null)
					{
						text = "no report from MySix Core (the game without mods, or MySix Core older than 1.0.18)";
					}
					else
					{
						list = Compare(orCreateValue.Report);
						text = string.Join("; ", list.Select((Problem p) => p.English()).ToArray());
					}
				}
				catch (Exception ex)
				{
					flag = true;
					list = null;
					text = "the check itself failed (" + ex.Message + ")";
				}
				bool flag2 = !flag && list != null && list.Count == 0;
				if (RequireMods == null || !RequireMods.Value)
				{
					Info(flag2 ? $"would let in {orCreateValue.Who}: has all {Required.Count} needed mods" : ("would turn away " + orCreateValue.Who + ": " + text));
					return true;
				}
				if (flag2)
				{
					orCreateValue.Passed = true;
					return true;
				}
				Refuse(__0, orCreateValue, flag ? null : list, text);
				return false;
			}
			catch (Exception ex2)
			{
				CorePlugin.Log.LogError((object)("MySix join check: failed, so the game decides on its own: " + ex2));
				return true;
			}
		}

		private static void AfterPeerInfo(ZNet __instance, ZRpc __0)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null) && __0 != null && __instance.IsServer() && __instance.IsDedicated() && Visits.TryGetValue(__0, out var value) && value.Passed)
				{
					value.Passed = false;
					ZNetPeer val = PeerOf(__instance, __0);
					if (val != null && val.IsReady())
					{
						Info($"let in {value.Who}: has all {Required.Count} needed mods");
					}
					else
					{
						Info(value.Who + " passed the mod check, but the game or another mod turned them away");
					}
				}
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogWarning((object)("MySix join check: could not log a join: " + ex.Message));
			}
		}

		private static void Refuse(ZRpc rpc, Visit visit, List<Problem> problems, string reasons)
		{
			if (problems != null && visit.Report != null)
			{
				try
				{
					rpc.Invoke("MySix_JoinRefused", new object[1] { Refusal(problems) });
				}
				catch (Exception ex)
				{
					CorePlugin.Log.LogWarning((object)("MySix join check: could not send the list of mods: " + ex.Message));
				}
			}
			try
			{
				rpc.Invoke("Error", new object[1] { 3 });
			}
			catch (Exception ex2)
			{
				CorePlugin.Log.LogWarning((object)("MySix join check: could not send the error: " + ex2.Message));
			}
			visit.Refused = true;
			visit.RefusedAt = Time.realtimeSinceStartup;
			Closing.Add(new KeyValuePair<ZRpc, Visit>(rpc, visit));
			CorePlugin.Log.LogWarning((object)("MySix join check: turned away " + visit.Who + ": " + reasons));
		}

		private static ZPackage Refusal(List<Problem> problems)
		{
			//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("1.0.18");
			val.Write(problems.Count);
			foreach (Problem problem in problems)
			{
				val.Write((int)problem.Kind);
				val.Write(problem.Guid ?? "");
				val.Write(problem.Name ?? "");
				val.Write(problem.Needed ?? "");
				val.Write(problem.Theirs ?? "");
			}
			return val;
		}

		private static string Who(ZNetPeer peer, string name)
		{
			string text = "";
			string text2 = "";
			try
			{
				ISocket socket = peer.m_socket;
				text = ((socket != null) ? socket.GetHostName() : null) ?? "";
				ISocket socket2 = peer.m_socket;
				text2 = ((socket2 != null) ? socket2.GetEndPointString() : null) ?? "";
			}
			catch (Exception)
			{
			}
			return (string.IsNullOrEmpty(name) ? "?" : Clean(name)) + " (" + text + ((text2.Length > 0 && text2 != text) ? (", " + text2) : "") + ")";
		}

		private static PeerInfo Read(ZPackage pkg)
		{
			int pos = pkg.GetPos();
			try
			{
				return ReadFields(pkg);
			}
			catch (Exception ex)
			{
				WarnOnce("read", "could not read a request to join, so the game's own version, ban and password checks may come after the mod check: " + ex.Message);
				return null;
			}
			finally
			{
				pkg.SetPos(pos);
			}
		}

		private static PeerInfo ReadFields(ZPackage pkg)
		{
			//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)
			//IL_005f: 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)
			PeerInfo peerInfo = new PeerInfo();
			pkg.ReadLong();
			GameVersion val = default(GameVersion);
			if (!GameVersion.TryParseGameVersion(pkg.ReadString(), ref val) || val < Version.FirstVersionWithNetworkVersion)
			{
				return peerInfo;
			}
			peerInfo.VersionReadable = true;
			peerInfo.Network = pkg.ReadUInt();
			if (_network.HasValue && peerInfo.Network != _network.Value)
			{
				return peerInfo;
			}
			pkg.ReadVector3();
			peerInfo.Name = pkg.ReadString();
			pkg.ReadString();
			SimulationDistance.Deserialize(ref pkg);
			peerInfo.Password = pkg.ReadString();
			peerInfo.InviteKey = pkg.ReadString();
			peerInfo.Complete = true;
			return peerInfo;
		}

		private static bool GameRefusesFirst(ZNet znet, ZNetPeer peer, PeerInfo info)
		{
			if (!info.VersionReadable || (_network.HasValue && info.Network != _network.Value))
			{
				return true;
			}
			if (!info.Complete)
			{
				return false;
			}
			try
			{
				if (_isAllowed != null && !(bool)_isAllowed.Invoke(znet, new object[2]
				{
					peer.m_socket.GetHostName(),
					info.Name
				}))
				{
					return true;
				}
			}
			catch (Exception e)
			{
				WarnOnce("allowed", "could not ask the game whether a player is banned, so a ban may be checked after the mods: " + Inner(e));
			}
			bool flag = false;
			try
			{
				flag = _serverPassword != null && (string)_serverPassword.GetValue(null) != info.Password;
			}
			catch (Exception e2)
			{
				WarnOnce("password", "could not compare a password, so a wrong one may be checked after the mods: " + Inner(e2));
			}
			if (!flag || string.IsNullOrEmpty(info.InviteKey))
			{
				return flag;
			}
			try
			{
				return !InviteTaken(info.InviteKey);
			}
			catch (Exception e3)
			{
				WarnOnce("invite", "could not ask the game whether an invite stands in for the password, so a player with the wrong password and an invite is checked for mods first: " + Inner(e3));
				return false;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool InviteTaken(string key)
		{
			IDistributionPlatform distributionPlatform = PlatformManager.DistributionPlatform;
			if (distributionPlatform == null)
			{
				return false;
			}
			IMatchmakingProvider matchmakingProvider = distributionPlatform.MatchmakingProvider;
			return ((matchmakingProvider != null) ? new bool?(matchmakingProvider.SecretKeyOk(key)) : ((bool?)null)) == true;
		}

		private static ZNetPeer PeerOf(ZNet znet, ZRpc rpc)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (_getPeer != null)
			{
				try
				{
					return (ZNetPeer)_getPeer.Invoke(znet, new object[1] { rpc });
				}
				catch (Exception e)
				{
					WarnOnce("getpeer", "ZNet.GetPeer failed, so the connection is looked up by hand: " + Inner(e));
				}
			}
			return ((IEnumerable<ZNetPeer>)znet.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p != null && p.m_rpc == rpc));
		}

		private static string Inner(Exception e)
		{
			return ((e is TargetInvocationException && e.InnerException != null) ? e.InnerException : e).Message;
		}

		private static void WarnOnce(string what, string text)
		{
			if (Warned.Add(what))
			{
				CorePlugin.Log.LogWarning((object)("MySix join check: " + text));
			}
		}

		private static void Info(string text)
		{
			CorePlugin.Log.LogInfo((object)("MySix join check: " + text));
		}

		internal static void ServerStarted()
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsDedicated())
			{
				ReadSwitch();
				Build();
				_started = true;
				LogHooks();
				LogState("");
			}
		}

		internal static void Tick(float now)
		{
			if (now >= _nextLook)
			{
				_nextLook = now + 2f;
				ReadSwitch();
			}
			if (Closing.Count == 0 || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			for (int num = Closing.Count - 1; num >= 0; num--)
			{
				ZRpc rpc = Closing[num].Key;
				Visit value = Closing[num].Value;
				if (!(now - value.RefusedAt < 10f))
				{
					Closing.RemoveAt(num);
					ZNetPeer val = ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p != null && p.m_rpc == rpc));
					if (val != null && !val.IsReady())
					{
						ZNet.instance.Disconnect(val);
						Info($"closed the connection of turned-away {value.Who}: still connected {10f:0} s after being turned away");
					}
				}
			}
		}

		private static void ReadSwitch()
		{
			string switchFile = SwitchFile;
			try
			{
				if (File.Exists(switchFile))
				{
					string[] array = File.ReadAllLines(switchFile);
					File.Delete(switchFile);
					string text = ((array.Length != 0) ? array[0].Trim().ToLowerInvariant() : "");
					if (text != "on" && text != "off")
					{
						CorePlugin.Log.LogWarning((object)("MySix join check: joincheck.txt says '" + Clean(text) + "', not 'on' or 'off': ignored, and the file deleted"));
					}
					else if (RequireMods != null)
					{
						bool flag = text == "on";
						bool value = RequireMods.Value;
						Info("switched " + (flag ? "ON" : "OFF") + " by joincheck.txt" + ((value == flag) ? " (it already was)" : ""));
						RequireMods.TrySetFromText(flag ? "true" : "false", out var _);
					}
				}
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix join check: could not read joincheck.txt: " + ex.Message));
			}
		}

		internal static void SettingChanged()
		{
			if (!_started || RequireMods == null)
			{
				return;
			}
			string text = NotRequired?.Value ?? "";
			if (RequireMods.Value != _loggedOn || !(text == _builtFrom))
			{
				if (text != _builtFrom)
				{
					Build();
				}
				LogState("now ");
			}
		}

		private static void LogState(string now)
		{
			bool num = (_loggedOn = RequireMods != null && RequireMods.Value);
			string text = string.Join(", ", Required.Select((Mod m) => m.ToString()).ToArray());
			if (num)
			{
				Info($"{now}ON - players must have these {Required.Count} mods, at these versions or newer: {text}");
			}
			else
			{
				Info(now + "OFF (Core.RequireMods = false): nobody is turned away; joins are only logged. Turned on, it would require: " + text);
			}
			if (NotAsked.Count > 0)
			{
				Info("not asked of players: " + string.Join(", ", NotAsked.Select((Mod m) => $"{m} ({m.Why})").ToArray()));
			}
			foreach (string warning in Warnings)
			{
				CorePlugin.Log.LogWarning((object)("MySix join check: " + warning));
			}
		}

		internal static void Install(Harmony harmony)
		{
			_hookConnection = Patch(harmony, typeof(ZNet), "OnNewConnection", new Type[1] { typeof(ZNetPeer) }, null, Hook("AfterNewConnection", 400));
			_hookPeerInfo = Patch(harmony, typeof(ZNet), "RPC_PeerInfo", new Type[2]
			{
				typeof(ZRpc),
				typeof(ZPackage)
			}, Hook("BeforePeerInfo", 800), Hook("AfterPeerInfo", 400));
			_hookMenu = Patch(harmony, typeof(FejdStartup), "ShowConnectError", new Type[1] { typeof(ConnectionStatus) }, null, Hook("RecordGameText", 800)) && Patch(harmony, typeof(FejdStartup), "ShowConnectError", new Type[1] { typeof(ConnectionStatus) }, null, Hook("ShowRefusal", 0));
			_getPeer = AccessTools.Method(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null);
			_isAllowed = AccessTools.Method(typeof(ZNet), "IsAllowed", new Type[2]
			{
				typeof(string),
				typeof(string)
			}, (Type[])null);
			_serverPassword = AccessTools.Field(typeof(ZNet), "m_serverPassword");
			try
			{
				object obj = typeof(Version).GetField("c_networkVersion", BindingFlags.Static | BindingFlags.Public)?.GetRawConstantValue();
				if (obj != null)
				{
					_network = Convert.ToUInt32(obj, CultureInfo.InvariantCulture);
				}
			}
			catch (Exception)
			{
				_network = null;
			}
		}

		private static HarmonyMethod Hook(string method, int priority)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.Method(typeof(JoinCheck), method, (Type[])null, (Type[])null))
			{
				priority = priority
			};
		}

		private static bool Patch(Harmony harmony, Type type, string method, Type[] args, HarmonyMethod prefix, HarmonyMethod postfix)
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, args, (Type[])null);
				if (methodInfo == null)
				{
					CorePlugin.Log.LogError((object)("MySix join check: the game has no " + type.Name + "." + method));
					return false;
				}
				harmony.Patch((MethodBase)methodInfo, prefix, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix join check: could not hook " + type.Name + "." + method + ": " + ex.Message));
				return false;
			}
		}

		private static void LogHooks()
		{
			List<string> list = new List<string>();
			if (!_hookPeerInfo)
			{
				list.Add("ZNet.RPC_PeerInfo is not hooked: nobody can be turned away");
			}
			if (!_hookConnection)
			{
				list.Add("ZNet.OnNewConnection is not hooked: no player's mods reach the server, so with Core.RequireMods on every player is turned away");
			}
			if (!ConfigSync.SenderHooked)
			{
				list.Add("ZRoutedRpc.RPC_RoutedRPC is not hooked: no setting for everyone can be changed with 'mysix set' from a player's game; use joincheck.txt or the settings file");
			}
			if (!_network.HasValue)
			{
				list.Add("the game's network version could not be read: a player on the wrong game version is checked for mods before the game turns them away");
			}
			if (_isAllowed == null)
			{
				list.Add("ZNet.IsAllowed is missing: a banned player is checked for mods before the game turns them away");
			}
			if (_serverPassword == null)
			{
				list.Add("ZNet.m_serverPassword is missing: a player with the wrong password is checked for mods (and may see the list) before the game turns them away");
			}
			if (list.Count == 0)
			{
				Info("hooks in place: ZNet.OnNewConnection, ZNet.RPC_PeerInfo (prefix, postfix), FejdStartup.ShowConnectError, ZRoutedRpc.RPC_RoutedRPC; deferring to the game: network version, IsAllowed, password (and its invite test)");
			}
			foreach (string item in list)
			{
				CorePlugin.Log.LogError((object)("MySix join check: " + item));
			}
		}

		internal static void StopPretending()
		{
			PretendPlain = false;
			PretendMissing.Clear();
			PretendVersions.Clear();
			PretendRefusedFeature.Clear();
			PretendGarbageReport = false;
		}

		private static string Pretending()
		{
			List<string> list = new List<string>();
			if (PretendPlain)
			{
				list.Add("no report at all (a game without mods)");
			}
			if (PretendMissing.Count > 0)
			{
				list.Add("missing " + string.Join(", ", PretendMissing.ToArray()));
			}
			if (PretendVersions.Count > 0)
			{
				list.Add("versions " + string.Join(", ", PretendVersions.Select((KeyValuePair<string, string> kv) => kv.Key + "=" + kv.Value).ToArray()));
			}
			if (PretendRefusedFeature.Count > 0)
			{
				list.Add("not running " + string.Join(", ", PretendRefusedFeature.ToArray()));
			}
			if (PretendGarbageReport)
			{
				list.Add("a report that cannot be read");
			}
			return string.Join("; ", list.ToArray());
		}

		private static void AfterNewConnection(ZNet __instance, ZNetPeer __0)
		{
			try
			{
				ZRpc val = __0?.m_rpc;
				if ((Object)(object)__instance == (Object)null || val == null)
				{
					return;
				}
				if (__instance.IsServer())
				{
					if (__instance.IsDedicated())
					{
						val.Register<ZPackage>("MySix_JoinReport", (Action<ZRpc, ZPackage>)OnReport);
					}
					return;
				}
				_refusal = null;
				LastRefusal = new List<Problem>();
				LastShown = "";
				LastLines = 0;
				LastOverflowing = false;
				Attempts++;
				val.Register<ZPackage>("MySix_JoinRefused", (Action<ZRpc, ZPackage>)OnRefused);
				string text = Pretending();
				if (text.Length > 0)
				{
					Info("pretending: " + text);
				}
				if (!PretendPlain)
				{
					int count;
					ZPackage val2 = BuildReport(out count);
					val.Invoke("MySix_JoinReport", new object[1] { val2 });
					Info($"told the server my mods ({count} mods)");
				}
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix join check: could not handle a new connection: " + ex));
			}
		}

		private static void OnRefused(ZRpc rpc, ZPackage pkg)
		{
			try
			{
				pkg.ReadInt();
				string text = Clean(pkg.ReadString());
				int num = pkg.ReadInt();
				if (num < 0 || num > 2000)
				{
					throw new InvalidDataException("a list of " + num);
				}
				List<Problem> list = new List<Problem>();
				for (int i = 0; i < num; i++)
				{
					list.Add(new Problem
					{
						Kind = (Kind)pkg.ReadInt(),
						Guid = Clean(pkg.ReadString(), 200),
						Name = Clean(pkg.ReadString()),
						Needed = Clean(pkg.ReadString()),
						Theirs = Clean(pkg.ReadString())
					});
				}
				_refusal = list;
				LastRefusal = list;
				CorePlugin.Log.LogWarning((object)("MySix join check: the server (MySix Core " + text + ") turned this game away " + $"for {list.Count} mod(s): " + string.Join("; ", list.Select((Problem p) => p.English()).ToArray())));
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogWarning((object)("MySix join check: the server turned this game away, but its list could not be read: " + ex.Message));
			}
		}

		private static void RecordGameText(FejdStartup __instance)
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				_gameText = (((Object)(object)__instance != (Object)null && (Object)(object)__instance.m_connectionFailedError != (Object)null) ? __instance.m_connectionFailedError.text : null);
			}
			catch (Exception)
			{
				_gameText = null;
			}
			try
			{
				RectTransform val = (RectTransform)(((Object)(object)__instance != (Object)null && (Object)(object)__instance.m_connectionFailedPanel != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
				if (!((Object)(object)val == (Object)null) && (_gameLayout == null || !((Object)(object)_gameLayout.Box == (Object)(object)val)))
				{
					RectTransform val2 = (((Object)(object)__instance.m_connectionFailedError != (Object)null) ? __instance.m_connectionFailedError.rectTransform : null);
					Transform obj = ((Transform)val).Find("ButtonOk");
					RectTransform val3 = (RectTransform)(object)((obj is RectTransform) ? obj : null);
					_gameLayout = new Layout
					{
						Box = val,
						BoxSize = val.sizeDelta,
						Text = val2,
						TextMin = (((Object)(object)val2 != (Object)null) ? val2.offsetMin : Vector2.zero),
						TextMax = (((Object)(object)val2 != (Object)null) ? val2.offsetMax : Vector2.zero),
						Ok = val3,
						OkMin = (((Object)(object)val3 != (Object)null) ? val3.offsetMin : Vector2.zero),
						OkMax = (((Object)(object)val3 != (Object)null) ? val3.offsetMax : Vector2.zero)
					};
				}
			}
			catch (Exception)
			{
				_gameLayout = null;
			}
		}

		private static void ShowRefusal(FejdStartup __instance)
		{
			List<Problem> refusal = _refusal;
			if (refusal == null || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			_refusal = null;
			try
			{
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				GameObject connectionFailedPanel = __instance.m_connectionFailedPanel;
				if ((Object)(object)connectionFailedError == (Object)null || (Object)(object)connectionFailedPanel == (Object)null)
				{
					return;
				}
				string text = connectionFailedError.text ?? "";
				string text2 = _gameText ?? "";
				string text3 = ((text2.Length > 0 && text.StartsWith(text2, StringComparison.Ordinal)) ? text.Substring(text2.Length) : ((text == text2) ? "" : text));
				text3 = text3.Trim('\r', '\n');
				string text4 = Texts.Get("mysix_join_title");
				List<string> list = new List<string>
				{
					connectionFailedError.richText ? ("<b>" + text4 + "</b>") : text4,
					Texts.Get("mysix_join_intro")
				};
				foreach (Problem item in refusal.Take(8))
				{
					list.Add(Line(item));
				}
				if (refusal.Count > 8)
				{
					list.Add(Texts.Get("mysix_join_more", (refusal.Count - 8).ToString(CultureInfo.InvariantCulture)));
				}
				string text5 = string.Join("\n", list.ToArray());
				connectionFailedPanel.SetActive(true);
				connectionFailedError.text = ((text3.Length > 0) ? (text5 + "\n" + text3) : text5);
				Fit(connectionFailedPanel, connectionFailedError);
				LastShown = connectionFailedError.text;
				LastLines = ((connectionFailedError.textInfo != null) ? connectionFailedError.textInfo.lineCount : 0);
				LastOverflowing = connectionFailedError.isTextOverflowing;
				Info(string.Format("showed the mod incompatibility message ({0} lines, overflowing: {1})", LastLines, LastOverflowing ? "true" : "false"));
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix join check: could not show why the server turned this game away: " + ex));
			}
		}

		private static string Line(Problem p)
		{
			bool flag = IsMySix(p.Guid);
			string text = Clean(p.Name);
			string text2 = Clean(p.Needed);
			string text3 = Clean(p.Theirs);
			string text4 = p.Kind switch
			{
				Kind.Missing => Texts.Get(flag ? "mysix_join_install" : "mysix_join_install_exact", text, text2), 
				Kind.Older => Texts.Get(flag ? "mysix_join_update" : "mysix_join_update_exact", text, text3, text2), 
				Kind.NotRunning => Texts.Get("mysix_join_notrunning", text, text3), 
				_ => Texts.Get("mysix_join_unreadable", text2), 
			};
			while (text4.Contains("  "))
			{
				text4 = text4.Replace("  ", " ");
			}
			return text4;
		}

		internal static string Clean(string s, int max = 80)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = s ?? "";
			foreach (char c in text)
			{
				if (!char.IsControl(c) && c != '<' && c != '>' && c != '$')
				{
					stringBuilder.Append(c);
				}
			}
			string text2 = stringBuilder.ToString().Trim();
			if (text2.Length <= max)
			{
				return text2;
			}
			return text2.Substring(0, max);
		}

		private static void Fit(GameObject panel, TMP_Text text)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			Transform val = panel.transform.Find("Image");
			RectTransform val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<RectTransform>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				CorePlugin.Log.LogWarning((object)"MySix join check: the connection-failed panel has no 'Image', so its size is left as it is");
				return;
			}
			Layout gameLayout = _gameLayout;
			if (gameLayout != null && (Object)(object)gameLayout.Box == (Object)(object)val2)
			{
				val2.sizeDelta = gameLayout.BoxSize;
				if ((Object)(object)gameLayout.Text != (Object)null)
				{
					gameLayout.Text.offsetMin = gameLayout.TextMin;
					gameLayout.Text.offsetMax = gameLayout.TextMax;
				}
				if ((Object)(object)gameLayout.Ok != (Object)null)
				{
					gameLayout.Ok.offsetMin = gameLayout.OkMin;
					gameLayout.Ok.offsetMax = gameLayout.OkMax;
				}
			}
			Vector2 sizeDelta = val2.sizeDelta;
			sizeDelta.x = 675f;
			val2.sizeDelta = sizeDelta;
			if (text.enableAutoSizing)
			{
				text.enableAutoSizing = false;
				text.fontSize = text.fontSizeMax;
			}
			RectTransform rectTransform = text.rectTransform;
			string text2 = text.text;
			Rect rect = rectTransform.rect;
			float y = text.GetPreferredValues(text2, ((Rect)(ref rect)).width, 0f).y;
			rect = rectTransform.rect;
			float num = y - ((Rect)(ref rect)).height;
			Canvas componentInParent = ((Component)val2).GetComponentInParent<Canvas>();
			RectTransform val3 = (RectTransform)(((Object)(object)componentInParent != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			float num2;
			if (!((Object)(object)val3 != (Object)null))
			{
				num2 = Screen.height;
			}
			else
			{
				rect = val3.rect;
				num2 = ((Rect)(ref rect)).height;
			}
			float num3 = num2 * 0.8f;
			rect = val2.rect;
			float num4 = num3 - ((Rect)(ref rect)).height;
			if (num > num4)
			{
				num = Mathf.Max(0f, num4);
				text.fontSizeMax = text.fontSize;
				text.fontSizeMin = Mathf.Min(12f, text.fontSize);
				text.enableAutoSizing = true;
			}
			if (num > 0f)
			{
				rectTransform.offsetMax += new Vector2(0f, num * (1f - rectTransform.anchorMax.y));
				rectTransform.offsetMin -= new Vector2(0f, num * rectTransform.anchorMin.y);
				Transform val4 = ((Transform)val2).Find("ButtonOk");
				RectTransform val5 = (((Object)(object)val4 != (Object)null) ? ((Component)val4).GetComponent<RectTransform>() : null);
				if ((Object)(object)val5 != (Object)null)
				{
					val5.offsetMax -= new Vector2(0f, num * val5.anchorMax.y);
					val5.offsetMin -= new Vector2(0f, num * val5.anchorMin.y);
				}
				sizeDelta.y += num;
				val2.sizeDelta = sizeDelta;
			}
			text.ForceMeshUpdate(false, false);
		}
	}
	internal sealed class Restart
	{
		private static readonly int[] WarnAt = new int[6] { 600, 300, 120, 60, 30, 10 };

		private readonly string _dir = Path.Combine(Paths.ConfigPath, "MySix.Core");

		private float _nextLook;

		private float _endsAt = -1f;

		private int _warned = int.MaxValue;

		private string _message = "";

		public bool Pending => _endsAt >= 0f;

		public void Tick(float now)
		{
			if (now >= _nextLook)
			{
				_nextLook = now + 2f;
				Look(now);
			}
			if (!Pending)
			{
				return;
			}
			int num = Mathf.CeilToInt(_endsAt - now);
			int[] warnAt = WarnAt;
			foreach (int num2 in warnAt)
			{
				if (num <= num2 && _warned > num2 && num > num2 - 5)
				{
					_warned = num2;
					Say("The server restarts in " + Words(num2) + ". Find somewhere safe and log out.");
				}
			}
			if (num <= 0)
			{
				_endsAt = -1f;
				Say("The server is restarting now.");
				CorePlugin.Log.LogWarning((object)"Restart: the time is up; saving the world and quitting for the server's host to start it again");
				Application.Quit();
			}
		}

		private void Look(float now)
		{
			string path = Path.Combine(_dir, "restart.txt");
			string path2 = Path.Combine(_dir, "restart-cancel.txt");
			try
			{
				if (File.Exists(path2))
				{
					File.Delete(path2);
					if (Pending)
					{
						_endsAt = -1f;
						Say("The server restart is called off.");
						CorePlugin.Log.LogInfo((object)"Restart: called off");
					}
				}
				if (File.Exists(path))
				{
					string[] array = File.ReadAllLines(path);
					File.Delete(path);
					float num = 5f;
					if (array.Length != 0 && float.TryParse(array[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
					{
						num = Mathf.Clamp(result, 0.25f, 120f);
					}
					_message = ((array.Length > 1) ? string.Join(" ", array, 1, array.Length - 1).Trim() : "");
					_endsAt = now + num * 60f;
					Say("The server restarts in " + Words(_warned = Mathf.CeilToInt(num * 60f)) + ". Find somewhere safe and log out." + ((_message.Length > 0) ? (" " + _message) : ""));
					CorePlugin.Log.LogWarning((object)string.Format("Restart: asked for, in {0} minute(s){1}", num, (_message.Length > 0) ? (": " + _message) : ""));
				}
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("Restart: could not read the request: " + ex.Message));
			}
		}

		private static string Words(int seconds)
		{
			if (seconds >= 120)
			{
				return $"{seconds / 60} minutes";
			}
			if (seconds >= 60)
			{
				return "1 minute";
			}
			return $"{seconds} seconds";
		}

		private static void Say(string text)
		{
			CorePlugin.Log.LogInfo((object)("Restart: told everyone: " + text));
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.InvokeRoutedRPC(0L, "ShowMessage", new object[2] { 2, text });
			}
		}
	}
	public enum Scope
	{
		Server,
		Player
	}
	public abstract class SettingBase
	{
		public string Feature { get; protected set; }

		public string Key { get; protected set; }

		public string Description { get; protected set; }

		public Scope Scope { get; protected set; }

		public string FullName => Feature + "." + Key;

		public string ShortName => Feature.Replace("MySix", "").Replace(" ", "") + "." + Key;

		public bool IsRemote { get; internal set; }

		public abstract string ValueText { get; }

		public abstract string LocalText { get; }

		public abstract string DefaultText { get; }

		public abstract string TypeHint { get; }

		public abstract bool TrySetFromText(string text, out string error);

		internal abstract void ApplyRemoteText(string text);

		internal abstract void ClearRemote();
	}
	public sealed class Setting<T> : SettingBase
	{
		private readonly ConfigEntry<T> _entry;

		private T _remote;

		public T Value
		{
			get
			{
				if (!base.IsRemote)
				{
					return _entry.Value;
				}
				return _remote;
			}
		}

		public override string ValueText => Format(Value);

		public override string LocalText => Format(_entry.Value);

		public override string DefaultText => Format((T)((ConfigEntryBase)_entry).DefaultValue);

		public override string TypeHint => Describe(typeof(T));

		public event Action<Setting<T>> Changed;

		internal Setting(string feature, string key, ConfigEntry<T> entry, Scope scope, string description)
		{
			base.Feature = feature;
			base.Key = key;
			object obj = description;
			if (obj == null)
			{
				ConfigDescription description2 = ((ConfigEntryBase)entry).Description;
				obj = ((description2 != null) ? description2.Description : null) ?? "";
			}
			base.Description = (string)obj;
			base.Scope = scope;
			_entry = entry;
			_entry.SettingChanged += delegate
			{
				if (!base.IsRemote)
				{
					Raise();
				}
				WorldSettings.LocalChanged(this);
				WorldPlayerSettings.LocalChanged(this);
			};
		}

		public override bool TrySetFromText(string text, out string error)
		{
			if (!TryParse(text, out var value, out error))
			{
				return false;
			}
			base.IsRemote = false;
			_entry.Value = value;
			Raise();
			error = null;
			return true;
		}

		public bool SetForWorld(string text)
		{
			if (base.Scope != Scope.Server || !WorldSettings.Active || !TryParse(text, out var value, out var _))
			{
				return false;
			}
			bool num = !base.IsRemote || !EqualityComparer<T>.Default.Equals(_remote, value);
			_remote = value;
			base.IsRemote = true;
			if (num)
			{
				Raise();
			}
			ConfigSync.BroadcastValues();
			return true;
		}

		internal override void ApplyRemoteText(string text)
		{
			if (!TryParse(text, out var value, out var error))
			{
				CorePlugin.Log.LogWarning((object)("Ignoring bad value for " + base.FullName + " from server: " + error));
				return;
			}
			bool num = !base.IsRemote || !EqualityComparer<T>.Default.Equals(_remote, value);
			_remote = value;
			base.IsRemote = true;
			if (num)
			{
				Raise();
			}
		}

		internal override void ClearRemote()
		{
			if (base.IsRemote)
			{
				base.IsRemote = false;
				Raise();
			}
		}

		private void Raise()
		{
			try
			{
				this.Changed?.Invoke(this);
			}
			catch (Exception arg)
			{
				CorePlugin.Log.LogError((object)$"{base.FullName} change handler failed: {arg}");
			}
		}

		private static string Format(T v)
		{
			if (!(v is float num))
			{
				if (!(v is bool))
				{
					return Convert.ToString(v, CultureInfo.InvariantCulture);
				}
				object obj = v;
				if (!(bool)((obj is bool) ? obj : null))
				{
					return "false";
				}
				return "true";
			}
			return num.ToString("0.###", CultureInfo.InvariantCulture);
		}

		private static bool TryParse(string text, out T value, out string error)
		{
			value = default(T);
			error = null;
			text = (text ?? "").Trim();
			Type typeFromHandle = typeof(T);
			try
			{
				if (typeFromHandle == typeof(bool))
				{
					if (text.Equals("true", StringComparison.OrdinalIgnoreCase) || text == "1")
					{
						value = (T)(object)true;
						return true;
					}
					if (text.Equals("false", StringComparison.OrdinalIgnoreCase) || text == "0")
					{
						value = (T)(object)false;
						return true;
					}
					error = "expected true or false";
					return false;
				}
				if (typeFromHandle == typeof(int))
				{
					if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
					{
						error = "expected a whole number";
						return false;
					}
					value = (T)(object)result;
					return true;
				}
				if (typeFromHandle == typeof(float))
				{
					if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
					{
						error = "expected a number";
						return false;
					}
					value = (T)(object)result2;
					return true;
				}
				if (typeFromHandle.IsEnum)
				{
					string[] names = Enum.GetNames(typeFromHandle);
					foreach (string text2 in names)
					{
						if (text2.Equals(text, StringComparison.OrdinalIgnoreCase))
						{
							value = (T)Enum.Parse(typeFromHandle, text2);
							return true;
						}
					}
					error = "expected one of: " + string.Join(", ", Enum.GetNames(typeFromHandle));
					return false;
				}
				if (typeFromHandle == typeof(string))
				{
					value = (T)(object)text;
					return true;
				}
				error = "unsupported setting type " + typeFromHandle.Name;
				return false;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				return false;
			}
		}

		private static string Describe(Type t)
		{
			if (!(t == typeof(bool)))
			{
				if (!(t == typeof(int)))
				{
					if (!(t == typeof(float)))
					{
						if (!t.IsEnum)
						{
							return "text";
						}
						return string.Join("|", Enum.GetNames(t));
					}
					return "number";
				}
				return "whole number";
			}
			return "true/false";
		}
	}
	public static class Settings
	{
		private static readonly Dictionary<string, SettingBase> All = new Dictionary<string, SettingBase>(StringComparer.OrdinalIgnoreCase);

		public static IEnumerable<SettingBase> Known => All.Values.OrderBy<SettingBase, string>((SettingBase s) => s.FullName, StringComparer.OrdinalIgnoreCase);

		public static IEnumerable<SettingBase> ServerOwned => Known.Where((SettingBase s) => s.Scope == Scope.Server);

		public static IEnumerable<string> Names => Known.Select((SettingBase s) => s.FullName);

		public static Setting<T> Register<T>(string feature, ConfigEntry<T> entry, Scope scope, string description = null)
		{
			if (entry == null)
			{
				throw new ArgumentNullException("entry");
			}
			Setting<T> setting = new Setting<T>(feature, ((ConfigEntryBase)entry).Definition.Key, entry, scope, description);
			if (All.ContainsKey(setting.FullName))
			{
				CorePlugin.Log.LogWarning((object)("Setting registered twice: " + setting.FullName));
			}
			All[setting.FullName] = setting;
			return setting;
		}

		public static SettingBase Find(string fullName)
		{
			if (All.TryGetValue(fullName ?? "", out var value))
			{
				return value;
			}
			List<SettingBase> list = All.Values.Where((SettingBase x) => string.Equals(x.ShortName, fullName, StringComparison.OrdinalIgnoreCase)).ToList();
			if (list.Count == 1)
			{
				return list[0];
			}
			List<SettingBase> list2 = All.Values.Where((SettingBase x) => string.Equals(x.Key, fullName, StringComparison.OrdinalIgnoreCase)).ToList();
			if (list2.Count != 1)
			{
				return null;
			}
			return list2[0];
		}

		internal static void ClearRemoteValues()
		{
			foreach (SettingBase value in All.Values)
			{
				value.ClearRemote();
			}
		}
	}
	public static class Texts
	{
		private const string Fallback = "English";

		private static readonly Dictionary<string, Dictionary<string, string>> Words = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);

		private static readonly MethodInfo AddWord = typeof(Localization).GetMethod("AddWord", BindingFlags.Instance | BindingFlags.NonPublic);

		private static Harmony _harmony;

		private static Localization Current => (Localization)AccessTools.Field(typeof(Localization), "m_instance").GetValue(null);

		public static void Load(Assembly assembly, string resourceSuffix)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			string text = null;
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			foreach (string text2 in manifestResourceNames)
			{
				if (text2.EndsWith(resourceSuffix, StringComparison.OrdinalIgnoreCase))
				{
					text = text2;
				}
			}
			if (text == null)
			{
				ManualLogSource log = CorePlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Texts: " + assembly.GetName().Name + " has no " + resourceSuffix));
				}
				return;
			}
			using (Stream stream = assembly.GetManifestResourceStream(text))
			{
				using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
				Parse(streamReader.ReadToEnd(), text);
			}
			if (_harmony == null)
			{
				_harmony = new Harmony("com.mysix.core.texts");
				_harmony.Patch((MethodBase)AccessTools.Method(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Texts), "AfterSetupLanguage", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Localization current = Current;
			if (current != null)
			{
				Apply(current, current.GetSelectedLanguage());
			}
		}

		private static void AfterSetupLanguage(Localization __instance, string __0)
		{
			Apply(__instance, __0);
		}

		private static void Parse(string text, string source)
		{
			Dictionary<string, string> value = null;
			int num = 0;
			string[] array = text.Split(new char[1] { '\n' });
			foreach (string obj in array)
			{
				num++;
				string text2 = obj.Trim();
				if (text2.Length == 0 || text2[0] == '#')
				{
					continue;
				}
				if (text2[0] == '[' && text2[text2.Length - 1] == ']')
				{
					string key = text2.Substring(1, text2.Length - 2).Trim();
					if (!Words.TryGetValue(key, out value))
					{
						value = (Words[key] = new Dictionary<string, string>(StringComparer.Ordinal));
					}
					continue;
				}
				int num2 = text2.IndexOf('=');
				if (value == null || num2 <= 0)
				{
					ManualLogSource log = CorePlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)$"Texts: {source} line {num} is not 'key = text' under a [Language]");
					}
				}
				else
				{
					value[text2.Substring(0, num2).Trim()] = text2.Substring(num2 + 1).Trim();
				}
			}
		}

		private static void Apply(Localization localization, string language)
		{
			if (localization != null && !(AddWord == null))
			{
				Put(localization, "English");
				if (!string.Equals(language, "English", StringComparison.OrdinalIgnoreCase))
				{
					Put(localization, language);
				}
			}
		}

		private static void Put(Localization localization, string language)
		{
			if (!Words.TryGetValue(language, out var value))
			{
				return;
			}
			foreach (KeyValuePair<string, string> item in value)
			{
				AddWord.Invoke(localization, new object[2] { item.Key, item.Value });
			}
		}

		public static string Get(string key, params string[] words)
		{
			return Localization.instance.Localize("$" + key, words);
		}

		public static IEnumerable<string> Keys(string language)
		{
			if (!Words.TryGetValue(language, out var value))
			{
				return Array.Empty<string>();
			}
			return value.Keys;
		}
	}
	internal static class WorldPlayerSettings
	{
		private delegate void FindObjectsFn(ZDOMan man, Vector2s sector, List<ZDO> objects, HashSet<SectorIndex> visited);

		private const string RpcHello = "MySix_PlayerSettingsHello";

		private const string RpcValues = "MySix_PlayerSettingsValues";

		private const string RpcSet = "MySix_PlayerSettingsSet";

		private static readonly int Prefab = StringExtensionMethods.GetStableHashCode("MySix_PlayerSettingsRecord");

		private static readonly int Data = StringExtensionMethods.GetStableHashCode("mysix_player_settings");

		private static readonly Vector3 Place = new Vector3(10240f, 0f, -10240f);

		private static readonly FindObjectsFn FindObjects = AccessTools.MethodDelegate<FindObjectsFn>(AccessTools.Method(typeof(ZDOMan), "FindObjects", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Dictionary<long, Dictionary<string, string>> Kept = new Dictionary<long, Dictionary<string, string>>();

		private static readonly Dictionary<string, Dictionary<string, string>> Seen = new Dictionary<string, Dictionary<string, string>>();

		private static bool _registered;

		private static bool _hosting;

		private static bool _helloSent;

		private static bool _applying;

		internal static int Answered;

		internal static ZDO Holder => Find();

		private static ZDO Find()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null)
			{
				return null;
			}
			List<ZDO> list = new List<ZDO>();
			FindObjects(ZDOMan.instance, ZoneSystem.GetZone(Place), list, new HashSet<SectorIndex>());
			return ((IEnumerable<ZDO>)list).FirstOrDefault((Func<ZDO, bool>)((ZDO z) => z != null && z.IsValid() && z.GetPrefab() == Prefab));
		}

		public static void Load()
		{
			Kept.Clear();
			Seen.Clear();
			_hosting = (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZDOMan.instance != null;
			if (!_hosting)
			{
				return;
			}
			ZDO obj = Find();
			string[] array = (((obj != null) ? obj.GetString(Data, "") : null) ?? "").Split(new char[1] { '\n' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { '\t' });
				if (array2.Length == 3 && long.TryParse(array2[0], out var result))
				{
					Choices(result)[array2[1]] = array2[2];
				}
				else if (array2.Length == 5 && array2[0] == "seen")
				{
					SeenOn(array2[1], array2[2])[array2[3]] = array2[4];
				}
			}
			if (Kept.Count > 0)
			{
				CorePlugin.Log.LogInfo((object)$"MySix: this world keeps its players' own settings ({Kept.Count} players)");
			}
		}

		public static void Save()
		{
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			if (!_hosting || ZDOMan.instance == null)
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<long, Dictionary<string, string>> item in Kept)
			{
				foreach (KeyValuePair<string, string> item2 in item.Value)
				{
					stringBuilder.Append(item.Key).Append('\t').Append(item2.Key)
						.Append('\t')
						.Append(Clean(item2.Value))
						.Append('\n');
				}
			}
			foreach (KeyValuePair<string, Dictionary<string, string>> item3 in Seen)
			{
				foreach (KeyValuePair<string, string> item4 in item3.Value)
				{
					stringBuilder.Append("seen\t").Append(item3.Key).Append('\t')
						.Append(item4.Key)
						.Append('\t')
						.Append(Clean(item4.Value))
						.Append('\n');
				}
			}
			if (stringBuilder.Length != 0)
			{
				ZDO val = Find();
				if (val == null)
				{
					val = ZDOMan.instance.CreateNewZDO(Place, Prefab);
					val.SetPrefab(Prefab);
					val.Persistent = true;
					val.SetOwner(ZDOMan.GetSessionID());
				}
				val.Set(Data, stringBuilder.ToString());
			}
		}

		public static void Unload()
		{
			Kept.Clear();
			Seen.Clear();
			_hosting = false;
			_helloSent = false;
		}

		private static Dictionary<string, string> Choices(long playerId)
		{
			if (!Kept.TryGetValue(playerId, out var value))
			{
				value = (Kept[playerId] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
			}
			return value;
		}

		private static Dictionary<string, string> SeenOn(string player, string computer)
		{
			string key = player + "\t" + computer;
			if (!Seen.TryGetValue(key, out var value))
			{
				value = (Seen[key] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
			}
			return value;
		}

		private static string Clean(string s)
		{
			return (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' ');
		}

		private static void OnHello(long sender, ZPackage pkg)
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Expected O, but got Unknown
			if (!_hosting)
			{
				return;
			}
			long num = pkg.ReadLong();
			string computer = pkg.ReadString();
			Dictionary<string, string> dictionary = ReadValues(pkg);
			Dictionary<string, string> dictionary2 = SeenOn(num.ToString(), computer);
			if (Kept.TryGetValue(num, out var value) && value.Count > 0)
			{
				foreach (KeyValuePair<string, string> item in dictionary)
				{
					if (!value.ContainsKey(item.Key) || (dictionary2.TryGetValue(item.Key, out var value2) && value2 != item.Value))
					{
						value[item.Key] = item.Value;
					}
				}
				foreach (KeyValuePair<string, string> item2 in value)
				{
					dictionary2[item2.Key] = item2.Value;
				}
				ZPackage pkg2 = new ZPackage();
				WriteValues(pkg2, value);
				Send(sender, "MySix_PlayerSettingsValues", pkg2);
				return;
			}
			Dictionary<string, string> dictionary3 = Choices(num);
			foreach (KeyValuePair<string, string> item3 in dictionary)
			{
				string key = item3.Key;
				string value3 = (dictionary2[item3.Key] = item3.Value);
				dictionary3[key] = value3;
			}
		}

		private static void OnSet(long sender, ZPackage pkg)
		{
			if (_hosting)
			{
				long playerId = pkg.ReadLong();
				string computer = pkg.ReadString();
				string key = pkg.ReadString();
				string value = pkg.ReadString();
				Choices(playerId)[key] = value;
				SeenOn(playerId.ToString(), computer)[key] = value;
			}
		}

		public static void Tick()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			Register();
			if (!_helloSent && _registered && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && (ZNet.instance.IsServer() || ZNet.instance.GetServerPeer() != null))
			{
				_helloSent = true;
				ZPackage val = new ZPackage();
				val.Write(Player.m_localPlayer.GetPlayerID());
				val.Write(Computer.Id);
				WriteValues(val, Settings.Known.Where((SettingBase s) => s.Scope == Scope.Player).ToDictionary((SettingBase s) => s.FullName, (SettingBase s) => s.LocalText));
				Send(Host(), "MySix_PlayerSettingsHello", val);
			}
		}

		private static void OnValues(long sender, ZPackage pkg)
		{
			Dictionary<string, string> dictionary = ReadValues(pkg);
			Answered++;
			_applying = true;
			try
			{
				int num = 0;
				foreach (KeyValuePair<string, string> item in dictionary)
				{
					SettingBase settingBase = Settings.Find(item.Key);
					if (settingBase != null && settingBase.Scope == Scope.Player && !(settingBase.LocalText == item.Value) && settingBase.TrySetFromText(item.Value, out var _))
					{
						num++;
					}
				}
				CorePlugin.Log.LogInfo((object)$"MySix: your own settings kept in this world are in use ({num} differed from this computer's)");
			}
			finally
			{
				_applying = false;
			}
		}

		public static void LocalChanged(SettingBase s)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (!_applying && _helloSent && s.Scope == Scope.Player && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				ZPackage val = new ZPackage();
				val.Write(Player.m_localPlayer.GetPlayerID());
				val.Write(Computer.Id);
				val.Write(s.FullName);
				val.Write(s.LocalText);
				Send(Host(), "MySix_PlayerSettingsSet", val);
			}
		}

		private static void Register()
		{
			if (!_registered && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.Register<ZPackage>("MySix_PlayerSettingsHello", (Action<long, ZPackage>)OnHello);
				ZRoutedRpc.instance.Register<ZPackage>("MySix_PlayerSettingsValues", (Action<long, ZPackage>)OnValues);
				ZRoutedRpc.instance.Register<ZPackage>("MySix_PlayerSettingsSet", (Action<long, ZPackage>)OnSet);
				_registered = true;
			}
		}

		public static void Reset()
		{
			_registered = false;
			_helloSent = false;
		}

		private static long Host()
		{
			if (!ZNet.instance.IsServer())
			{
				return ZNet.instance.GetServerPeer().m_uid;
			}
			return ZDOMan.GetSessionID();
		}

		private static void Send(long to, string rpc, ZPackage pkg)
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.InvokeRoutedRPC(to, rpc, new object[1] { pkg });
			}
		}

		private static void WriteValues(ZPackage pkg, Dictionary<string, string> values)
		{
			pkg.Write(values.Count);
			foreach (KeyValuePair<string, string> value in values)
			{
				pkg.Write(value.Key);
				pkg.Write(value.Value ?? "");
			}
		}

		private static Dictionary<string, string> ReadValues(ZPackage pkg)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			int num = pkg.ReadInt();
			for (int i = 0; i < num; i++)
			{
				dictionary[pkg.ReadString()] = pkg.ReadString();
			}
			return dictionary;
		}

		internal static IReadOnlyDictionary<string, string> KeptFor(long playerId)
		{
			if (!Kept.TryGetValue(playerId, out var value))
			{
				return new Dictionary<string, string>();
			}
			return value;
		}

		internal static void Rejoin()
		{
			_helloSent = false;
		}

		internal static void Quietly(Action change)
		{
			_applying = true;
			try
			{
				change();
			}
			finally
			{
				_applying = false;
			}
		}
	}
	public interface IWorldScanConsumer
	{
		void BeginPass();

		void Visit(ZDO zdo, int prefabHash);

		void EndPass(float realtimeNow);
	}
	public class WorldScanner
	{
		private static readonly FieldRef<ZDOMan, List<ZDO>[]> ObjectsBySector = AccessTools.FieldRefAccess<ZDOMan, List<ZDO>[]>("m_objectsBySector");

		private static readonly FieldRef<ZDOMan, Dictionary<ZDOID, ZDO>> ObjectsById = AccessTools.FieldRefAccess<ZDOMan, Dictionary<ZDOID, ZDO>>("m_objectsByID");

		private readonly List<IWorldScanConsumer> _consumers = new List<IWorldScanConsumer>();

		private readonly Stopwatch _slice = new Stopwatch();

		private int _sector = -1;

		private float _passStart;

		private double _passWorkMs;

		private double _passMaxSliceMs;

		private int _passFrames;

		private int _passObjects;

		public int CompletedPasses { get; private set; }

		public bool WorldLoaded { get; private set; }

		public bool HasConsumers => _consumers.Count > 0;

		public void Add(IWorldScanConsumer consumer)
		{
			if (consumer != null && !_consumers.Contains(consumer))
			{
				_consumers.Add(consumer);
			}
		}

		public void FinishPassNow()
		{
			_passStart = -1.7014117E+38f;
		}

		public void Tick(float now, float cycleSeconds, int maxObjectsPerFrame)
		{
			if (_consumers.Count == 0 || ZDOMan.instance == null)
			{
				return;
			}
			List<ZDO>[] array = ObjectsBySector.Invoke(ZDOMan.instance);
			if (array == null)
			{
				return;
			}
			if (!WorldLoaded)
			{
				if (ObjectsById.Invoke(ZDOMan.instance).Count == 0)
				{
					return;
				}
				WorldLoaded = true;
			}
			if (_sector < 0)
			{
				_sector = 0;
				_passStart = now;
				_passWorkMs = (_passMaxSliceMs = 0.0);
				_passFrames = (_passObjects = 0);
				foreach (IWorldScanConsumer consumer in _consumers)
				{
					consumer.BeginPass();
				}
			}
			float num = Math.Max(1f, cycleSeconds);
			double num2 = (now - _passStart) / num;
			int num3 = ((num2 >= 1.0) ? array.Length : ((int)(num2 * (double)array.Length)));
			if (_sector >= num3 && _sector < array.Length)
			{
				return;
			}
			_slice.Restart();
			int num4 = Math.Max(100, maxObjectsPerFrame);
			int num5 = 0;
			while (_sector < array.Length && _sector < num3 && num5 < num4)
			{
				List<ZDO> list = array[_sector++];
				if (list == null)
				{
					continue;
				}
				for (int i = 0; i < list.Count; i++)
				{
					ZDO val = list[i];
					if (val != null && val.IsValid())
					{
						int prefab = val.GetPrefab();
						for (int j = 0; j < _consumers.Count; j++)
						{
							_consumers[j].Visit(val, prefab);
						}
					}
				}
				num5 += list.Count;
			}
			_passObjects += num5;
			bool flag = _sector >= array.Length;
			if (flag)
			{
				_sector = -1;
				foreach (IWorldScanConsumer consumer2 in _consumers)
				{
					consumer2.EndPass(now);
				}
			}
			double totalMilliseconds = _slice.Elapsed.TotalMilliseconds;
			_slice.Reset();
			_passWorkMs += totalMilliseconds;
			_passFrames++;
			if (totalMilliseconds > _passMaxSliceMs)
			{
				_passMaxSliceMs = totalMilliseconds;
			}
			if (flag)
			{
				if (CompletedPasses == 0 || _passMaxSliceMs > 8.0)
				{
					CorePlugin.Log.Log((LogLevel)((_passMaxSliceMs > 8.0) ? 4 : 16), (object)($"World pass over {_passObjects} objects took {now - _passStart:0}s: {_passFrames} frames, " + $"{_passWorkMs:0.0} ms total work, slowest frame {_passMaxSliceMs:0.00} ms"));
				}
				CompletedPasses++;
			}
		}
	}
	internal static class WorldSettings
	{
		private delegate void FindObjectsFn(ZDOMan man, Vector2s sector, List<ZDO> objects, HashSet<SectorIndex> visited);

		private static readonly int Prefab = StringExtensionMethods.GetStableHashCode("MySix_SettingsRecord");

		private static readonly int Data = StringExtensionMethods.GetStableHashCode("mysix_settings");

		private static readonly Vector3 Place = new Vector3(-10240f, 0f, 10240f);

		private static readonly FindObjectsFn FindObjects = AccessTools.MethodDelegate<FindObjectsFn>(AccessTools.Method(typeof(ZDOMan), "FindObjects", (Type[])null, (Type[])null), (object)null, true);

		internal static readonly HashSet<string> HostOnly = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly List<string> OtherComputers = new List<string>();

		public static bool Active { get; private set; }

		private static IEnumerable<SettingBase> Kept => Settings.ServerOwned.Where((SettingBase s) => !HostOnly.Contains(s.FullName));

		private static bool Hosting
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					return ZDOMan.instance != null;
				}
				return false;
			}
		}

		internal static ZDO Holder => Find();

		private static ZDO Find()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null)
			{
				return null;
			}
			List<ZDO> list = new List<ZDO>();
			FindObjects(ZDOMan.instance, ZoneSystem.GetZone(Place), list, new HashSet<SectorIndex>());
			return ((IEnumerable<ZDO>)list).FirstOrDefault((Func<ZDO, bool>)((ZDO z) => z != null && z.IsValid() && z.GetPrefab() == Prefab));
		}

		public static void Load()
		{
			OtherComputers.Clear();
			if (!Hosting)
			{
				return;
			}
			Active = true;
			ZDO obj = Find();
			string text = ((obj != null) ? obj.GetString(Data, "") : null) ?? "";
			if (text.Length == 0)
			{
				CorePlugin.Log.LogInfo((object)"MySix: this world keeps no settings yet: it takes this computer's, and keeps them from its next save");
				{
					foreach (SettingBase item in Kept)
					{
						item.ApplyRemoteText(item.LocalText);
					}
					return;
				}
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			string text2 = "@" + Computer.Id + "\t";
			string[] array = text.Split(new char[1] { '\n' });
			foreach (string text3 in array)
			{
				if (text3.StartsWith("@"))
				{
					if (text3.StartsWith(text2))
					{
						Split(text3.Substring(text2.Length), dictionary2);
					}
					else
					{
						OtherComputers.Add(text3);
					}
				}
				else
				{
					Split(text3, dictionary);
				}
			}
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			foreach (SettingBase item2 in Kept)
			{
				string value;
				string text4 = (dictionary.TryGetValue(item2.FullName, out value) ? value : item2.LocalText);
				if (text4 != item2.LocalText && dictionary2.TryGetValue(item2.FullName, out var value2) && value2 != item2.LocalText)
				{
					list2.Add(item2.ShortName + " " + item2.LocalText + " (was " + text4 + ")");
					text4 = item2.LocalText;
				}
				else if (text4 != item2.LocalText)
				{
					list.Add(item2.ShortName + " " + text4 + " (this computer: " + item2.LocalText + ")");
				}
				item2.ApplyRemoteText(text4);
			}
			CorePlugin.Log.LogInfo((object)($"MySix: this world's own settings are in force ({dictionary.Count} kept in it)" + ((list.Count > 0) ? ("; different from this computer's: " + string.Join(", ", list)) : "") + ((list2.Count > 0) ? ("; changed in this computer's settings file since, so changed for the world: " + string.Join(", ", list2)) : "")));
		}

		private static void Split(string line, Dictionary<string, string> into)
		{
			int num = line.IndexOf('=');
			if (num > 0)
			{
				into[line.Substring(0, num).Trim()] = line.Substring(num + 1).Trim();
			}
		}

		public static void Unload()
		{
			Active = false;
		}

		public static void LocalChanged(SettingBase s)
		{
			if (Active && Hosting && s.Scope == Scope.Server)
			{
				if (!HostOnly.Contains(s.FullName))
				{
					s.ApplyRemoteText(s.LocalText);
				}
				ConfigSync.BroadcastValues();
			}
		}

		public static void Save()
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (!Active || !Hosting)
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (SettingBase item in Kept)
			{
				stringBuilder.Append(item.FullName).Append('=').Append(item.ValueText)
					.Append('\n');
			}
			foreach (SettingBase item2 in Kept)
			{
				stringBuilder.Append('@').Append(Computer.Id).Append('\t')
					.Append(item2.FullName)
					.Append('=')
					.Append(item2.LocalText)
					.Append('\n');
			}
			foreach (string otherComputer in OtherComputers)
			{
				stringBuilder.Append(otherComputer).Append('\n');
			}
			ZDO val = Find();
			if (val == null)
			{
				val = ZDOMan.instance.CreateNewZDO(Place, Prefab);
				val.SetPrefab(Prefab);
				val.Persistent = true;
				val.SetOwner(ZDOMan.GetSessionID());
			}
			val.Set(Data, stringBuilder.ToString());
		}
	}
	internal static class Computer
	{
		private static string _id;

		internal static string Pretend;

		public static string Id => Pretend ?? _id ?? (_id = ((uint)StringExtensionMethods.GetStableHashCode(SystemInfo.deviceUniqueIdentifier + "|" + Environment.MachineName)).ToString("x8"));
	}
	[HarmonyPatch(typeof(ZNet), "ServerLoadWorld")]
	internal static class LoadWorldSettings
	{
		private static void Postfix()
		{
			WorldSettings.Load();
			WorldPlayerSettings.Load();
			try
			{
				JoinCheck.ServerStarted();
			}
			catch (Exception ex)
			{
				CorePlugin.Log.LogError((object)("MySix join check: could not start: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "SaveWorld")]
	internal static class SaveWorldSettings
	{
		private static void Prefix()
		{
			WorldSettings.Save();
			WorldPlayerSettings.Save();
		}
	}
}