Decompiled source of BountyBoard v1.0.0

plugins/YesuBuildKit.BountyBoard.dll

Decompiled 2 hours ago
using System;
using System.Collections;
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.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using YesuBuildKit.BountyBoard.Patches;
using YesuBuildKit.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("YesuBuildKit.BountyBoard")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+2f671b203e8c5d7fd1f653467436e8da043a21fe")]
[assembly: AssemblyProduct("YesuBuildKit.BountyBoard")]
[assembly: AssemblyTitle("YesuBuildKit.BountyBoard")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace YesuBuildKit.Core
{
	internal static class ConfigApiContract
	{
		public const int Version = 1;

		public const string DataKeyPrefix = "YesuBuildKit.ConfigApi/";

		public static string DataKey(string modGuid)
		{
			return "YesuBuildKit.ConfigApi/" + modGuid;
		}
	}
	internal static class ConfigApiNames
	{
		public const string ApiVersion = "ApiVersion";

		public const string Guid = "Guid";

		public const string Name = "Name";

		public const string ModVersion = "ModVersion";

		public const string Active = "Active";

		public const string Keys = "Keys";

		public const string Describe = "Describe";

		public const string Options = "Options";

		public const string Values = "Values";

		public const string Connected = "Connected";

		public const string Role = "Role";

		public const string World = "World";

		public const string CanChangeServer = "CanChangeServer";

		public const string Request = "Request";

		public const string LastResult = "LastResult";

		public const string OnResult = "OnResult";

		public const string OnChanged = "OnChanged";

		public const string ChangeCounter = "ChangeCounter";
	}
	internal static class DescribeIndex
	{
		public const int TypeName = 0;

		public const int Default = 1;

		public const int Description = 2;

		public const int Acceptable = 3;

		public const int Min = 4;

		public const int Max = 5;

		public const int Length = 6;
	}
	internal static class ValuesIndex
	{
		public const int Local = 0;

		public const int ServerDefault = 1;

		public const int WorldOverride = 2;

		public const int Effective = 3;

		public const int Source = 4;

		public const int Length = 5;
	}
	internal static class ResultIndex
	{
		public const int Counter = 0;

		public const int Key = 1;

		public const int Scope = 2;

		public const int Status = 3;

		public const int Message = 4;

		public const int Length = 5;
	}
	internal static class RoleNames
	{
		public const string None = "none";

		public const string Solo = "solo";

		public const string Host = "host";

		public const string Dedicated = "dedicated";

		public const string Client = "client";
	}
	internal static class ConfigApiHost
	{
		public static void Register(SyncedConfig config)
		{
			AppDomain.CurrentDomain.SetData(ConfigApiContract.DataKey(config.Mod.Guid), Build(config));
		}

		public static string Role()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return "none";
			}
			if (instance.IsServer())
			{
				if (ZNet.IsSinglePlayer)
				{
					return "solo";
				}
				if (!instance.IsDedicated() && !Application.isBatchMode)
				{
					return "host";
				}
				return "dedicated";
			}
			return "client";
		}

		public static string WorldName()
		{
			try
			{
				return (ZNet.World != null) ? (ZNet.World.m_name ?? "") : "";
			}
			catch (Exception)
			{
				return "";
			}
		}

		internal static Dictionary<string, Delegate> Build(SyncedConfig config)
		{
			ModInfo mod = config.Mod;
			return new Dictionary<string, Delegate>(StringComparer.Ordinal)
			{
				["ApiVersion"] = (Func<int>)(() => 1),
				["Guid"] = (Func<string>)(() => mod.Guid),
				["Name"] = (Func<string>)(() => mod.Name),
				["ModVersion"] = (Func<string>)(() => mod.Version),
				["Active"] = (Func<bool>)delegate
				{
					try
					{
						return Harmony.HasAnyPatches(mod.HarmonyId("Handshake"));
					}
					catch (Exception)
					{
						return false;
					}
				},
				["Keys"] = (Func<string[]>)delegate
				{
					List<string> list = new List<string>();
					foreach (ISyncedEntry entry in config.Entries)
					{
						list.Add(entry.Key);
					}
					return list.ToArray();
				},
				["Describe"] = (Func<string, string[]>)delegate(string key)
				{
					try
					{
						return config.Find(key)?.Describe();
					}
					catch (Exception)
					{
						return (string[])null;
					}
				},
				["Options"] = (Func<string, string[]>)delegate(string key)
				{
					try
					{
						return config.Find(key)?.Options();
					}
					catch (Exception)
					{
						return (string[])null;
					}
				},
				["Values"] = (Func<string, string[]>)delegate(string key)
				{
					try
					{
						ISyncedEntry syncedEntry = config.Find(key);
						return (syncedEntry == null) ? null : config.ValuesFor(syncedEntry);
					}
					catch (Exception)
					{
						return (string[])null;
					}
				},
				["Connected"] = (Func<bool>)(() => VersionHandshake.ConnectedToValidatedServer),
				["Role"] = new Func<string>(Role),
				["World"] = new Func<string>(WorldName),
				["CanChangeServer"] = (Func<bool>)delegate
				{
					try
					{
						return config.CanChangeServer;
					}
					catch (Exception)
					{
						return false;
					}
				},
				["Request"] = (Func<string, string, string, bool>)((string key, string value, string scope) => config.RequestSet(key, value, scope)),
				["LastResult"] = (Func<string[]>)(() => config.LastResult),
				["OnResult"] = new Action<Action<string, string, string, bool, string>>(config.AddResultCallback),
				["OnChanged"] = new Action<Action>(config.AddChangedCallback),
				["ChangeCounter"] = (Func<int>)(() => config.ChangeCounter)
			};
		}
	}
	internal static class FailureNotice
	{
		internal const string HookGroup = "FailureNotice";

		private const string QueueKey = "YesuBuildKit.FailureNotice.NextFree";

		internal static readonly FailureNoticeState State = new FailureNoticeState();

		private static ModInfo _mod;

		private static Harmony _hook;

		internal static string LastShown { get; private set; }

		internal static int ShownCount { get; private set; }

		public static void Record(ModInfo mod, string group)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			State.Record(group);
			_mod = mod;
			if (_hook != null)
			{
				return;
			}
			try
			{
				_hook = new Harmony(mod.HarmonyId("FailureNotice"));
				_hook.Patch((MethodBase)AccessTools.Method(typeof(Player), "OnSpawned", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(FailureNotice), "OnSpawnedPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Log.Error("Could not hook the player's spawn to say that a feature is off; the log line above is the only notice. " + ex.Message);
			}
		}

		private static void OnSpawnedPostfix(Player __instance)
		{
			try
			{
				ZNet instance = ZNet.instance;
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)instance == (Object)null) && State.Begin(instance))
				{
					((MonoBehaviour)instance).StartCoroutine(Show(instance));
				}
			}
			catch (Exception ex)
			{
				Log.Error("Could not queue the notice that a feature is off: " + ex.Message);
			}
		}

		private static IEnumerator Show(ZNet session)
		{
			float unscaledTime = Time.unscaledTime;
			float nextFree = ((AppDomain.CurrentDomain.GetData("YesuBuildKit.FailureNotice.NextFree") is float num) ? num : 0f);
			float newNextFree;
			float num2 = FailureNoticeState.Slot(unscaledTime, nextFree, out newNextFree);
			AppDomain.CurrentDomain.SetData("YesuBuildKit.FailureNotice.NextFree", newNextFree);
			yield return (object)new WaitForSecondsRealtime(num2 - unscaledTime);
			while ((Object)(object)session != (Object)null && (Object)(object)Player.m_localPlayer == (Object)null)
			{
				yield return (object)new WaitForSecondsRealtime(1f);
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)session == (Object)null) && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)MessageHud.instance == (Object)null))
			{
				string text = FailureNoticeState.Line((_mod != null) ? _mod.Name : null, State.Failed);
				((Character)localPlayer).Message((MessageType)1, text, 0, (Sprite)null, false);
				State.Shown(session);
				LastShown = text;
				ShownCount++;
				Log.Warning("Told the player: " + text);
			}
		}
	}
	internal sealed class FailureNoticeState
	{
		public const float Spacing = 4f;

		public const float FirstDelay = 3f;

		private readonly List<string> _failed = new List<string>();

		private object _session;

		private bool _shown;

		public IList<string> Failed => _failed;

		public void Record(string group)
		{
			if (!string.IsNullOrEmpty(group) && !_failed.Contains(group))
			{
				_failed.Add(group);
			}
		}

		public bool Begin(object session)
		{
			if (_failed.Count == 0 || session == null)
			{
				return false;
			}
			if (session == _session)
			{
				return false;
			}
			_session = session;
			_shown = false;
			return true;
		}

		public void Shown(object session)
		{
			if (session == _session)
			{
				_shown = true;
			}
		}

		public bool WasShown(object session)
		{
			if (_shown)
			{
				return session == _session;
			}
			return false;
		}

		public static float Slot(float now, float nextFree, out float newNextFree)
		{
			float num = Math.Max(now + 3f, nextFree);
			newNextFree = num + 4f;
			return num;
		}

		public static string Line(string modName, IList<string> groups)
		{
			string text = DisplayName(modName);
			if (groups == null || groups.Count == 0)
			{
				return text + " could not patch the game";
			}
			string text2 = ((groups.Count != 1) ? (string.Join(", ", Take(groups, groups.Count - 1)) + " and " + groups[groups.Count - 1] + " are") : (groups[0] + " is"));
			return text + " could not patch the game, so " + text2 + " off";
		}

		public static string DisplayName(string modName)
		{
			if (string.IsNullOrEmpty(modName))
			{
				return "A YesuBuildKit mod";
			}
			if (!modName.StartsWith("YesuBuildKit ", StringComparison.Ordinal) || modName.Length <= "YesuBuildKit ".Length)
			{
				return modName;
			}
			return modName.Substring("YesuBuildKit ".Length);
		}

		private static string[] Take(IList<string> list, int count)
		{
			string[] array = new string[count];
			for (int i = 0; i < count; i++)
			{
				array[i] = list[i];
			}
			return array;
		}
	}
	internal enum JoinOutcome
	{
		Validated,
		JoinsWithoutMod,
		Refused
	}
	internal static class HandshakeRules
	{
		public static bool Validates(string theirs, string mine)
		{
			if (theirs != null)
			{
				return theirs == mine;
			}
			return false;
		}

		public static JoinOutcome Decide(bool optional, bool validated)
		{
			if (validated)
			{
				return JoinOutcome.Validated;
			}
			if (!optional)
			{
				return JoinOutcome.Refused;
			}
			return JoinOutcome.JoinsWithoutMod;
		}

		public static bool SendsConfig(JoinOutcome outcome)
		{
			return outcome == JoinOutcome.Validated;
		}

		public static bool AcceptsSetRequest(bool optional, bool validated)
		{
			return !optional || validated;
		}

		public static string ClientMismatchLine(bool optional, string modName, string server, string mine)
		{
			if (Validates(server, mine))
			{
				return null;
			}
			if (!optional)
			{
				return modName + ": the server runs version " + server + ", you have " + mine + ".";
			}
			return modName + ": the server runs version " + server + ", you have " + mine + ". Joining without the server's part of the mod.";
		}
	}
	internal static class Log
	{
		private static ManualLogSource _source;

		private static Func<bool> _debugEnabled = () => false;

		public static void Init(ManualLogSource source, Func<bool> debugEnabled)
		{
			_source = source;
			if (debugEnabled != null)
			{
				_debugEnabled = debugEnabled;
			}
		}

		public static void Info(string message)
		{
			ManualLogSource source = _source;
			if (source != null)
			{
				source.LogInfo((object)message);
			}
		}

		public static void Warning(string message)
		{
			ManualLogSource source = _source;
			if (source != null)
			{
				source.LogWarning((object)message);
			}
		}

		public static void Error(string message)
		{
			ManualLogSource source = _source;
			if (source != null)
			{
				source.LogError((object)message);
			}
		}

		public static void Debug(string message)
		{
			if (_source != null && _debugEnabled())
			{
				_source.LogInfo((object)("[debug] " + message));
			}
		}
	}
	internal sealed class ModInfo
	{
		public const string VersionRpc = "Version";

		public const string ConfigRpc = "Config";

		public const string ConfigInfoRpc = "ConfigInfo";

		public const string SetConfigRpc = "SetConfig";

		public const string SetConfigResultRpc = "SetConfigResult";

		public const string VersionHandshakeGroup = "Handshake";

		public string Guid { get; }

		public string Name { get; }

		public string Version { get; }

		public ModInfo(string guid, string name, string version)
		{
			if (string.IsNullOrWhiteSpace(guid))
			{
				throw new ArgumentException("A mod needs a GUID.", "guid");
			}
			if (guid != guid.ToLowerInvariant())
			{
				throw new ArgumentException("Mod GUIDs are lowercase.", "guid");
			}
			Guid = guid;
			Name = name ?? guid;
			Version = version ?? "0.0.0";
		}

		public string RpcName(string suffix)
		{
			return Scoped(suffix);
		}

		public string ZdoKey(string suffix)
		{
			return Scoped(suffix);
		}

		public string HarmonyId(string group)
		{
			return Scoped(group);
		}

		public IEnumerable<string> CoreNames()
		{
			yield return RpcName("Version");
			yield return RpcName("Config");
			yield return RpcName("ConfigInfo");
			yield return RpcName("SetConfig");
			yield return RpcName("SetConfigResult");
			yield return HarmonyId("Handshake");
		}

		private string Scoped(string suffix)
		{
			if (string.IsNullOrWhiteSpace(suffix))
			{
				throw new ArgumentException("A scoped name needs a suffix.", "suffix");
			}
			return Guid + "." + suffix;
		}
	}
	internal sealed class PatchGroup
	{
		private readonly Harmony _harmony;

		public string Name { get; }

		public bool Applied { get; private set; }

		private PatchGroup(string name, Harmony harmony)
		{
			Name = name;
			_harmony = harmony;
		}

		public static PatchGroup Apply(ModInfo mod, string group, params Type[] patchClasses)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			PatchGroup patchGroup = new PatchGroup(group, new Harmony(mod.HarmonyId(group)));
			try
			{
				foreach (Type type in patchClasses)
				{
					patchGroup._harmony.CreateClassProcessor(type).Patch();
				}
				patchGroup.Applied = true;
				Log.Debug("Patched group " + group + " (" + patchClasses.Length + " classes).");
			}
			catch (Exception ex)
			{
				Log.Error("Could not patch group '" + group + "'; that feature is off. The game may have updated. " + ex);
				try
				{
					patchGroup._harmony.UnpatchSelf();
				}
				catch (Exception ex2)
				{
					Log.Error("Rollback of group '" + group + "' failed: " + ex2.Message);
				}
				patchGroup.Applied = false;
				FailureNotice.Record(mod, group);
			}
			return patchGroup;
		}
	}
	internal enum SetScope
	{
		World,
		Server,
		ClearWorld
	}
	internal static class SetScopeText
	{
		public const string World = "World";

		public const string Server = "Server";

		public const string ClearWorld = "ClearWorld";

		public static string Name(SetScope scope)
		{
			return scope switch
			{
				SetScope.World => "World", 
				SetScope.Server => "Server", 
				_ => "ClearWorld", 
			};
		}

		public static bool TryParse(string text, out SetScope scope)
		{
			scope = SetScope.World;
			if (text == null)
			{
				return false;
			}
			switch (text.Trim().ToLowerInvariant())
			{
			case "world":
				scope = SetScope.World;
				return true;
			case "server":
				scope = SetScope.Server;
				return true;
			case "clearworld":
				scope = SetScope.ClearWorld;
				return true;
			default:
				return false;
			}
		}
	}
	internal sealed class SetRequestFacts
	{
		public bool HandshakeValidated;

		public bool IsHostOrAdmin;

		public bool RateLimited;

		public bool ScopeKnown;

		public SetScope Scope;

		public bool KeyKnown;

		public string Key;

		public bool ValueTextSafe;

		public bool WorldLoaded;

		public bool ValueAccepted;

		public string ValueError;
	}
	internal sealed class SetDecision
	{
		public bool Accepted { get; }

		public string Reason { get; }

		public SetDecision(bool accepted, string reason)
		{
			Accepted = accepted;
			Reason = reason ?? "";
		}

		public override string ToString()
		{
			if (!Accepted)
			{
				return "refused: " + Reason;
			}
			return "accepted";
		}
	}
	internal static class SetRequestRules
	{
		public const int MaxValueChars = 1024;

		public const int MaxKeyChars = 200;

		public const string NotValidated = "this mod's version does not match the server's.";

		public const string RateLimited = "too many changes too quickly; wait a moment.";

		public const string NotAdmin = "only the host or an admin can change this.";

		public const string BadScope = "the scope must be World, Server, or ClearWorld.";

		public const string NoWorld = "no world is loaded, so there is nowhere to keep a world setting.";

		public const string BadValueText = "the value is too long or has line breaks.";

		public static string UnknownKey(string key)
		{
			return "this mod has no synced setting named '" + Clip(key) + "'.";
		}

		public static SetDecision Decide(SetRequestFacts f)
		{
			if (!f.HandshakeValidated)
			{
				return new SetDecision(accepted: false, "this mod's version does not match the server's.");
			}
			if (f.RateLimited)
			{
				return new SetDecision(accepted: false, "too many changes too quickly; wait a moment.");
			}
			if (!f.IsHostOrAdmin)
			{
				return new SetDecision(accepted: false, "only the host or an admin can change this.");
			}
			if (!f.ScopeKnown)
			{
				return new SetDecision(accepted: false, "the scope must be World, Server, or ClearWorld.");
			}
			if (!f.KeyKnown)
			{
				return new SetDecision(accepted: false, UnknownKey(f.Key));
			}
			if (f.Scope != SetScope.ClearWorld && !f.ValueTextSafe)
			{
				return new SetDecision(accepted: false, "the value is too long or has line breaks.");
			}
			if (f.Scope != SetScope.Server && !f.WorldLoaded)
			{
				return new SetDecision(accepted: false, "no world is loaded, so there is nowhere to keep a world setting.");
			}
			if (f.Scope != SetScope.ClearWorld && !f.ValueAccepted)
			{
				return new SetDecision(accepted: false, string.IsNullOrEmpty(f.ValueError) ? "the value is not valid for this setting." : f.ValueError);
			}
			return new SetDecision(accepted: true, "");
		}

		public static bool IsSafeValueText(string text)
		{
			if (text == null || text.Length > 1024)
			{
				return false;
			}
			foreach (char c in text)
			{
				if (c == '\n' || c == '\r' || c == '\0')
				{
					return false;
				}
			}
			return true;
		}

		public static bool IsSafeKey(string key)
		{
			if (string.IsNullOrEmpty(key) || key.Length > 200)
			{
				return false;
			}
			for (int i = 0; i < key.Length; i++)
			{
				if (key[i] < ' ')
				{
					return false;
				}
			}
			return true;
		}

		private static string Clip(string text)
		{
			if (text == null)
			{
				return "";
			}
			if (text.Length > 60)
			{
				return text.Substring(0, 60) + "...";
			}
			return text;
		}
	}
	internal sealed class RateLimiter
	{
		private sealed class Bucket
		{
			public double Tokens;

			public double At;
		}

		private readonly double _capacity;

		private readonly double _refillPerSecond;

		private readonly Dictionary<long, Bucket> _buckets = new Dictionary<long, Bucket>();

		public int Tracked => _buckets.Count;

		public RateLimiter(double capacity, double refillPerSecond)
		{
			if (capacity < 1.0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			if (refillPerSecond < 0.0)
			{
				throw new ArgumentOutOfRangeException("refillPerSecond");
			}
			_capacity = capacity;
			_refillPerSecond = refillPerSecond;
		}

		public bool TryTake(long sender, double now)
		{
			if (!_buckets.TryGetValue(sender, out var value))
			{
				value = new Bucket
				{
					Tokens = _capacity,
					At = now
				};
				_buckets[sender] = value;
			}
			double num = now - value.At;
			if (num > 0.0)
			{
				value.Tokens = Math.Min(_capacity, value.Tokens + num * _refillPerSecond);
				value.At = now;
			}
			else if (num < 0.0)
			{
				value.At = now;
			}
			if (value.Tokens < 1.0)
			{
				return false;
			}
			value.Tokens -= 1.0;
			return true;
		}

		public void Forget(long sender)
		{
			_buckets.Remove(sender);
		}

		public void Clear()
		{
			_buckets.Clear();
		}
	}
	internal sealed class SyncedConfig
	{
		private sealed class InfoItem
		{
			public string ServerDefault;

			public bool HasOverride;

			public string Override;
		}

		private sealed class Pending
		{
			public string Key;

			public string Scope;

			public string Value;

			public float SentAt;
		}

		private const int ProtocolVersion = 1;

		private const float RequestTimeout = 10f;

		private readonly ModInfo _mod;

		private readonly ConfigFile _file;

		private readonly List<ISyncedEntry> _entries = new List<ISyncedEntry>();

		private readonly Dictionary<string, ISyncedEntry> _byKey = new Dictionary<string, ISyncedEntry>(StringComparer.Ordinal);

		private readonly OverrideStore _store;

		private readonly RateLimiter _limiter = new RateLimiter(8.0, 2.0);

		private readonly Dictionary<string, InfoItem> _info = new Dictionary<string, InfoItem>(StringComparer.Ordinal);

		private readonly Dictionary<long, Pending> _pending = new Dictionary<long, Pending>();

		private readonly List<Action> _changedCallbacks = new List<Action>();

		private readonly List<Action<string, string, string, bool, string>> _resultCallbacks = new List<Action<string, string, string, bool, string>>();

		private string[] _lastResult;

		private int _resultCounter;

		private int _changeCounter;

		private long _nextRequestId;

		private bool _infoAdmin;

		private float _now;

		private FileSystemWatcher _watcher;

		private volatile bool _fileDirty;

		private bool _valuesDirty;

		private float _reloadAt;

		private bool _watchTried;

		public ModInfo Mod => _mod;

		internal IList<ISyncedEntry> Entries => _entries;

		internal int ChangeCounter => _changeCounter;

		internal string[] LastResult
		{
			get
			{
				if (_lastResult != null)
				{
					return (string[])_lastResult.Clone();
				}
				return null;
			}
		}

		internal bool IsServerSide
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal bool CanChangeServer
		{
			get
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return false;
				}
				if (instance.IsServer())
				{
					return true;
				}
				if (!VersionHandshake.ConnectedToValidatedServer)
				{
					return false;
				}
				if (_infoAdmin)
				{
					return true;
				}
				try
				{
					return instance.LocalPlayerIsAdminOrHost();
				}
				catch (Exception)
				{
					return false;
				}
			}
		}

		public event Action Changed;

		public SyncedConfig(ModInfo mod, ConfigFile file)
		{
			_mod = mod;
			_file = file;
			_file.SettingChanged += delegate
			{
				_valuesDirty = true;
			};
			string directoryName = Path.GetDirectoryName(file.ConfigFilePath);
			_store = new OverrideStore(mod.Guid, directoryName, ValidateOverrideLine, delegate(string message)
			{
				Log.Warning(message);
			});
			try
			{
				ConfigApiHost.Register(this);
			}
			catch (Exception ex)
			{
				Log.Warning("Could not publish the settings contract: " + ex.Message);
			}
		}

		public SyncedEntry<T> Bind<T>(string section, string key, T defaultValue, string description)
		{
			return Bind(section, key, defaultValue, description, null);
		}

		public SyncedEntry<T> Bind<T>(string section, string key, T defaultValue, string description, AcceptableValueBase acceptable)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			SyncedEntry<T> syncedEntry = new SyncedEntry<T>(_file.Bind<T>(section, key, defaultValue, new ConfigDescription(description + " [Synced: the server's value wins.]", acceptable, Array.Empty<object>())), description);
			_entries.Add(syncedEntry);
			_byKey[syncedEntry.Key] = syncedEntry;
			return syncedEntry;
		}

		internal ISyncedEntry Find(string key)
		{
			if (key == null || !_byKey.TryGetValue(key, out var value))
			{
				return null;
			}
			return value;
		}

		internal void AddChangedCallback(Action callback)
		{
			if (callback != null)
			{
				_changedCallbacks.Add(callback);
			}
		}

		internal void AddResultCallback(Action<string, string, string, bool, string> callback)
		{
			if (callback != null)
			{
				_resultCallbacks.Add(callback);
			}
		}

		internal string[] ValuesFor(ISyncedEntry entry)
		{
			string[] array = new string[5];
			string text = (array[0] = entry.Serialize());
			array[3] = entry.EffectiveText();
			if (VersionHandshake.ConnectedToValidatedServer)
			{
				bool serverHasOverride = false;
				string text2 = array[3];
				string text3 = null;
				if (_info.TryGetValue(entry.Key, out var value))
				{
					text2 = value.ServerDefault;
					serverHasOverride = value.HasOverride;
					text3 = (value.HasOverride ? value.Override : null);
				}
				array[1] = text2;
				array[2] = text3;
				array[4] = ValueResolver.Name(ValueResolver.ClientSource(connectedToServer: true, serverHasOverride));
				return array;
			}
			array[1] = text;
			array[2] = (entry.HasOverride ? entry.OverrideText : null);
			if (IsServerSide)
			{
				ValueResolver.Effective(array[2], text, out var source);
				array[4] = ValueResolver.Name(source);
			}
			else
			{
				array[4] = ValueResolver.Name(ValueSource.Local);
			}
			return array;
		}

		public ZPackage Write()
		{
			//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(_entries.Count);
			foreach (ISyncedEntry entry in _entries)
			{
				val.Write(entry.Key);
				val.Write(entry.EffectiveText());
			}
			return val;
		}

		public ZPackage WriteInfo(bool receiverIsAdmin)
		{
			//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(receiverIsAdmin);
			val.Write(_entries.Count);
			foreach (ISyncedEntry entry in _entries)
			{
				val.Write(entry.Key);
				val.Write(entry.Serialize());
				val.Write(entry.HasOverride);
				val.Write(entry.HasOverride ? entry.OverrideText : "");
			}
			return val;
		}

		public void Read(ZPackage pkg)
		{
			Dictionary<string, ISyncedEntry> dictionary = new Dictionary<string, ISyncedEntry>();
			foreach (ISyncedEntry entry in _entries)
			{
				dictionary[entry.Key] = entry;
			}
			int num = pkg.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = pkg.ReadString();
				string serverValue = pkg.ReadString();
				if (dictionary.TryGetValue(text, out var value))
				{
					try
					{
						value.SetServerValue(serverValue);
					}
					catch (Exception ex)
					{
						Log.Warning("Server sent a bad value for " + text + ": " + ex.Message);
					}
				}
			}
			Log.Info("Applied " + num + " config values from the server.");
			RaiseChanged();
		}

		public void ReadInfo(ZPackage pkg)
		{
			try
			{
				if (pkg.ReadInt() != 1)
				{
					return;
				}
				bool infoAdmin = pkg.ReadBool();
				int num = pkg.ReadInt();
				Dictionary<string, InfoItem> dictionary = new Dictionary<string, InfoItem>(StringComparer.Ordinal);
				for (int i = 0; i < num; i++)
				{
					string key = pkg.ReadString();
					InfoItem infoItem = new InfoItem
					{
						ServerDefault = pkg.ReadString(),
						HasOverride = pkg.ReadBool()
					};
					string text = pkg.ReadString();
					infoItem.Override = (infoItem.HasOverride ? text : null);
					dictionary[key] = infoItem;
				}
				_infoAdmin = infoAdmin;
				_info.Clear();
				foreach (KeyValuePair<string, InfoItem> item in dictionary)
				{
					_info[item.Key] = item.Value;
				}
				RaiseInfoChanged();
			}
			catch (Exception ex)
			{
				Log.Warning("Could not read the server's setting details: " + ex.Message);
			}
		}

		public void UnlockAll()
		{
			foreach (ISyncedEntry entry in _entries)
			{
				entry.Unlock();
			}
			_info.Clear();
			_infoAdmin = false;
			FailPending("Disconnected before the server answered.");
			RaiseChanged();
		}

		public void SendTo(ZRpc rpc)
		{
			rpc.Invoke(_mod.RpcName("Config"), new object[1] { Write() });
			bool receiverIsAdmin = false;
			try
			{
				receiverIsAdmin = (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsAdmin(rpc.GetSocket().GetHostName());
			}
			catch (Exception)
			{
			}
			rpc.Invoke(_mod.RpcName("ConfigInfo"), new object[1] { WriteInfo(receiverIsAdmin) });
		}

		public void WorldStarted(string worldName)
		{
			try
			{
				_store.Load(worldName);
				ApplyOverridesFromStore();
				_valuesDirty = true;
				Log.Debug("World '" + worldName + "' started with " + _store.Count + " override(s) for " + _mod.Name + ".");
			}
			catch (Exception ex)
			{
				Log.Warning("Could not load the world settings for '" + worldName + "'; the server config stays in force. " + ex.Message);
				ClearOverrides();
			}
		}

		public void WorldEnded()
		{
			try
			{
				bool isLoaded = _store.IsLoaded;
				_store.Unload();
				ClearOverrides();
				_limiter.Clear();
				FailPending("The world ended before the server answered.");
				if (isLoaded)
				{
					_valuesDirty = true;
				}
			}
			catch (Exception ex)
			{
				Log.Warning("Could not clear the world settings: " + ex.Message);
			}
		}

		private void ClearOverrides()
		{
			foreach (ISyncedEntry entry in _entries)
			{
				try
				{
					entry.SetOverride(null);
				}
				catch (Exception)
				{
				}
			}
		}

		private string ValidateOverrideLine(string key, string value)
		{
			if (!_byKey.TryGetValue(key, out var value2))
			{
				return "this mod has no synced setting with that name.";
			}
			string canonical;
			return value2.Validate(value, out canonical);
		}

		private void ApplyOverridesFromStore()
		{
			foreach (ISyncedEntry entry in _entries)
			{
				try
				{
					if (_store.TryGet(entry.Key, out var text))
					{
						entry.SetOverride(text);
					}
					else
					{
						entry.SetOverride(null);
					}
				}
				catch (Exception ex)
				{
					Log.Warning("Ignoring the world setting for " + entry.Key + ": " + ex.Message);
					try
					{
						entry.SetOverride(null);
					}
					catch (Exception)
					{
					}
				}
			}
		}

		private void EnsureWorld()
		{
			ZNet instance = ZNet.instance;
			string text = null;
			if ((Object)(object)instance != (Object)null && instance.IsServer() && !instance.HaveStopped && ZNet.World != null)
			{
				text = ZNet.World.m_name ?? "";
			}
			if (text == null)
			{
				if (_store.IsLoaded)
				{
					WorldEnded();
				}
			}
			else if (_store.WorldName != text)
			{
				WorldStarted(text);
			}
		}

		public bool RequestSet(string key, string valueText, string scopeText)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			try
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance == (Object)null)
				{
					Record(key, scopeText, valueText, accepted: false, "load a world first; there is no game session.");
					return false;
				}
				if (instance.IsServer())
				{
					SetScope scope;
					SetDecision setDecision = Evaluate(validated: true, hostOrAdmin: true, limited: false, key, scopeText, valueText, out scope);
					Record(key, scopeText, valueText, setDecision.Accepted, setDecision.Reason);
					return setDecision.Accepted;
				}
				ZRpc serverRPC = instance.GetServerRPC();
				if (!VersionHandshake.ConnectedToValidatedServer || serverRPC == null)
				{
					Record(key, scopeText, valueText, accepted: false, "the server does not have this mod at the same version.");
					return false;
				}
				if (!SetRequestRules.IsSafeKey(key) || !SetScopeText.TryParse(scopeText, out var scope2) || (scope2 != SetScope.ClearWorld && !SetRequestRules.IsSafeValueText(valueText)))
				{
					Record(key, scopeText, valueText, accepted: false, "that request is not valid.");
					return false;
				}
				long num = ++_nextRequestId;
				ZPackage val = new ZPackage();
				val.Write(1);
				val.Write(num);
				val.Write(key);
				val.Write(valueText ?? "");
				val.Write(SetScopeText.Name(scope2));
				_pending[num] = new Pending
				{
					Key = key,
					Scope = SetScopeText.Name(scope2),
					Value = (valueText ?? ""),
					SentAt = _now
				};
				serverRPC.Invoke(_mod.RpcName("SetConfig"), new object[1] { val });
				return true;
			}
			catch (Exception ex)
			{
				Log.Warning("Setting request failed: " + ex.Message);
				try
				{
					Record(key, scopeText, valueText, accepted: false, "something went wrong sending the request.");
				}
				catch (Exception)
				{
				}
				return false;
			}
		}

		public void HandleSetRequest(ZRpc rpc, ZPackage pkg)
		{
			long requestId = 0L;
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
				{
					return;
				}
				int num = pkg.ReadInt();
				requestId = pkg.ReadLong();
				string text = pkg.ReadString();
				string valueText = pkg.ReadString();
				string scopeText = pkg.ReadString();
				if (num != 1)
				{
					Reply(rpc, requestId, new SetDecision(accepted: false, "the server speaks a different version of this request."));
					return;
				}
				bool validated = VersionHandshake.IsValidated(rpc);
				bool flag = IsAdmin(rpc);
				bool limited = !_limiter.TryTake(RuntimeHelpers.GetHashCode(rpc), _now);
				SetScope scope;
				SetDecision setDecision = Evaluate(validated, flag, limited, text, scopeText, valueText, out scope);
				if (setDecision.Accepted)
				{
					Log.Info("Setting " + text + " changed by a client (" + SetScopeText.Name(scope) + ").");
				}
				else
				{
					Log.Debug("Refused a setting request for " + text + ": " + setDecision.Reason);
				}
				Reply(rpc, requestId, setDecision, flag);
			}
			catch (Exception ex)
			{
				Log.Warning("A setting request could not be handled: " + ex.Message);
				try
				{
					Reply(rpc, requestId, new SetDecision(accepted: false, "the server could not read that request."));
				}
				catch (Exception)
				{
				}
			}
		}

		private static bool IsAdmin(ZRpc rpc)
		{
			try
			{
				return (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsAdmin(rpc.GetSocket().GetHostName());
			}
			catch (Exception)
			{
				return false;
			}
		}

		private void Reply(ZRpc rpc, long requestId, SetDecision decision, bool isAdmin = false)
		{
			//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(requestId);
			val.Write(decision.Accepted);
			val.Write(decision.Reason);
			val.Write(isAdmin);
			rpc.Invoke(_mod.RpcName("SetConfigResult"), new object[1] { val });
		}

		public void HandleSetResult(ZPackage pkg)
		{
			try
			{
				if (pkg.ReadInt() == 1)
				{
					long key = pkg.ReadLong();
					bool accepted = pkg.ReadBool();
					string message = pkg.ReadString();
					bool infoAdmin = pkg.ReadBool();
					_infoAdmin = infoAdmin;
					if (_pending.TryGetValue(key, out var value))
					{
						_pending.Remove(key);
						Record(value.Key, value.Scope, value.Value, accepted, message);
					}
				}
			}
			catch (Exception ex)
			{
				Log.Warning("Could not read the server's answer to a setting request: " + ex.Message);
			}
		}

		private SetDecision Evaluate(bool validated, bool hostOrAdmin, bool limited, string key, string scopeText, string valueText, out SetScope scope)
		{
			SetRequestFacts setRequestFacts = new SetRequestFacts
			{
				HandshakeValidated = validated,
				IsHostOrAdmin = hostOrAdmin,
				RateLimited = limited,
				Key = key,
				ScopeKnown = SetScopeText.TryParse(scopeText, out scope),
				WorldLoaded = _store.IsLoaded
			};
			setRequestFacts.Scope = scope;
			ISyncedEntry syncedEntry = (SetRequestRules.IsSafeKey(key) ? Find(key) : null);
			setRequestFacts.KeyKnown = syncedEntry != null;
			setRequestFacts.ValueTextSafe = SetRequestRules.IsSafeValueText(valueText);
			string canonical = null;
			if (syncedEntry != null && setRequestFacts.ScopeKnown && scope != SetScope.ClearWorld && setRequestFacts.ValueTextSafe)
			{
				setRequestFacts.ValueError = syncedEntry.Validate(valueText, out canonical);
				setRequestFacts.ValueAccepted = setRequestFacts.ValueError == null;
			}
			SetDecision setDecision = SetRequestRules.Decide(setRequestFacts);
			if (!setDecision.Accepted)
			{
				return setDecision;
			}
			return Apply(syncedEntry, scope, canonical);
		}

		private SetDecision Apply(ISyncedEntry entry, SetScope scope, string canonical)
		{
			string error;
			switch (scope)
			{
			case SetScope.World:
				if (!_store.Set(entry.Key, canonical, out error))
				{
					return new SetDecision(accepted: false, "the world setting could not be saved: " + error);
				}
				entry.SetOverride(canonical);
				_valuesDirty = true;
				return new SetDecision(accepted: true, "Saved for this world");
			case SetScope.ClearWorld:
				if (!_store.Remove(entry.Key, out error))
				{
					return new SetDecision(accepted: false, "the world setting could not be cleared: " + error);
				}
				entry.SetOverride(null);
				_valuesDirty = true;
				return new SetDecision(accepted: true, "Cleared for this world; the server default applies");
			default:
				try
				{
					entry.SetFileValue(canonical);
					if (!_file.SaveOnConfigSet)
					{
						_file.Save();
					}
				}
				catch (Exception ex)
				{
					return new SetDecision(accepted: false, "the server default could not be saved: " + ex.Message);
				}
				_valuesDirty = true;
				return new SetDecision(accepted: true, entry.HasOverride ? "Saved as the server default (this world has its own value, which still applies)" : "Saved as the server default");
			}
		}

		private void Record(string key, string scope, string valueText, bool accepted, string message)
		{
			_resultCounter++;
			_lastResult = new string[5];
			_lastResult[0] = _resultCounter.ToString();
			_lastResult[1] = key ?? "";
			_lastResult[2] = scope ?? "";
			_lastResult[3] = (accepted ? "ok" : "refused");
			_lastResult[4] = message ?? "";
			Action<string, string, string, bool, string>[] array = _resultCallbacks.ToArray();
			foreach (Action<string, string, string, bool, string> action in array)
			{
				try
				{
					action(key ?? "", scope ?? "", valueText ?? "", accepted, message ?? "");
				}
				catch (Exception ex)
				{
					Log.Warning("A settings result callback failed: " + ex.Message);
				}
			}
		}

		private void FailPending(string reason)
		{
			if (_pending.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<long, Pending> item in new List<KeyValuePair<long, Pending>>(_pending))
			{
				Record(item.Value.Key, item.Value.Scope, item.Value.Value, accepted: false, reason);
			}
			_pending.Clear();
		}

		internal void ForgetPeer(ZRpc rpc)
		{
			if (rpc != null)
			{
				_limiter.Forget(RuntimeHelpers.GetHashCode(rpc));
			}
		}

		public void WatchFile()
		{
			if (_watcher != null)
			{
				return;
			}
			try
			{
				string configFilePath = _file.ConfigFilePath;
				_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath));
				_watcher.Changed += delegate
				{
					_fileDirty = true;
				};
				_watcher.Created += delegate
				{
					_fileDirty = true;
				};
				_watcher.Renamed += delegate
				{
					_fileDirty = true;
				};
				_watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				Log.Warning("Cannot watch the config file; restart the server to apply edits. " + ex.Message);
			}
		}

		public void Tick(float now)
		{
			_now = now;
			if (!_watchTried && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				_watchTried = true;
				try
				{
					WatchFile();
				}
				catch (Exception ex)
				{
					Log.Warning("Cannot watch the config file; restart the server to apply edits. " + ex.Message);
				}
			}
			try
			{
				EnsureWorld();
				if (_store.Poll(now))
				{
					ApplyOverridesFromStore();
					_valuesDirty = true;
					Log.Info("World settings for " + _mod.Name + " were edited on disk and applied.");
				}
				if (_pending.Count > 0)
				{
					ExpirePending(now);
				}
			}
			catch (Exception ex2)
			{
				Log.Warning("World settings check failed: " + ex2.Message);
			}
			if (_fileDirty)
			{
				_fileDirty = false;
				_reloadAt = now + 0.5f;
			}
			if (_reloadAt > 0f && now >= _reloadAt)
			{
				_reloadAt = 0f;
				try
				{
					_file.Reload();
					_valuesDirty = true;
				}
				catch (Exception ex3)
				{
					Log.Warning("Config reload failed: " + ex3.Message);
				}
			}
			if (!_valuesDirty)
			{
				return;
			}
			_valuesDirty = false;
			RaiseChanged();
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer?.m_rpc != null && VersionHandshake.IsValidated(peer.m_rpc))
				{
					SendTo(peer.m_rpc);
				}
			}
		}

		private void ExpirePending(float now)
		{
			List<long> list = null;
			foreach (KeyValuePair<long, Pending> item in _pending)
			{
				if (now - item.Value.SentAt > 10f)
				{
					if (list == null)
					{
						list = new List<long>();
					}
					list.Add(item.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (long item2 in list)
			{
				Pending pending = _pending[item2];
				_pending.Remove(item2);
				Record(pending.Key, pending.Scope, pending.Value, accepted: false, "the server did not answer.");
			}
		}

		private void RaiseChanged()
		{
			_changeCounter++;
			this.Changed?.Invoke();
			RunChangedCallbacks();
		}

		private void RaiseInfoChanged()
		{
			_changeCounter++;
			RunChangedCallbacks();
		}

		private void RunChangedCallbacks()
		{
			Action[] array = _changedCallbacks.ToArray();
			foreach (Action action in array)
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					Log.Warning("A settings change callback failed: " + ex.Message);
				}
			}
		}
	}
	internal interface ISyncedEntry
	{
		string Key { get; }

		Type ValueType { get; }

		string Description { get; }

		string DefaultText { get; }

		bool HasOverride { get; }

		string OverrideText { get; }

		string Serialize();

		string EffectiveText();

		string Validate(string text, out string canonical);

		void SetServerValue(string text);

		void Unlock();

		void SetOverride(string textOrNull);

		void SetFileValue(string text);

		string[] Describe();

		string[] Options();
	}
	internal sealed class SyncedEntry<T> : ISyncedEntry
	{
		private T _serverValue;

		private T _override;

		private bool _hasOverride;

		public ConfigEntry<T> Entry { get; }

		public bool Locked { get; private set; }

		public T Value
		{
			get
			{
				if (!Locked)
				{
					if (!_hasOverride)
					{
						return Entry.Value;
					}
					return _override;
				}
				return _serverValue;
			}
		}

		public string Key => ((ConfigEntryBase)Entry).Definition.Section + "." + ((ConfigEntryBase)Entry).Definition.Key;

		public Type ValueType => typeof(T);

		public string Description { get; }

		public bool HasOverride => _hasOverride;

		public string OverrideText
		{
			get
			{
				if (!_hasOverride)
				{
					return null;
				}
				return TomlTypeConverter.ConvertToString((object)_override, typeof(T));
			}
		}

		public string DefaultText
		{
			get
			{
				try
				{
					return TomlTypeConverter.ConvertToString(((ConfigEntryBase)Entry).DefaultValue, typeof(T));
				}
				catch (Exception)
				{
					return "";
				}
			}
		}

		public SyncedEntry(ConfigEntry<T> entry, string description)
		{
			Entry = entry;
			Description = description ?? "";
		}

		public string Serialize()
		{
			return TomlTypeConverter.ConvertToString((object)Entry.Value, typeof(T));
		}

		public string EffectiveText()
		{
			return TomlTypeConverter.ConvertToString((object)Value, typeof(T));
		}

		public void SetServerValue(string text)
		{
			_serverValue = (T)TomlTypeConverter.ConvertToValue(text, typeof(T));
			Locked = true;
		}

		public void Unlock()
		{
			Locked = false;
			_serverValue = default(T);
		}

		public void SetOverride(string textOrNull)
		{
			if (textOrNull == null)
			{
				_hasOverride = false;
				_override = default(T);
			}
			else
			{
				_override = (T)TomlTypeConverter.ConvertToValue(textOrNull, typeof(T));
				_hasOverride = true;
			}
		}

		public void SetFileValue(string text)
		{
			Entry.Value = (T)TomlTypeConverter.ConvertToValue(text, typeof(T));
		}

		public string Validate(string text, out string canonical)
		{
			canonical = null;
			Type typeFromHandle = typeof(T);
			if (text == null)
			{
				return "no value was given.";
			}
			if (!TomlTypeConverter.CanConvert(typeFromHandle))
			{
				return "this setting's type (" + typeFromHandle.Name + ") cannot be changed from text.";
			}
			object obj;
			try
			{
				obj = TomlTypeConverter.ConvertToValue(text, typeFromHandle);
			}
			catch (Exception)
			{
				return "'" + Clip(text) + "' is not a valid " + typeFromHandle.Name + ".";
			}
			if (obj == null)
			{
				return "'" + Clip(text) + "' is not a valid " + typeFromHandle.Name + ".";
			}
			if (obj is float || obj is double)
			{
				double d = Convert.ToDouble(obj);
				if (double.IsNaN(d) || double.IsInfinity(d))
				{
					return "the number must be finite.";
				}
			}
			if (typeFromHandle.IsEnum && !typeFromHandle.IsDefined(typeof(FlagsAttribute), inherit: false) && !Enum.IsDefined(typeFromHandle, obj))
			{
				return "'" + Clip(text) + "' is not one of: " + string.Join(", ", Enum.GetNames(typeFromHandle)) + ".";
			}
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)Entry).Description.AcceptableValues;
			if (acceptableValues != null)
			{
				bool flag;
				try
				{
					flag = acceptableValues.IsValid(obj);
				}
				catch (Exception)
				{
					flag = false;
				}
				if (!flag)
				{
					return "'" + Clip(text) + "' is outside what this setting allows (" + AcceptableText(acceptableValues) + ").";
				}
			}
			try
			{
				canonical = TomlTypeConverter.ConvertToString(obj, typeFromHandle);
			}
			catch (Exception)
			{
				return "'" + Clip(text) + "' cannot be written for this setting.";
			}
			return null;
		}

		public string[] Describe()
		{
			string[] array = new string[6]
			{
				typeof(T).Name,
				DefaultText,
				Description,
				"",
				"",
				""
			};
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)Entry).Description.AcceptableValues;
			if (acceptableValues == null)
			{
				return array;
			}
			array[3] = AcceptableText(acceptableValues);
			Type type = ((object)acceptableValues).GetType();
			if (type.IsGenericType && type.GetGenericTypeDefinition().Name.StartsWith("AcceptableValueRange", StringComparison.Ordinal))
			{
				array[4] = PropertyText(acceptableValues, "MinValue");
				array[5] = PropertyText(acceptableValues, "MaxValue");
			}
			return array;
		}

		public string[] Options()
		{
			try
			{
				AcceptableValueBase acceptableValues = ((ConfigEntryBase)Entry).Description.AcceptableValues;
				if (acceptableValues != null)
				{
					Type type = ((object)acceptableValues).GetType();
					if (type.IsGenericType && type.GetGenericTypeDefinition().Name.StartsWith("AcceptableValueList", StringComparison.Ordinal) && type.GetProperty("AcceptableValues", BindingFlags.Instance | BindingFlags.Public)?.GetValue(acceptableValues, null) is Array array)
					{
						List<string> list = new List<string>();
						foreach (object item in array)
						{
							list.Add(TomlTypeConverter.ConvertToString(item, typeof(T)));
						}
						return list.ToArray();
					}
				}
				if (typeof(T).IsEnum && !typeof(T).IsDefined(typeof(FlagsAttribute), inherit: false))
				{
					return Enum.GetNames(typeof(T));
				}
			}
			catch (Exception)
			{
			}
			return new string[0];
		}

		private static string AcceptableText(AcceptableValueBase acceptable)
		{
			string text = acceptable.ToDescriptionString() ?? "";
			text = text.Trim();
			while (text.StartsWith("#"))
			{
				text = text.Substring(1).TrimStart(Array.Empty<char>());
			}
			return text.Replace('\n', ' ').Replace('\r', ' ');
		}

		private static string PropertyText(object target, string name)
		{
			try
			{
				object obj = target.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public)?.GetValue(target, null);
				return (obj == null) ? "" : TomlTypeConverter.ConvertToString(obj, typeof(T));
			}
			catch (Exception)
			{
				return "";
			}
		}

		private static string Clip(string text)
		{
			if (text.Length > 60)
			{
				return text.Substring(0, 60) + "...";
			}
			return text;
		}
	}
	internal enum ValueSource
	{
		ServerDefault,
		World,
		Local
	}
	internal static class ValueResolver
	{
		public static string Effective(string worldOverride, string serverFileValue, out ValueSource source)
		{
			if (worldOverride != null)
			{
				source = ValueSource.World;
				return worldOverride;
			}
			source = ValueSource.ServerDefault;
			return serverFileValue;
		}

		public static ValueSource ClientSource(bool connectedToServer, bool serverHasOverride)
		{
			if (!connectedToServer)
			{
				return ValueSource.Local;
			}
			if (!serverHasOverride)
			{
				return ValueSource.ServerDefault;
			}
			return ValueSource.World;
		}

		public static string Name(ValueSource source)
		{
			return source switch
			{
				ValueSource.World => "world", 
				ValueSource.ServerDefault => "server", 
				_ => "local", 
			};
		}
	}
	internal static class VersionHandshake
	{
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class OnNewConnectionPatch
		{
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				peer.m_rpc.Register<string>(_mod.RpcName("Version"), (Action<ZRpc, string>)RPC_Version);
				if (__instance.IsServer())
				{
					peer.m_rpc.Register<ZPackage>(_mod.RpcName("SetConfig"), (Action<ZRpc, ZPackage>)RPC_SetConfig);
					peer.m_rpc.Invoke(_mod.RpcName("Version"), new object[1] { _mod.Version });
				}
				else
				{
					peer.m_rpc.Register<ZPackage>(_mod.RpcName("Config"), (Action<ZRpc, ZPackage>)RPC_Config);
					peer.m_rpc.Register<ZPackage>(_mod.RpcName("ConfigInfo"), (Action<ZRpc, ZPackage>)RPC_ConfigInfo);
					peer.m_rpc.Register<ZPackage>(_mod.RpcName("SetConfigResult"), (Action<ZRpc, ZPackage>)RPC_SetConfigResult);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static class PeerInfoPatch
		{
			private static bool Prefix(ZNet __instance, ZRpc rpc)
			{
				if (!__instance.IsServer() || Validated.Contains(rpc))
				{
					return true;
				}
				if (_optional && HandshakeRules.Decide(optional: true, validated: false) == JoinOutcome.JoinsWithoutMod)
				{
					Log.Debug("A client " + (ClientVersions.TryGetValue(rpc, out var value) ? ("with " + _mod.Name + " " + value) : ("without " + _mod.Name)) + " joins; it is treated as not having the mod.");
					return true;
				}
				string value2;
				string text = (ClientVersions.TryGetValue(rpc, out value2) ? ("has " + _mod.Name + " " + value2 + ", this server runs " + _mod.Version) : ("does not have " + _mod.Name + " " + _mod.Version));
				string[] obj = new string[5] { "Refusing ", null, null, null, null };
				ISocket socket = rpc.GetSocket();
				obj[1] = ((socket != null) ? socket.GetEndPointString() : null);
				obj[2] = ": the client ";
				obj[3] = text;
				obj[4] = ".";
				Log.Warning(string.Concat(obj));
				rpc.Invoke("Error", new object[1] { 3 });
				return false;
			}

			private static void Postfix(ZNet __instance, ZRpc rpc)
			{
				if (__instance.IsServer() && Validated.Contains(rpc))
				{
					_config.SendTo(rpc);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static class DisconnectPatch
		{
			private static void Prefix(ZNetPeer peer)
			{
				if (peer?.m_rpc != null)
				{
					Validated.Remove(peer.m_rpc);
					ClientVersions.Remove(peer.m_rpc);
					_config?.ForgetPeer(peer.m_rpc);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		private static class WorldStartPatch
		{
			private static void Postfix(ZNet __instance)
			{
				try
				{
					if (_config != null && __instance.IsServer() && ZNet.World != null)
					{
						_config.WorldStarted(ZNet.World.m_name ?? "");
					}
				}
				catch (Exception ex)
				{
					Log.Warning("World start hook failed: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		private static class WorldEndPatch
		{
			private static void Postfix()
			{
				try
				{
					_config?.WorldEnded();
				}
				catch (Exception ex)
				{
					Log.Warning("World end hook failed: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private static class ShutdownPatch
		{
			private static void Postfix()
			{
				Reset();
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static class ConnectErrorPatch
		{
			private static void Postfix(FejdStartup __instance)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Invalid comparison between Unknown and I4
				if (_clientMessage != null)
				{
					if ((int)ZNet.GetConnectionStatus() == 3 && (Object)(object)__instance.m_connectionFailedError != (Object)null)
					{
						TMP_Text connectionFailedError = __instance.m_connectionFailedError;
						connectionFailedError.text = connectionFailedError.text + "\n" + _clientMessage;
					}
					_clientMessage = null;
				}
			}
		}

		private static ModInfo _mod;

		private static SyncedConfig _config;

		private static readonly HashSet<ZRpc> Validated = new HashSet<ZRpc>();

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

		private static bool _serverValidated;

		private static string _clientMessage;

		private static bool _optional;

		public static Type[] PatchClasses => new Type[7]
		{
			typeof(OnNewConnectionPatch),
			typeof(PeerInfoPatch),
			typeof(DisconnectPatch),
			typeof(ShutdownPatch),
			typeof(ConnectErrorPatch),
			typeof(WorldStartPatch),
			typeof(WorldEndPatch)
		};

		public static bool Optional => _optional;

		public static bool SessionActive
		{
			get
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance != (Object)null)
				{
					if (!instance.IsServer())
					{
						return _serverValidated;
					}
					return true;
				}
				return false;
			}
		}

		public static bool ConnectedToValidatedServer
		{
			get
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance != (Object)null && !instance.IsServer())
				{
					return _serverValidated;
				}
				return false;
			}
		}

		public static void Init(ModInfo mod, SyncedConfig config)
		{
			_mod = mod;
			_config = config;
		}

		public static void InitOptional(ModInfo mod, SyncedConfig config)
		{
			_mod = mod;
			_config = config;
			_optional = true;
		}

		public static bool IsValidated(ZRpc rpc)
		{
			return Validated.Contains(rpc);
		}

		private static void RPC_Version(ZRpc rpc, string version)
		{
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				ClientVersions[rpc] = version;
				if (version == _mod.Version)
				{
					Validated.Add(rpc);
				}
				return;
			}
			if (version == _mod.Version)
			{
				_serverValidated = true;
				_clientMessage = null;
			}
			else if (_optional)
			{
				Log.Info(HandshakeRules.ClientMismatchLine(optional: true, _mod.Name, version, _mod.Version));
			}
			else
			{
				_clientMessage = _mod.Name + ": the server runs version " + version + ", you have " + _mod.Version + ".";
				Log.Warning(_clientMessage);
			}
			rpc.Invoke(_mod.RpcName("Version"), new object[1] { _mod.Version });
		}

		private static void RPC_Config(ZRpc rpc, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer())
			{
				_config.Read(pkg);
			}
		}

		private static void RPC_ConfigInfo(ZRpc rpc, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer())
			{
				_config?.ReadInfo(pkg);
			}
		}

		private static void RPC_SetConfig(ZRpc rpc, ZPackage pkg)
		{
			if (!_optional || HandshakeRules.AcceptsSetRequest(optional: true, Validated.Contains(rpc)))
			{
				_config?.HandleSetRequest(rpc, pkg);
			}
		}

		private static void RPC_SetConfigResult(ZRpc rpc, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer())
			{
				_config?.HandleSetResult(pkg);
			}
		}

		private static void Reset()
		{
			Validated.Clear();
			ClientVersions.Clear();
			_serverValidated = false;
			_config?.WorldEnded();
			_config?.UnlockAll();
		}
	}
	internal static class OverrideFormat
	{
		public const string FolderName = "YesuBuildKit.Worlds";

		public const string FileExtension = ".cfg";

		public const int MaxFolderNameLength = 64;

		public const string FallbackFolderName = "_world";

		public const int MaxFileBytes = 262144;

		private static readonly char[] Banned = new char[9] { '/', '\\', ':', '*', '?', '"', '<', '>', '|' };

		private static readonly string[] Reserved = new string[22]
		{
			"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
			"COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
			"LPT8", "LPT9"
		};

		public static string SafeWorldName(string world)
		{
			if (string.IsNullOrWhiteSpace(world))
			{
				return "_world";
			}
			StringBuilder stringBuilder = new StringBuilder(world.Length);
			string text = world.Trim();
			foreach (char c in text)
			{
				if (c < ' ' || c == '\u007f' || Array.IndexOf(Banned, c) >= 0)
				{
					stringBuilder.Append('_');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			string text2 = stringBuilder.ToString().TrimEnd('.', ' ');
			if (text2.Length == 0)
			{
				return "_world";
			}
			if (text2[0] == '.')
			{
				text2 = "_" + text2.TrimStart(new char[1] { '.' });
			}
			if (text2.Length > 64)
			{
				text2 = text2.Substring(0, 64);
				if (char.IsHighSurrogate(text2[text2.Length - 1]))
				{
					text2 = text2.Substring(0, text2.Length - 1);
				}
				text2 = text2.TrimEnd('.', ' ');
				if (text2.Length == 0)
				{
					return "_world";
				}
			}
			string text3 = text2;
			int num = text3.IndexOf('.');
			if (num >= 0)
			{
				text3 = text3.Substring(0, num);
			}
			if (Reserved.Contains<string>(text3.TrimEnd(new char[1] { ' ' }), StringComparer.OrdinalIgnoreCase))
			{
				text2 = "_" + text2;
			}
			return text2;
		}

		public static string RootFolder(string configDir)
		{
			return Path.Combine(configDir, "YesuBuildKit.Worlds");
		}

		public static string WorldFolder(string configDir, string world)
		{
			return Path.Combine(RootFolder(configDir), SafeWorldName(world));
		}

		public static string FilePath(string configDir, string world, string guid)
		{
			return Path.Combine(WorldFolder(configDir, world), guid + ".cfg");
		}

		public static string Format(string guid, string world, IEnumerable<KeyValuePair<string, string>> values)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("# YesuBuildKit settings for one world.\n");
			stringBuilder.Append("# Mod: ").Append(OneLine(guid)).Append('\n');
			stringBuilder.Append("# World: ").Append(OneLine(world)).Append('\n');
			stringBuilder.Append("# One setting per line as Section.Key = value. While this world is loaded these win over the server's config file.\n");
			stringBuilder.Append("# Edit this file while the server runs and it applies within a few seconds. Delete a line to go back to the server default.\n");
			stringBuilder.Append('\n');
			foreach (KeyValuePair<string, string> item in values.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> p) => p.Key, StringComparer.Ordinal))
			{
				stringBuilder.Append(item.Key).Append(" = ").Append(OneLine(item.Value))
					.Append('\n');
			}
			return stringBuilder.ToString();
		}

		public static OverrideParseResult Parse(string text, Func<string, string, string> validate)
		{
			OverrideParseResult overrideParseResult = new OverrideParseResult();
			if (string.IsNullOrEmpty(text))
			{
				return overrideParseResult;
			}
			string[] array = text.Split(new char[1] { '\n' });
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length == 0 || text2[0] == '#' || text2[0] == ';')
				{
					continue;
				}
				int num = text2.IndexOf('=');
				if (num < 0)
				{
					overrideParseResult.Warnings.Add("line " + (i + 1) + ": no '=' in '" + Clip(text2) + "', skipped.");
					continue;
				}
				string text3 = text2.Substring(0, num).Trim();
				string text4 = text2.Substring(num + 1).Trim();
				if (text3.Length == 0)
				{
					overrideParseResult.Warnings.Add("line " + (i + 1) + ": no setting name before '=', skipped.");
					continue;
				}
				string text5 = null;
				try
				{
					text5 = validate?.Invoke(text3, text4);
				}
				catch (Exception ex)
				{
					text5 = ex.Message;
				}
				if (text5 != null)
				{
					overrideParseResult.Warnings.Add("line " + (i + 1) + ": " + Clip(text3) + ": " + text5 + " Skipped.");
					continue;
				}
				if (overrideParseResult.Values.ContainsKey(text3))
				{
					overrideParseResult.Warnings.Add("line " + (i + 1) + ": " + Clip(text3) + " appears twice; the later line wins.");
				}
				overrideParseResult.Values[text3] = text4;
			}
			return overrideParseResult;
		}

		private static string OneLine(string text)
		{
			return (text ?? "").Replace('\r', ' ').Replace('\n', ' ');
		}

		private static string Clip(string text)
		{
			if (text.Length > 60)
			{
				return text.Substring(0, 60) + "...";
			}
			return text;
		}
	}
	internal sealed class OverrideParseResult
	{
		public Dictionary<string, string> Values { get; } = new Dictionary<string, string>(StringComparer.Ordinal);

		public List<string> Warnings { get; } = new List<string>();
	}
	internal sealed class OverrideStore : IDisposable
	{
		private const double Settle = 0.5;

		private const double PollEvery = 2.0;

		private readonly string _guid;

		private readonly string _configDir;

		private readonly Func<string, string, string> _validate;

		private readonly Action<string> _warn;

		private readonly Dictionary<string, string> _values = new Dictionary<string, string>(StringComparer.Ordinal);

		private FileSystemWatcher _watcher;

		private volatile bool _dirty;

		private double _reloadAt = -1.0;

		private double _nextPoll;

		private string _stamp;

		public string WorldName { get; private set; }

		public string FilePath { get; private set; }

		public bool IsLoaded => WorldName != null;

		public int Count => _values.Count;

		public IEnumerable<string> Keys => _values.Keys;

		public OverrideStore(string guid, string configDir, Func<string, string, string> validate, Action<string> warn)
		{
			_guid = guid;
			_configDir = configDir;
			_validate = validate;
			_warn = warn ?? ((Action<string>)delegate
			{
			});
		}

		public bool TryGet(string key, out string text)
		{
			return _values.TryGetValue(key, out text);
		}

		public void Load(string worldName)
		{
			Unload();
			WorldName = worldName ?? "";
			FilePath = OverrideFormat.FilePath(_configDir, WorldName, _guid);
			ReadInto(_values, warnAboutLines: true);
			_stamp = Stamp();
			StartWatching();
		}

		public void Unload()
		{
			StopWatching();
			_values.Clear();
			WorldName = null;
			FilePath = null;
			_dirty = false;
			_reloadAt = -1.0;
			_stamp = null;
		}

		public void Dispose()
		{
			Unload();
		}

		public void MarkDirty()
		{
			_dirty = true;
		}

		public bool Poll(double now)
		{
			if (!IsLoaded)
			{
				return false;
			}
			if (_watcher == null && now >= _nextPoll)
			{
				_nextPoll = now + 2.0;
				if (Stamp() != _stamp)
				{
					_dirty = true;
				}
			}
			if (_dirty)
			{
				_dirty = false;
				_reloadAt = now + 0.5;
			}
			if (_reloadAt < 0.0 || now < _reloadAt)
			{
				return false;
			}
			_reloadAt = -1.0;
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			if (!ReadInto(dictionary, warnAboutLines: true))
			{
				return false;
			}
			_stamp = Stamp();
			if (SameValues(dictionary, _values))
			{
				return false;
			}
			_values.Clear();
			foreach (KeyValuePair<string, string> item in dictionary)
			{
				_values[item.Key] = item.Value;
			}
			return true;
		}

		public bool Set(string key, string text, out string error)
		{
			error = null;
			if (!IsLoaded)
			{
				error = "no world is loaded.";
				return false;
			}
			string value;
			bool flag = _values.TryGetValue(key, out value);
			_values[key] = text ?? "";
			if (Write(out error))
			{
				return true;
			}
			if (flag)
			{
				_values[key] = value;
			}
			else
			{
				_values.Remove(key);
			}
			return false;
		}

		public bool Remove(string key, out string error)
		{
			error = null;
			if (!IsLoaded)
			{
				error = "no world is loaded.";
				return false;
			}
			if (!_values.TryGetValue(key, out var value))
			{
				return true;
			}
			_values.Remove(key);
			if (Write(out error))
			{
				return true;
			}
			_values[key] = value;
			return false;
		}

		private bool Write(out string error)
		{
			error = null;
			string text = FilePath + ".tmp";
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
				File.WriteAllText(text, OverrideFormat.Format(_guid, WorldName, _values), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				if (File.Exists(FilePath))
				{
					File.Replace(text, FilePath, null);
				}
				else
				{
					File.Move(text, FilePath);
				}
				_stamp = Stamp();
				return true;
			}
			catch (Exception ex)
			{
				error = "could not write " + FilePath + ": " + ex.Message;
				try
				{
					if (File.Exists(text))
					{
						File.Delete(text);
					}
				}
				catch (Exception)
				{
				}
				return false;
			}
		}

		private bool ReadInto(Dictionary<string, string> into, bool warnAboutLines)
		{
			try
			{
				FileInfo fileInfo = new FileInfo(FilePath);
				if (!fileInfo.Exists)
				{
					return true;
				}
				if (fileInfo.Length > 262144)
				{
					_warn("Override file " + FilePath + " is bigger than " + 256 + " KB and was not read.");
					return false;
				}
				OverrideParseResult overrideParseResult = OverrideFormat.Parse(File.ReadAllText(FilePath, Encoding.UTF8), _validate);
				if (warnAboutLines)
				{
					foreach (string warning in overrideParseResult.Warnings)
					{
						_warn(Path.GetFileName(FilePath) + " (" + WorldName + "), " + warning);
					}
				}
				foreach (KeyValuePair<string, string> value in overrideParseResult.Values)
				{
					into[value.Key] = value.Value;
				}
				return true;
			}
			catch (Exception ex)
			{
				_warn("Could not read " + FilePath + "; keeping what was loaded. " + ex.Message);
				return false;
			}
		}

		private string Stamp()
		{
			try
			{
				FileInfo fileInfo = new FileInfo(FilePath);
				return fileInfo.Exists ? (fileInfo.LastWriteTimeUtc.Ticks + ":" + fileInfo.Length) : "none";
			}
			catch (Exception)
			{
				return "?";
			}
		}

		private void StartWatching()
		{
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
				_watcher = new FileSystemWatcher(Path.GetDirectoryName(FilePath), Path.GetFileName(FilePath));
				_watcher.Changed += delegate
				{
					_dirty = true;
				};
				_watcher.Created += delegate
				{
					_dirty = true;
				};
				_watcher.Deleted += delegate
				{
					_dirty = true;
				};
				_watcher.Renamed += delegate
				{
					_dirty = true;
				};
				_watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				StopWatching();
				_warn("Cannot watch " + FilePath + "; it is checked every few seconds instead. " + ex.Message);
			}
		}

		private void StopWatching()
		{
			if (_watcher != null)
			{
				try
				{
					_watcher.EnableRaisingEvents = false;
					_watcher.Dispose();
				}
				catch (Exception)
				{
				}
				_watcher = null;
			}
		}

		private static bool SameValues(Dictionary<string, string> a, Dictionary<string, string> b)
		{
			if (a.Count != b.Count)
			{
				return false;
			}
			foreach (KeyValuePair<string, string> item in a)
			{
				if (!b.TryGetValue(item.Key, out var value) || value != item.Value)
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace YesuBuildKit.BountyBoard
{
	internal static class BountyBoardControl
	{
		private static float _nextFault;

		public static bool SessionActive
		{
			get
			{
				if (Plugin.Active)
				{
					return VersionHandshake.SessionActive;
				}
				return false;
			}
		}

		public static int ActiveCount
		{
			get
			{
				if (!ClientView.Enabled)
				{
					return ServerState.Service.Book.Count;
				}
				return ClientView.Mirror.Count;
			}
		}

		public static int CoinsPaidToMe => ClientView.Payouts.TotalCoins;

		public static int PendingRequests => ClientView.Delivery.PendingCount;

		public static string Render(string signText)
		{
			if (!SignText.IsTag(signText))
			{
				return null;
			}
			if (ClientView.Enabled)
			{
				return ClientView.RenderSign(signText);
			}
			if (!Plugin.Active || !Plugin.Cfg.BoardEnabled.Value)
			{
				return null;
			}
			return SignText.Render(signText, ServerState.Service.Book.Views(), ClientView.DisplayName, Plugin.Cfg.MaxCoinsPerBounty.Value);
		}

		public static string Describe(int index)
		{
			IReadOnlyList<BountyView> readOnlyList2;
			if (!ClientView.Enabled)
			{
				IReadOnlyList<BountyView> readOnlyList = ServerState.Service.Book.Views();
				readOnlyList2 = readOnlyList;
			}
			else
			{
				readOnlyList2 = ClientView.Mirror.All;
			}
			IReadOnlyList<BountyView> readOnlyList3 = readOnlyList2;
			if (index < 0 || index >= readOnlyList3.Count)
			{
				return null;
			}
			return SignText.Line(readOnlyList3[index], ClientView.DisplayName, Plugin.Cfg.MaxCoinsPerBounty.Value);
		}

		public static bool ReportKill(string creaturePrefab)
		{
			if (!SessionActive)
			{
				return false;
			}
			return ClientView.ReportKill(creaturePrefab);
		}

		public static bool Deliver(string itemPrefab, int amount)
		{
			if (!SessionActive)
			{
				return false;
			}
			return ClientView.Deliver(itemPrefab, amount);
		}

		public static void Tick(float time)
		{
			try
			{
				ServerState.Tick(time);
			}
			catch (Exception ex)
			{
				Fault("server", ex);
			}
			if (!ClientView.Enabled)
			{
				return;
			}
			try
			{
				ClientView.Tick(time);
			}
			catch (Exception ex2)
			{
				Fault("client", ex2);
			}
		}

		private static void Fault(string what, Exception ex)
		{
			if (!(Time.unscaledTime < _nextFault))
			{
				_nextFault = Time.unscaledTime + 30f;
				Log.Error("Bounty Board " + what + " failed this frame: " + ex);
			}
		}
	}
	internal enum ReserveStatus
	{
		Granted,
		Repeated,
		NoBounty,
		WrongKind,
		Full,
		BadRequest,
		TooMany,
		Used
	}
	internal sealed class ReserveResult
	{
		public ReserveStatus Status;

		public int Accepted;

		public long BountyId;
	}
	internal enum ConfirmStatus
	{
		Applied,
		AppliedLate,
		AlreadyApplied,
		Unknown,
		BadAmount,
		BountyGone
	}
	internal sealed class Completion
	{
		public Bounty Bounty;

		public List<string> Contributors;
	}
	internal sealed class ConfirmResult
	{
		public ConfirmStatus Status;

		public int Applied;

		public Completion Completion;
	}
	internal sealed class KillResult
	{
		public int Advanced;

		public List<Completion> Completions = new List<Completion>();
	}
	internal enum ReservationState
	{
		Active,
		Expired,
		Confirmed,
		Released
	}
	internal sealed class Reservation
	{
		public long Sender;

		public int RequestId;

		public long BountyId;

		public int Amount;

		public double ExpiresAt;

		public ReservationState State;

		public double KeepUntil;
	}
	internal sealed class BountyBook
	{
		private struct Key : IEquatable<Key>
		{
			public readonly long Sender;

			public readonly int RequestId;

			public Key(long sender, int requestId)
			{
				Sender = sender;
				RequestId = requestId;
			}

			public bool Equals(Key other)
			{
				if (Sender == other.Sender)
				{
					return RequestId == other.RequestId;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is Key other)
				{
					return Equals(other);
				}
				return false;
			}

			public override int GetHashCode()
			{
				long sender = Sender;
				return (sender.GetHashCode() * 397) ^ RequestId;
			}
		}

		public const double ReservationSeconds = 20.0;

		public const double LateConfirmGraceSeconds = 600.0;

		public const double FinishedKeepSeconds = 600.0;

		public const double ReleasedKeepSeconds = 60.0;

		public const int MaxPerSender = 3;

		public const int MaxActiveReservations = 64;

		public const int MaxRecords = 512;

		private readonly List<Bounty> _active = new List<Bounty>();

		private readonly Dictionary<Key, Reservation> _reservations = new Dictionary<Key, Reservation>();

		private long _nextBountyId = 1L;

		private long _nextPayoutId = 1L;

		public bool Dirty { get; private set; }

		public bool SyncDirty { get; private set; }

		public int LastDay { get; private set; } = -1;

		public IReadOnlyList<Bounty> Active => _active;

		public int Count => _active.Count;

		public long NextBountyId => _nextBountyId;

		public long NextPayoutId => _nextPayoutId;

		public int ActiveReservations => _reservations.Values.Count((Reservation r) => r.State == ReservationState.Active);

		public int RecordCount => _reservations.Count;

		public void ClearDirty()
		{
			Dirty = false;
		}

		public void ClearSyncDirty()
		{
			SyncDirty = false;
		}

		public void SetLastDay(int day)
		{
			if (day != LastDay)
			{
				LastDay = day;
				Dirty = true;
			}
		}

		public Bounty Get(long id)
		{
			foreach (Bounty item in _active)
			{
				if (item.Id == id)
				{
					return item;
				}
			}
			return null;
		}

		public List<BountyView> Views()
		{
			return _active.Select((Bounty b) => b.ToView()).ToList();
		}

		public long TakePayoutId()
		{
			Dirty = true;
			return _nextPayoutId++;
		}

		public Bounty Add(BountyDraft draft)
		{
			Bounty bounty = new Bounty
			{
				Id = _nextBountyId++,
				Kind = draft.Kind,
				Target = draft.Target,
				Required = draft.Required,
				Progress = 0,
				Coins = draft.Coins
			};
			_active.Add(bounty);
			Touch();
			return bounty;
		}

		private void Touch()
		{
			Dirty = true;
			SyncDirty = true;
		}

		public int ReservedFor(long bountyId)
		{
			int num = 0;
			foreach (Reservation value in _reservations.Values)
			{
				if (value.State == ReservationState.Active && value.BountyId == bountyId)
				{
					num += value.Amount;
				}
			}
			return num;
		}

		public void Expire(double now)
		{
			List<Key> list = null;
			foreach (KeyValuePair<Key, Reservation> reservation in _reservations)
			{
				Reservation value = reservation.Value;
				if (value.State == ReservationState.Active && now >= value.ExpiresAt)
				{
					value.State = ReservationState.Expired;
					value.KeepUntil = value.ExpiresAt + 600.0;
				}
				if (value.State != ReservationState.Active && now >= value.KeepUntil)
				{
					if (list == null)
					{
						list = new List<Key>();
					}
					list.Add(reservation.Key);
				}
			}
			if (list != null)
			{
				foreach (Key item in list)
				{
					_reservations.Remove(item);
				}
			}
			if (_reservations.Count <= 512)
			{
				return;
			}
			foreach (Key item2 in (from p in (from p in _reservations
					where p.Value.State != ReservationState.Active
					orderby p.Value.KeepUntil
					select p).Take(_reservations.Count - 512)
				select p.Key).ToList())
			{
				_reservations.Remove(item2);
			}
		}

		public ReserveResult TryReserve(long sender, int requestId, long bountyId, int offered, double now)
		{
			Expire(now);
			Key key = new Key(sender, requestId);
			if (offered < 1 || offered > 1000)
			{
				return new ReserveResult
				{
					Status = ReserveStatus.BadRequest,
					BountyId = bountyId
				};
			}
			if (_reservations.TryGetValue(key, out var value))
			{
				if (value.State == ReservationState.Active && value.BountyId == bountyId)
				{
					return new ReserveResult
					{
						Status = ReserveStatus.Repeated,
						Accepted = value.Amount,
						BountyId = bountyId
					};
				}
				return new ReserveResult
				{
					Status = ReserveStatus.Used,
					BountyId = bountyId
				};
			}
			Bounty bounty = Get(bountyId);
			if (bounty == null)
			{
				return new ReserveResult
				{
					Status = ReserveStatus.NoBounty,
					BountyId = bountyId
				};
			}
			if (bounty.Kind != BountyKind.Deliver)
			{
				return new ReserveResult
				{
					Status = ReserveStatus.WrongKind,
					BountyId = bountyId
				};
			}
			int num = 0;
			int num2 = 0;
			foreach (Reservation value2 in _reservations.Values)
			{
				if (value2.State == ReservationState.Active)
				{
					num2++;
					if (value2.Sender == sender)
					{
						num++;
					}
				}
			}
			if (num >= 3 || num2 >= 64)
			{
				return new ReserveResult
				{
					Status = ReserveStatus.TooMany,
					BountyId = bountyId
				};
			}
			int num3 = bounty.Remaining - ReservedFor(bountyId);
			if (num3 <= 0)
			{
				return new ReserveResult
				{
					Status = ReserveStatus.Full,
					BountyId = bountyId
				};
			}
			int num4 = Math.Min(offered, num3);
			_reservations[key] = new Reservation
			{
				Sender = sender,
				RequestId = requestId,
				BountyId = bountyId,
				Amount = num4,
				ExpiresAt = now + 20.0,
				State = ReservationState.Active
			};
			return new ReserveResult
			{
				Status = ReserveStatus.Granted,
				Accepted = num4,
				BountyId = bountyId
			};
		}

		public ConfirmResult Confirm(long sender, int requestId, int amount, string senderName, double now)
		{
			Expire(now);
			if (!_reservations.TryGetValue(new Key(sender, requestId), out var value))
			{
				return new ConfirmResult
				{
					Status = ConfirmStatus.Unknown
				};
			}
			switch (value.State)
			{
			case ReservationState.Confirmed:
				return new ConfirmResult
				{
					Status = ConfirmStatus.AlreadyApplied
				};
			case ReservationState.Released:
				return new ConfirmResult
				{
					Status = ConfirmStatus.Unknown
				};
			default:
			{
				if (amount != value.Amount)
				{
					return new ConfirmResult
					{
						Status = ConfirmStatus.BadAmount
					};
				}
				bool flag = value.State == ReservationState.Expired;
				Bounty bounty = Get(value.BountyId);
				value.State = ReservationState.Confirmed;
				value.KeepUntil = now + 600.0;
				if (bounty == null)
				{
					return new ConfirmResult
					{
						Status = ConfirmStatus.BountyGone
					};
				}
				int val = (flag ? (bounty.Remaining - ReservedFor(bounty.Id)) : bounty.Remaining);
				int num = Math.Min(value.Amount, val);
				if (num <= 0)
				{
					return new ConfirmResult
					{
						Status = ConfirmStatus.BountyGone
					};
				}
				bounty.Progress += num;
				bounty.AddContributor(senderName);
				Touch();
				ConfirmResult confirmResult = new ConfirmResult
				{
					Status = (flag ? ConfirmStatus.AppliedLate : ConfirmStatus.Applied),
					Applied = num
				};
				if (bounty.Progress >= bounty.Required)
				{
					confirmResult.Completion = Complete(bounty);
				}
				return confirmResult;
			}
			}
		}

		public bool Release(long sender, int requestId, double now)
		{
			Expire(now);
			if (!_reservations.TryGetValue(new Key(sender, requestId), out var value) || value.State != ReservationState.Active)
			{
				return false;
			}
			value.State = ReservationState.Released;
			value.KeepUntil = now + 60.0;
			return true;
		}

		public KillResult AddKill(string creature, IEnumerable<string> contributors)
		{
			KillResult killResult = new KillResult();
			List<string> list = ((contributors == null) ? new List<string>() : contributors.ToList());
			foreach (Bounty item in _active.ToList())
			{
				if (item.Kind != BountyKind.Kill || !BountyRules.SameTarget(item.Target, creature) || item.Remaining <= 0)
				{
					continue;
				}
				item.Progress++;
				foreach (string item2 in list)
				{
					item.AddContributor(item2);
				}
				killResult.Advanced++;
				Touch();
				if (item.Progress >= item.Required)
				{
					killResult.Completions.Add(Complete(item));
				}
			}
			return killResult;
		}

		private Completion Complete(Bounty bounty)
		{
			_active.Remove(bounty);
			Touch();
			Bounty bounty2 = bounty.Copy();
			return new Completion
			{
				Bounty = bounty2,
				Contributors = new List<string>(bounty2.Contributors)
			};
		}

		public int RemoveUnreserved(double now)
		{
			Expire(now);
			List<Bounty> list = _active.Where((Bounty b) => ReservedFor(b.Id) == 0).ToList();
			foreach (Bounty item in list)
			{
				_active.Remove(item);
			}
			if (list.Count > 0)
			{
				Touch();
			}
			return list.Count;
		}

		public int TrimTo(int max, double now)
		{
			Expire(now);
			int num = 0;
			int num2 = _active.Count - 1;
			while (num2 >= 0 && _active.Count > max)
			{
				if (ReservedFor(_active[num2].Id) == 0)
				{
					_active.RemoveAt(num2);
					num++;
				}
				num2--;
			}
			if (num > 0)
			{
				Touch();
			}
			return num;
		}

		public int Restore(IEnumerable<Bounty> bounties, long nextBountyId, long nextPayoutId, int lastDay)
		{
			_active.Clear();
			_reservations.Clear();
			int num = 0;
			long num2 = 0L;
			foreach (Bounty bounty2 in bounties)
			{
				if (bounty2 == null || bounty2.Id <= 0 || Get(bounty2.Id) != null || _active.Count >= 16 || !BountyRules.ValidTarget(bounty2.Target) || bounty2.Required < 1 || bounty2.Required > 1000 || bounty2.Progress < 0 || bounty2.Progress >= bounty2.Required || bounty2.Coins < 1 || bounty2.Coins > 10000 || !Enum.IsDefined(typeof(BountyKind), bounty2.Kind))
				{
					num++;
					continue;
				}
				Bounty bounty = bounty2.Copy();
				bounty.Contributors = new List<string>();
				foreach (string contributor in bounty2.Contributors)
				{
					bounty.AddContributor(contributor);
				}
				_active.Add(bounty);
				if (bounty.Id > num2)
				{
					num2 = bounty.Id;
				}
			}
			_nextBountyId = Math.Max(Math.Max(nextBountyId, num2 + 1), 1L);
			_nextPayoutId = Math.Max(nextPayoutId, 1L);
			LastDay = ((lastDay < -1) ? (-1) : lastDay);
			Dirty = false;
			SyncDirty = true;
			return num;
		}
	}
	internal sealed class BountyMirror
	{
		private List<BountyView> _views = new List<BountyView>();

		public int Version { get; private set; }

		public int Count => _views.Count;

		public IReadOnlyList<BountyView> All => _views;

		public BountyView Get(long id)
		{
			return _views.FirstOrDefault((BountyView v) => v.Id == id);
		}

		public void Clear()
		{
			_views = new List<BountyView>();
			Version++;
		}

		public void Apply(IEnumerable<BountyView> views)
		{
			List<BountyView> list = views.ToList();
			bool flag = list.Count == _views.Count;
			int num = 0;
			while (flag && num < list.Count)
			{
				flag = list[num].Same(_views[num]);
				num++;
			}
			if (!flag)
			{
				_views = list;
				Version++;
			}
		}
	}
	internal sealed class BountyFileContents
	{
		public long NextBountyId;

		public long NextPayoutId;

		public int LastDay;

		public List<Bounty> Bounties = new List<Bounty>();
	}
	internal enum LoadStatus
	{
		Missing,
		Ok,
		Corrupt
	}
	internal sealed class LoadResult
	{
		public LoadStatus Status;

		public BountyFileContents Contents;

		public string Error;

		public string MovedTo;
	}
	internal static class BountyFile
	{
		public const string HeaderWord = "YesuBuildKit.BountyBoard";

		public const int Version = 1;

		public const string Extension = ".bounties";

		public const int MaxFileChars = 262144;

		public static string Serialize(IEnumerable<Bounty> bounties, long nextBountyId, long nextPayoutId, int lastDay)
		{
			List<Bounty> list = bounties.ToList();
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("YesuBuildKit.BountyBoard").Append(' ').Append(1.ToString(CultureInfo.InvariantCulture))
				.Append('\n');
			stringBuilder.Append("next\t").Append(nextBountyId.ToString(CultureInfo.InvariantCulture)).Append('\t')
				.Append(nextPayoutId.ToString(CultureInfo.InvariantCulture))
				.Append('\t')
				.Append(lastDay.ToString(CultureInfo.InvariantCulture))
				.Append('\n');
			foreach (Bounty item in list)
			{
				StringBuilder stringBuilder2 = stringBuilder.Append("bounty\t").Append(item.Id.ToString(CultureInfo.InvariantCulture)).Append('\t');
				int kind = (int)item.Kind;
				stringBuilder2.Append(kind.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(Escape(item.Target))
					.Append('\t')
					.Append(item.Required.ToString(CultureInfo.InvariantCulture))
					.Append('\t')
					.Append(item.Progress.ToString(CultureInfo.InvariantCulture))
					.Append('\t')
					.Append(item.Coins.ToString(CultureInfo.InvariantCulture))
					.Append('\n');
				foreach (string contributor in item.Contributors)
				{
					stringBuilder.Append("who\t").Append(Escape(contributor)).Append('\n');
				}
			}
			stringBuilder.Append("end ").Append(list.Count.ToString(CultureInfo.InvariantCulture)).Append('\n');
			return stringBuilder.ToString();
		}

		public static bool TryParse(string text, out BountyFileContents contents, out string error)
		{
			contents = null;
			if (text == null)
			{
				return Fail("No text.", out error);
			}
			if (text.Length > 262144)
			{
				return Fail("The file is larger than " + 262144 + " characters.", out error);
			}
			string[] array = text.Split(new char[1] { '\n' });
			if (array.Length < 4 || array[^1].Length != 0)
			{
				return Fail("The file is incomplete.", out error);
			}
			int num = array.Length - 2;
			if (array[0] != "YesuBuildKit.BountyBoard " + 1.ToString(CultureInfo.InvariantCulture))
			{
				return Fail("Line 1 is not the version " + 1 + " header.", out error);
			}
			string[] array2 = array[1].Split(new char[1] { '\t' });
			if (array2.Length != 4 || array2[0] != "next" || !TryLong(array2[1], out var value) || value < 1 || !TryLong(array2[2], out var value2) || value2 < 1 || !int.TryParse(array2[3], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result) || result < -1)
			{
				return Fail("Line 2 is not 'next <bounty id> <payout id> <day>'.", out error);
			}
			if (!array[num].StartsWith("end ", StringComparison.Ordinal) || !int.TryParse(array[num].Substring(4), NumberStyles.None, CultureInfo.InvariantCulture, out var result2))
			{
				return Fail("The closing 'end <count>' line is missing.", out error);
			}
			if (result2 > 16)
			{
				return Fail("More than " + 16 + " bounties.", out error);
			}
			BountyFileContents bountyFileContents = new BountyFileContents
			{
				NextBountyId = value,
				NextPayoutId = value2,
				LastDay = result
			};
			HashSet<long> hashSet = new HashSet<long>();
			Bounty bounty = null;
			for (int i = 2; i < num; i++)
			{
				int num2 = i + 1;
				string[] array3 = array[i].Split(new char[1] { '\t' });
				if (array3[0] == "who")
				{
					if (bounty == null || array3.Length != 2)
					{
						return Fail("Line " + num2 + ": a 'who' line must follow a bounty and have one field.", out error);
					}
					if (!TryUnescape(array3[1], out var value3) || value3.Length == 0 || value3 != BountyRules.CleanPlayerName(value3))
					{
						return Fail("Line " + num2 + ": bad contributor name.", out error);
					}
					if (bounty.Contributors.Count >= 32 || bounty.Contributors.Contains(value3))
					{
						return Fail("Line " + num2 + ": too many or repeated contributors.", out error);
					}
					bounty.Contributors.Add(value3);
					continue;
				}
				if (array3[0] != "bounty" || array3.Length != 7)
				{
					return Fail("Line " + num2 + " is not a bounty line with 7 fields.", out error);
				}
				if (!TryLong(array3[1], out var value4) || value4 < 1 || value4 >= value)
				{
					return Fail("Line " + num2 + ": bad id.", out error);
				}
				if (!hashSet.Add(value4))
				{
					return Fail("Line " + num2 + ": duplicate id " + value4 + ".", out error);
				}
				if (array3[2] != "0" && array3[2] != "1")
				{
					return Fail("Line " + num2 + ": kind must be 0 or 1.", out error);
				}
				if (!TryUnescape(array3[3], out var value5) || !BountyRules.ValidTarget(value5))
				{
					return Fail("Line " + num2 + ": bad target.", out error);
				}
				if (!TryInt(array3[4], out var value6) || value6 < 1 || value6 > 1000)
				{
					return Fail("Line " + num2 + ": bad required count.", out error);
				}
				if (!TryInt(array3[5], out var value7) || value7 >= value6)
				{
					return Fail("Line " + num2 + ": bad progress.", out error);
				}
				if (!TryInt(array3[6], out var value8) || value8 < 1 || value8 > 10000)
				{
					return Fail("Line " + num2 + ": bad coins.", out error);
				}
				bounty = new Bounty
				{
					Id = value4,
					Kind = ((!(array3[2] == "0")) ? BountyKind.Deliver : BountyKind.Kill),
					Target = value5,
					Required = value6,
					Progress = value7,
					Coins = value8
				};
				bountyFileContents.Bounties.Add(bounty);
			}
			if (result2 != bountyFileContents.Bounties.Count)
			{
				return Fail("The closing count " + result2 + " does not match the " + bountyFileContents.Bounties.Count + " bounties.", out error);
			}
			contents = bountyFileContents;
			error = null;
			return true;
		}

		private static bool Fail(string message, out string error)
		{
			error = message;
			return false;
		}

		private static bool TryLong(string text, out long value)
		{
			return long.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value);
		}

		private static bool TryInt(string text, out int value)
		{
			return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value);
		}

		internal static string Escape(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			foreach (char c in text)
			{
				switch (c)
				{
				case '\\':
					stringBuilder.Append("\\\\");
					break;
				case '\t':
					stringBuilder.Append("\\t");
					break;
				case '\n':
					stringBuilder.Append("\\n");
					break;
				case '\r':
					stringBuilder.Append("\\r");
					break;
				default:
					stringBuilder.Append(c);
					break;
				}
			}
			return stringBuilder.ToString();
		}

		internal static bool TryUnescape(string text, out string value)
		{
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			for (int i = 0; i < text.Length; i++)
			{
				char c = text[i];
				if (c != '\\')
				{
					stringBuilder.Append(c);
					continue;
				}
				if (++i >= text.Length)
				{
					value = null;
					return false;
				}
				switch (text[i])
				{
				case '\\':
					stringBuilder.Append('\\');
					break;
				case 't':
					stringBuilder.Append('\t');
					break;
				case 'n':
					stringBuilder.Append('\n');
					break;
				case 'r':
					stringBuilder.Append('\r');
					break;
				default:
					value = null;
					return false;
				}
			}
			value = stringBuilder.ToString();
			return true;
		}
	}
	internal static class BountyFileStorage
	{
		public const int MaxWorldFileNameChars = 64;

		private static readonly string[] Reserved = new string[22]
		{
			"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
			"COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
			"LPT8", "LPT9"
		};

		public static string PathFor(string directory, string worldName)
		{
			string text = worldName ?? "";
			StringBuilder stringBuilder = new StringBuilder();
			string text2 = text;
			foreach (char c in text2)
			{
				if (stringBuilder.Length >= 64)
				{
					break;
				}
				stringBuilder.Append((char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == ' ') ? c : '_');
			}
			string text3 = stringBuilder.ToString().Trim();
			bool num = text3 != text || text3.Length == 0 || Array.IndexOf(Reserved, text3.ToUpperInvariant()) >= 0;
			if (text3.Length == 0)
			{
				text3 = "world";
			}
			if (num)
			{
				text3 = text3 + "-" + Hash(text);
			}
			return Path.Combine(directory, text3 + ".bounties");
		}

		private static string Hash(string text)
		{
			uint num = 2166136261u;
			foreach (char c in text)
			{
				num ^= c;
				num *= 16777619;
			}
			return num.ToString("x8", CultureInfo.InvariantCulture);
		}

		public static LoadResult Load(string path, string stamp)
		{
			try
			{
				if (!File.Exists(path))
				{
					return new LoadResult
					{
						Status = LoadStatus.Missing
					};
				}
				string text = null;
				string error = null;
				if (new FileInfo(path).Length > 1048576)
				{
					error = "The file is far larger than any bounty list.";
				}
				else
				{
					text = File.ReadAllText(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				}
				if (error == null && BountyFile.TryParse(text, out var contents, out error))
				{
					return new LoadResult
					{
						Status = LoadStatus.Ok,
						Contents = contents
					};
				}
				string text2 = path + ".bad-" + stamp;
				try
				{
					File.Move(path, text2);
				}
				catch (Exception ex)
				{
					return new LoadResult
					{
						Status = LoadStatus.Corrupt,
						Error = error + " (could not move it aside: " + ex.Message + ")"
					};
				}
				return new LoadResult
				{
					Status = LoadStatus.Corrupt,
					Error = error,
					MovedTo = text2
				};
			}
			catch (Exception ex2)
			{
				return new LoadResult
				{
					Status = LoadStatus.Corrupt,
					Error = ex2.Message
				};
			}
		}

		public static string Save(string path, string text)
		{
			string text2 = path + ".tmp";
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(path));
				File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				if (File.Exists(path))
				{
					File.Replace(text2, path, null);
				}
				else
				{
					File.Move(text2, path);
				}
				return null;
			}
			catch (Exception ex)
			{
				try
				{
					if (File.Exists(text2))
					{
						File.Delete(text2);
					}
				}
				catch (Exception)
				{
				}
				return ex.Message;
			}
		}
	}
	internal sealed class BountyDraft
	{
		public BountyKind Kind;

		public string Target;

		public int Required;

		public int Coins;
	}
	internal static class BountyGenerator
	{
		public static int ScaleCoins(PoolEntry entry, int count, int maxCoins)
		{
			int num = (int)Math.Round((double)entry.Coins * (double)count / (double)entry.Max, MidpointRounding.AwayFromZero);
			if (num < 1)
			{
				num = 1;
			}
			int num2 = BountyRules.ClampMaxCoins(maxCoins);
			if (num <= num2)
			{
				return num;
			}
			return num2;
		}

		public static BountyDraft Generate(Random rng, IReadOnlyList<PoolEntry> kills, IReadOnlyList<PoolEntry> delivers, IReadOnlyCollection<Bounty> existing, int maxCoins)
		{
			if (rng == null)
			{
				throw new ArgumentNullException("rng");
			}
			existing = existing ?? new List<Bounty>();
			List<PoolEntry> list = Fresh(kills, BountyKind.Kill, existing);
			List<PoolEntry> list2 = Fresh(delivers, BountyKind.Deliver, existing);
			if (list.Count == 0 && list2.Count == 0)
			{
				return null;
			}
			BountyKind bountyKind;
			if (list.Count == 0)
			{
				bountyKind = BountyKind.Deliver;
			}
			else if (list2.Count == 0)
			{
				bountyKind = BountyKind.Kill;
			}
			else
			{
				int num = 0;
				int num2 = 0;
				foreach (Bounty item in existing)
				{
					if (item.Kind == BountyKind.Kill)
					{
						num++;
					}
					else
					{
						num2++;
					}
				}
				bountyKind = ((num >= num2) ? ((num2 < num) ? BountyKind.Deliver : ((rng.Next(2) != 0) ? BountyKind.Deliver : BountyKind.Kill)) : BountyKind.Kill);
			}
			List<PoolEntry> list3 = ((bountyKind == BountyKind.Kill) ? list : list2);
			PoolEntry poolEntry = list3[rng.Next(list3.Count)];
			int num3 = ((poolEntry.Min == poolEntry.Max) ? poolEntry.Min : rng.Next(poolEntry.Min, poolEntry.Max + 1));
			return new BountyDraft
			{
				Kind = bountyKind,
				Target = poolEntry.Name,
				Required = num3,
				Coins = ScaleCoins(poolEntry, num3, maxCoins)
			};
		}

		private static List<PoolEntry> Fresh(IReadOnlyList<PoolEntry> pool, BountyKind kind, IReadOnlyCollection<Bounty> existing)
		{
			List<PoolEntry> list = new List<PoolEntry>();
			if (pool == null)
			{
				return list;
			}
			foreach (PoolEntry item in pool)
			{
				bool flag = false;
				foreach (Bounty item2 in existing)
				{
					if (item2.Kind == kind && BountyRules.SameTarget(item2.Target, item.Name))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					list.Add(item);
				}
			}
			return list;
		}
	}
	internal static class DailyRotation
	{
		public const long DefaultDayLengthSeconds = 1200L;

		public static int DayOf(double worldSeconds, long dayLengthSeconds)
		{
			if (dayLengthSeconds < 1)
			{
				dayLengthSeconds = 1200L;
			}
			if (double.IsNaN(worldSeconds) || double.IsInfinity(worldSeconds) || worldSeconds < 0.0)
			{
				return 0;
			}
			double num = worldSeconds / (double)dayLengthSeconds;
			if (!(num >= 2147483647.0))
			{
				return (int)num;
			}
			return int.MaxValue;
		}

		public static bool ShouldRotate(int lastDay, int currentDay, bool enabled)
		{
			if (enabled && lastDay >= 0)
			{
				return currentDay > lastDay;
			}
			return false;
		}
	}
	internal enum BountyKind : byte
	{
		Kill,
		Deliver
	}
	internal enum RewardShare
	{
		Everyone,
		Contributors
	}
	internal static class BountyRules
	{
		public const int MinActive = 1;

		public const int MaxActive = 5;

		public const int DefaultActive = 3;

		public const int DefaultMaxCoins = 500;

		public const int HardMaxCoins = 10000;

		public const int HardMaxCount = 1000;

		public const int MaxTargetChars = 64;

		public const int MaxPlayerNameChars = 40;

		public const int MaxContributors = 32;

		public const int MaxPoolEntries = 64;

		public const int MaxPoolTextChars = 4096;

		public const int MaxDeliverAmount = 1000;

		public const int MaxStored = 16;

		public static int ClampActive(int value)
		{
			if (value >= 1)
			{
				if (value <= 5)
				{
					return value;
				}
				return 5;
			}
			return 1;
		}

		public static int ClampMaxCoins(int value)
		{
			if (value >= 1)
			{
				if (value <= 10000)
				{
					return value;
				}
				return 10000;
			}
			return 1;
		}

		public static bool ValidTarget(string name)
		{
			if (string.IsNullOrEmpty(name) || name.Length > 64)
			{
				return false;
			}
			foreach (char c in name)
			{
				if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_' && c != '-')
				{
					return false;
				}
			}
			return true;
		}

		public static bool SameTarget(string a, string b)
		{
			return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
		}

		public static string CleanPlayerName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder(Math.Min(name.Length, 42));
			for (int i = 0; i < name.Length; i++)
			{
				char c = name[i];
				if (char.IsHighSurrogate(c) && i + 1 < name.Length && char.IsLowSurrogate(name[i + 1]))
				{
					stringBuilder.Append(c).Append(name[i + 1]);
					i++;
				}
				else if (char.IsSurrogate(c) || char.IsControl(c))
				{
					stringBuilder.Append(' ');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			string text = stringBuilder.ToString().Trim();
			if (text.Length > 40)
			{
				text = text.Substring(0, 40);
				if (char.IsHighSurrogate(text[text.Length - 1]))
				{
					text = text.Substring(0, text.Length - 1);
				}
				text = text.TrimEnd(Array.Empty<char>());
			}
			return text;
		}
	}
	internal sealed c