Decompiled source of OffWithTheirNuts v1.0.0

OffWithTheirNuts/OffWithTheirNuts.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Off With Their Nuts!")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace OffWithTheirNuts;

internal sealed class AnimalHoverText
{
	private string lastHoverText;

	private string lastFormattedHoverText;

	private TextResources lastTextResources;

	private bool lastIsSterile;

	private bool lastIsIrreversibleSterilizationEnabled;

	private string lastShortcutLabel;

	private string sterileStatusLine;

	private string shortcutLine;

	internal string WithSterilityInfo(string hoverText, TextResources textResources, bool isSterile, bool isIrreversibleSterilizationEnabled, string shortcutLabel)
	{
		if (lastTextResources != textResources || lastIsSterile != isSterile || lastIsIrreversibleSterilizationEnabled != isIrreversibleSterilizationEnabled || lastShortcutLabel != shortcutLabel)
		{
			lastTextResources = textResources;
			lastIsSterile = isSterile;
			lastIsIrreversibleSterilizationEnabled = isIrreversibleSterilizationEnabled;
			lastShortcutLabel = shortcutLabel;
			lastHoverText = null;
			sterileStatusLine = (isSterile ? ("\n<color=#FFC6A8>" + textResources.SterileStatus + "</color>") : "");
			shortcutLine = FormatShortcutLine(textResources, isSterile, isIrreversibleSterilizationEnabled, shortcutLabel);
		}
		if (hoverText != lastHoverText)
		{
			string text = (isSterile ? WithSterileStatus(hoverText) : hoverText);
			lastFormattedHoverText = text + shortcutLine;
			lastHoverText = hoverText;
		}
		return lastFormattedHoverText;
	}

	private string WithSterileStatus(string hoverText)
	{
		int num = hoverText.IndexOf("\n[", StringComparison.Ordinal);
		if (num >= 0)
		{
			return hoverText.Insert(num, sterileStatusLine);
		}
		return hoverText + sterileStatusLine;
	}

	private static string FormatShortcutLine(TextResources textResources, bool isSterile, bool isIrreversibleSterilizationEnabled, string shortcutLabel)
	{
		if (shortcutLabel == null || (isSterile && isIrreversibleSterilizationEnabled))
		{
			return "";
		}
		string text = (isSterile ? textResources.RestoreFertilityHint : ((!isIrreversibleSterilizationEnabled) ? textResources.SterilizeHint : textResources.IrreversibleSterilizationHint));
		string text2 = text;
		return "\n[<color=yellow><b>" + shortcutLabel + "</b></color>] " + text2;
	}
}
[BepInPlugin("rehallowed.OffWithTheirNuts", "Off With Their Nuts!", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
public sealed class OffWithTheirNutsPlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Tameable), "GetHoverText")]
	private static class HoverTextPatch
	{
		private static void Postfix(Tameable __instance, ref string __result, ZNetView ___m_nview)
		{
			OffWithTheirNutsPlugin instance = OffWithTheirNutsPlugin.instance;
			if (!((Object)(object)instance == (Object)null) && instance.RestrictionsActive && !string.IsNullOrEmpty(__result) && !((Object)(object)___m_nview == (Object)null))
			{
				bool flag = ZdoSterilityOperations.IsSterile(___m_nview.GetZDO());
				string shortcutLabel = instance.hotkey.ShortcutLabel;
				bool flag2 = shortcutLabel != null && ___m_nview.IsValid() && IsSterilizable(__instance);
				if (flag || flag2)
				{
					__result = instance.animalHoverText.WithSterilityInfo(__result, instance.uiLanguage.TextResources, flag, instance.serverSync.IsIrreversibleSterilizationEnabled, flag2 ? shortcutLabel : null);
				}
			}
		}
	}

	[HarmonyPatch(typeof(Procreation), "Procreate")]
	private static class ProcreatePatch
	{
		private static bool Prefix(ZNetView ___m_nview)
		{
			ServerSync serverSync = instance?.serverSync;
			if (serverSync == null || !serverSync.HasWorld)
			{
				return true;
			}
			if (!serverSync.SettingsReady)
			{
				return false;
			}
			if (!serverSync.RestrictionsEnabled)
			{
				return true;
			}
			ZDO val = ((___m_nview != null) ? ___m_nview.GetZDO() : null);
			if (!ZdoSterilityOperations.IsSterile(val))
			{
				return true;
			}
			if (val.IsOwner())
			{
				ZdoSterilityOperations.ClearPregnancy(val);
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(Procreation), "ReadyForProcreation")]
	private static class ReadyForProcreationPatch
	{
		private static bool Prefix(ref bool __result, ZNetView ___m_nview)
		{
			ServerSync serverSync = instance?.serverSync;
			if (serverSync == null || !serverSync.HasWorld)
			{
				return true;
			}
			if (serverSync.SettingsReady && (!serverSync.RestrictionsEnabled || !ZdoSterilityOperations.IsSterile((___m_nview != null) ? ___m_nview.GetZDO() : null)))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}

	private readonly HashSet<ZDOID> individualChanges = new HashSet<ZDOID>();

	private const string KeySectionModActivation = "keySectionModActivation";

	private const string KeyEnableMod = "keyEnableMod";

	private const int OrderEnableMod = 0;

	private const string KeySectionPersonalSettings = "keySectionPersonalSettings";

	private const string KeySterilizationShortcut = "keySterilizationShortcut";

	private const int OrderToggleSterilization = 1;

	private const string KeySterilizationEffects = "keySterilizationEffects";

	private const int OrderSterilizationEffects = 0;

	private const string KeySectionWorldAdministration = "keySectionWorldAdministration";

	private const string KeyIrreversibleSterilization = "keyIrreversibleSterilization";

	private const int OrderIrreversibleSterilization = 2;

	private const string KeyResetRestrictions = "keyResetRestrictions";

	private const int OrderResetRestrictions = 1;

	private const string KeyRemoveModData = "keyRemoveModData";

	private const int OrderRemoveModData = 0;

	private readonly ConfigurationManagerAttributes enabledAttributes = new ConfigurationManagerAttributes();

	private readonly ConfigurationManagerAttributes irreversibleSterilizationAttributes = new ConfigurationManagerAttributes();

	private readonly ConfigurationManagerAttributes shortcutAttributes = new ConfigurationManagerAttributes();

	private readonly ConfigurationManagerAttributes effectsAttributes = new ConfigurationManagerAttributes();

	private readonly ConfigurationManagerAttributes resetAttributes = new ConfigurationManagerAttributes();

	private readonly ConfigurationManagerAttributes cleanupAttributes = new ConfigurationManagerAttributes();

	private ConfigEntry<bool> enabledSetting;

	private ConfigEntry<bool> irreversibleSterilizationSetting;

	private ConfigEntry<KeyboardShortcut> shortcutSetting;

	private ConfigEntry<bool> effectsSetting;

	private static OffWithTheirNutsPlugin instance;

	private readonly AnimalHoverText animalHoverText = new AnimalHoverText();

	private Harmony harmony;

	private ServerSync serverSync;

	private SterilizationHotkey hotkey;

	private GameUiLanguage uiLanguage;

	private FieldRef<ZDOMan, Dictionary<ZDOID, ZDO>> worldObjects;

	private bool resetting;

	internal static ServerSync ActiveServerSync
	{
		get
		{
			if (!((Object)(object)instance == (Object)null))
			{
				return instance.serverSync;
			}
			return null;
		}
	}

	internal static GameUiLanguage ActiveUiLanguage
	{
		get
		{
			if (!((Object)(object)instance == (Object)null))
			{
				return instance.uiLanguage;
			}
			return null;
		}
	}

	private bool RestrictionsActive => serverSync?.RestrictionsActive ?? false;

	private void ToggleTarget(Character target)
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		ZNet currentNetwork = serverSync.CurrentNetwork;
		if ((Object)(object)currentNetwork == (Object)null)
		{
			return;
		}
		ZNetView component = ((Component)target).GetComponent<ZNetView>();
		if (!((Object)(object)component == (Object)null) && component.IsValid() && IsSterilizable(((Component)target).GetComponent<Tameable>()))
		{
			ZDO zDO = component.GetZDO();
			bool flag = !ZdoSterilityOperations.IsSterile(zDO);
			if (currentNetwork.IsServer())
			{
				StartChange(null, zDO.m_uid, flag);
			}
			else
			{
				serverSync.RequestChange(zDO.m_uid, flag);
			}
		}
	}

	private void StartChange(ZNetPeer requester, ZDOID id, bool requestedState)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		if (!RestrictionsActive)
		{
			return;
		}
		if (resetting || individualChanges.Contains(id))
		{
			serverSync.Notify(requester, PlayerNoticeKind.ChangePending);
			return;
		}
		ZDOMan obj = ZDOMan.instance;
		ZDO val = ((obj != null) ? obj.GetZDO(id) : null);
		if (val == null || !IsSterilityChangeAllowed(requester, val))
		{
			serverSync.Notify(requester, PlayerNoticeKind.TargetUnavailable);
			return;
		}
		if (ZdoSterilityOperations.IsSterile(val) == requestedState)
		{
			serverSync.Notify(requester, requestedState ? PlayerNoticeKind.AlreadySterile : PlayerNoticeKind.AlreadyFertile);
			return;
		}
		if (!requestedState && serverSync.IsIrreversibleSterilizationEnabled)
		{
			serverSync.Notify(requester, PlayerNoticeKind.FertilityRestorationBlocked);
			return;
		}
		individualChanges.Add(id);
		((MonoBehaviour)this).StartCoroutine(ChangeAnimal(requester, id, requestedState));
	}

	private IEnumerator ChangeAnimal(ZNetPeer requester, ZDOID id, bool requestedState)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		NetworkSterilityWrites.ChangeResult result = new NetworkSterilityWrites.ChangeResult();
		try
		{
			yield return NetworkSterilityWrites.ApplyChanges(serverSync.CurrentNetwork, new List<NetworkSterilityWrites.TargetWrite>(1)
			{
				new NetworkSterilityWrites.TargetWrite(id)
			}, requestedState, result);
			PlayerNoticeKind kind = PlayerNoticeKind.ChangeUnconfirmed;
			if (result.Changed == 1)
			{
				kind = (requestedState ? PlayerNoticeKind.Sterilized : PlayerNoticeKind.FertileAgain);
				serverSync.PublishSterilityChangeEffect(id, requestedState);
			}
			serverSync.Notify(requester, kind);
		}
		finally
		{
			individualChanges.Remove(id);
		}
	}

	private static bool IsSterilizable(Tameable tameable)
	{
		if ((Object)(object)tameable != (Object)null && tameable.IsTamed() && (Object)(object)((Component)tameable).GetComponent<Procreation>() != (Object)null)
		{
			return (Object)(object)((Component)tameable).GetComponent<Growup>() == (Object)null;
		}
		return false;
	}

	private static bool IsSterilityChangeAllowed(ZNetPeer requester, ZDO target)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		ZNetScene obj = ZNetScene.instance;
		GameObject val = ((obj != null) ? obj.FindInstance(target.m_uid) : null);
		if (requester == null)
		{
			Player localPlayer = Player.m_localPlayer;
			Character val2 = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetHoverCreature() : null);
			if ((Object)(object)val2 != (Object)null && (Object)(object)((Component)val2).gameObject == (Object)(object)val)
			{
				return IsSterilizable(val.GetComponent<Tameable>());
			}
			return false;
		}
		ZDO requestingPlayer = ServerSync.GetRequestingPlayer(requester);
		if (requestingPlayer == null)
		{
			return false;
		}
		ZNetScene val3 = ZNetScene.instance;
		if ((Object)(object)val3 == (Object)null)
		{
			return false;
		}
		GameObject prefab = val3.GetPrefab(requestingPlayer.GetPrefab());
		Player val4 = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<Player>() : null);
		if ((Object)(object)val4 == (Object)null)
		{
			return false;
		}
		GameObject prefab2 = val3.GetPrefab(target.GetPrefab());
		Character val5 = (((Object)(object)prefab2 != (Object)null) ? prefab2.GetComponent<Character>() : null);
		if ((Object)(object)val5 == (Object)null)
		{
			return false;
		}
		if ((Object)(object)val != (Object)null)
		{
			if (!IsSterilizable(val.GetComponent<Tameable>()))
			{
				return false;
			}
		}
		else if (!target.GetBool(ZDOVars.s_tamed, false) || !((Object)(object)prefab2.GetComponent<Tameable>() != (Object)null) || !((Object)(object)prefab2.GetComponent<Procreation>() != (Object)null) || !((Object)(object)prefab2.GetComponent<Growup>() == (Object)null))
		{
			return false;
		}
		float num = val4.m_maxInteractDistance + Mathf.Max(0f, val5.GetHoverOffset());
		Vector3 position = requestingPlayer.GetPosition();
		CapsuleCollider val6 = (((Object)(object)val != (Object)null) ? val.GetComponent<CapsuleCollider>() : null);
		Vector3 val7;
		if ((Object)(object)val6 != (Object)null && ((Collider)val6).enabled)
		{
			val7 = position - ((Collider)val6).ClosestPoint(position);
			return ((Vector3)(ref val7)).sqrMagnitude <= num * num;
		}
		CapsuleCollider component = prefab2.GetComponent<CapsuleCollider>();
		if ((Object)(object)component != (Object)null)
		{
			Vector3 localScale = prefab2.transform.localScale;
			num += component.radius * Mathf.Max(Mathf.Abs(localScale.x), Mathf.Abs(localScale.z));
		}
		val7 = position - target.GetPosition();
		return ((Vector3)(ref val7)).sqrMagnitude <= num * num;
	}

	private void BindSettings()
	{
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Expected O, but got Unknown
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Expected O, but got Unknown
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Expected O, but got Unknown
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0219: Expected O, but got Unknown
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Expected O, but got Unknown
		//IL_0289: Unknown result type (might be due to invalid IL or missing references)
		//IL_0293: Expected O, but got Unknown
		enabledAttributes.CustomDrawer = DrawEnabled;
		enabledAttributes.HideDefaultButton = true;
		enabledAttributes.Order = 0;
		shortcutAttributes.Order = 1;
		effectsAttributes.CustomDrawer = DrawEffects;
		effectsAttributes.Order = 0;
		irreversibleSterilizationAttributes.CustomDrawer = DrawIrreversibleSterilization;
		irreversibleSterilizationAttributes.HideDefaultButton = true;
		irreversibleSterilizationAttributes.Order = 2;
		resetAttributes.CustomDrawer = DrawReset;
		resetAttributes.HideDefaultButton = true;
		resetAttributes.Order = 1;
		cleanupAttributes.CustomDrawer = DrawCleanup;
		cleanupAttributes.HideDefaultButton = true;
		cleanupAttributes.Order = 0;
		UpdateConfigLabels();
		enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("keySectionModActivation", "keyEnableMod", true, new ConfigDescription(enabledAttributes.Description, (AcceptableValueBase)null, new object[1] { enabledAttributes }));
		shortcutSetting = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("keySectionPersonalSettings", "keySterilizationShortcut", new KeyboardShortcut((KeyCode)117, Array.Empty<KeyCode>()), new ConfigDescription(shortcutAttributes.Description, (AcceptableValueBase)null, new object[1] { shortcutAttributes }));
		effectsSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("keySectionPersonalSettings", "keySterilizationEffects", true, new ConfigDescription(effectsAttributes.Description, (AcceptableValueBase)null, new object[1] { effectsAttributes }));
		irreversibleSterilizationSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("keySectionWorldAdministration", "keyIrreversibleSterilization", false, new ConfigDescription(irreversibleSterilizationAttributes.Description, (AcceptableValueBase)null, new object[1] { irreversibleSterilizationAttributes }));
		((BaseUnityPlugin)this).Config.Bind<string>("keySectionWorldAdministration", "keyResetRestrictions", "", new ConfigDescription(resetAttributes.Description, (AcceptableValueBase)null, new object[1] { resetAttributes }));
		((BaseUnityPlugin)this).Config.Bind<string>("keySectionWorldAdministration", "keyRemoveModData", "", new ConfigDescription(cleanupAttributes.Description, (AcceptableValueBase)null, new object[1] { cleanupAttributes }));
		enabledSetting.SettingChanged += OnWorldSettingChanged;
		irreversibleSterilizationSetting.SettingChanged += OnWorldSettingChanged;
		shortcutSetting.SettingChanged += OnShortcutChanged;
	}

	private void UpdateConfigLabels()
	{
		TextResources textResources = uiLanguage.TextResources;
		enabledAttributes.SetText(textResources.ModActivationCategory, textResources.EnabledName, textResources.EnabledDescription);
		shortcutAttributes.SetText(textResources.PersonalSettingsCategory, textResources.ShortcutName, textResources.ShortcutDescription);
		effectsAttributes.SetText(textResources.PersonalSettingsCategory, textResources.SterilizationEffectsName, textResources.SterilizationEffectsDescription);
		irreversibleSterilizationAttributes.SetText(textResources.AdministrationCategory, textResources.IrreversibleSterilizationName, textResources.IrreversibleSterilizationDescription);
		resetAttributes.SetText(textResources.AdministrationCategory, textResources.ResetName, textResources.ResetDescription);
		cleanupAttributes.SetText(textResources.AdministrationCategory, textResources.CleanupName, textResources.CleanupDescription);
	}

	private void OnUiLanguageChanged()
	{
		UpdateConfigLabels();
		try
		{
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				BaseUnityPlugin val = value.Instance;
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Type type = ((object)val).GetType();
				if (!(type.FullName != "ConfigurationManager.ConfigurationManager"))
				{
					if (AccessTools.Property(type, "DisplayingWindow")?.GetValue(val) is int num && num != 0)
					{
						AccessTools.Method(type, "BuildSettingList", Type.EmptyTypes, (Type[])null)?.Invoke(val, null);
					}
					break;
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not refresh the open Configuration Manager window. " + ex.Message));
		}
	}

	private void DrawEnabled(ConfigEntryBase entry)
	{
		bool flag = serverSync?.Enabled ?? enabledSetting.Value;
		bool flag2 = DrawWorldToggle(flag);
		if (flag2 != flag)
		{
			serverSync.RequestEnabled(flag2);
		}
	}

	private void DrawIrreversibleSterilization(ConfigEntryBase entry)
	{
		bool flag = serverSync?.IsIrreversibleSterilizationEnabled ?? irreversibleSterilizationSetting.Value;
		bool flag2 = DrawWorldToggle(flag);
		if (flag2 != flag)
		{
			serverSync.RequestIrreversibleSterilization(flag2);
		}
	}

	private bool DrawWorldToggle(bool current)
	{
		bool enabled = GUI.enabled;
		try
		{
			GUI.enabled = enabled && (Object)(object)instance == (Object)(object)this && serverSync.CanChangeWorldSettings;
			return DrawLocalizedToggle(current);
		}
		finally
		{
			GUI.enabled = enabled;
		}
	}

	private void DrawEffects(ConfigEntryBase entry)
	{
		bool value = effectsSetting.Value;
		bool flag = DrawLocalizedToggle(value);
		if (flag != value)
		{
			effectsSetting.Value = flag;
		}
	}

	private bool DrawLocalizedToggle(bool current)
	{
		TextResources textResources = uiLanguage.TextResources;
		return GUILayout.Toggle(current, current ? textResources.Enabled : textResources.Disabled, Array.Empty<GUILayoutOption>());
	}

	private void DrawReset(ConfigEntryBase entry)
	{
		bool enabled = GUI.enabled;
		try
		{
			GUI.enabled = enabled && (Object)(object)instance == (Object)(object)this && serverSync.CanReset;
			if (GUILayout.Button(uiLanguage.TextResources.ResetButton, Array.Empty<GUILayoutOption>()))
			{
				serverSync.RequestReset();
			}
		}
		finally
		{
			GUI.enabled = enabled;
		}
	}

	private void DrawCleanup(ConfigEntryBase entry)
	{
		bool enabled = GUI.enabled;
		try
		{
			GUI.enabled = enabled && (Object)(object)instance == (Object)(object)this && IsCleanupAvailable(serverSync.CurrentNetwork);
			if (GUILayout.Button(uiLanguage.TextResources.CleanupButton, Array.Empty<GUILayoutOption>()))
			{
				ClearWorldModData();
			}
		}
		finally
		{
			GUI.enabled = enabled;
		}
	}

	private void OnWorldSettingChanged(object sender, EventArgs args)
	{
		serverSync?.RefreshWorldSettings();
	}

	private void OnShortcutChanged(object sender, EventArgs args)
	{
		hotkey.Dispose();
		RefreshHotkey();
	}

	private void RefreshHotkey()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		hotkey.Refresh(shortcutSetting.Value);
	}

	private void Awake()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		harmony = new Harmony("rehallowed.OffWithTheirNuts");
		try
		{
			uiLanguage = new GameUiLanguage();
			worldObjects = AccessTools.FieldRefAccess<ZDOMan, Dictionary<ZDOID, ZDO>>("m_objectsByID");
			hotkey = new SterilizationHotkey(() => RestrictionsActive, ToggleTarget);
			BindSettings();
			uiLanguage.Changed += OnUiLanguageChanged;
			SterilizationEffects sterilizationEffects = new SterilizationEffects(effectsSetting, ((BaseUnityPlugin)this).Logger);
			serverSync = new ServerSync(enabledSetting, irreversibleSterilizationSetting, RefreshHotkey, OnWorldClosed, StartChange, StartReset, delegate(PlayerNotice notice)
			{
				notice.Show(uiLanguage.TextResources);
			}, sterilizationEffects.PlayIfEnabled);
			harmony.PatchAll(typeof(OffWithTheirNutsPlugin).Assembly);
			if (!GameUiLanguage.PatchLanguageSetup(harmony))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Valheim's language setup method was not found. Using the startup language.");
			}
			instance = this;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Off With Their Nuts! 1.0.0 loaded.");
		}
		catch (Exception ex)
		{
			harmony.UnpatchSelf();
			ReleaseUiLanguage();
			((BaseUnityPlugin)this).Logger.LogError((object)("Off With Their Nuts! was disabled during initialization. " + ex));
		}
	}

	private void OnDestroy()
	{
		if ((Object)(object)instance == (Object)(object)this)
		{
			serverSync.CloseWorld();
			instance = null;
		}
		if (shortcutSetting != null)
		{
			shortcutSetting.SettingChanged -= OnShortcutChanged;
		}
		if (enabledSetting != null)
		{
			enabledSetting.SettingChanged -= OnWorldSettingChanged;
		}
		if (irreversibleSterilizationSetting != null)
		{
			irreversibleSterilizationSetting.SettingChanged -= OnWorldSettingChanged;
		}
		ReleaseUiLanguage();
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}

	private void ReleaseUiLanguage()
	{
		if (uiLanguage != null)
		{
			uiLanguage.Changed -= OnUiLanguageChanged;
		}
	}

	private void OnWorldClosed()
	{
		resetting = false;
		((MonoBehaviour)this).StopAllCoroutines();
		individualChanges.Clear();
		hotkey.Dispose();
	}

	private static bool IsCleanupAvailable(ZNet network)
	{
		if ((Object)(object)network != (Object)null && network.IsServer() && (Object)(object)Player.m_localPlayer != (Object)null)
		{
			return ZDOMan.instance != null;
		}
		return false;
	}

	private void ClearWorldModData()
	{
		ZNet currentNetwork = serverSync.CurrentNetwork;
		if (!IsCleanupAvailable(currentNetwork))
		{
			return;
		}
		TextResources textResources = uiLanguage.TextResources;
		if (currentNetwork.GetPeers().Count != 0)
		{
			ShowCleanupNotice(textResources.CleanupPlayersConnected);
			return;
		}
		if (resetting || individualChanges.Count != 0)
		{
			ShowCleanupNotice(textResources.ChangePending);
			return;
		}
		ZDOMan val = ZDOMan.instance;
		int num = 0;
		foreach (ZDO value in worldObjects.Invoke(val).Values)
		{
			if (ZdoSterilityOperations.TryRemoveSterility(value))
			{
				val.SetDirtySector(value);
				num++;
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("World cleanup removed " + num + " sterility fields."));
		ShowCleanupNotice(textResources.CleanupCompleted);
	}

	private static void ShowCleanupNotice(string message)
	{
		MessageHud val = MessageHud.instance;
		if ((Object)(object)val != (Object)null)
		{
			val.ShowMessage((MessageType)2, message, 0, (Sprite)null, false, false);
		}
	}

	private void StartReset(ZNetPeer requester)
	{
		if (serverSync.IsWorldAdmin(requester) && ZDOMan.instance != null)
		{
			if (resetting)
			{
				serverSync.Notify(requester, PlayerNoticeKind.ResetRunning);
				return;
			}
			resetting = true;
			Stopwatch duration = Stopwatch.StartNew();
			serverSync.Notify(requester, PlayerNoticeKind.ResetStarted);
			((MonoBehaviour)this).StartCoroutine(ResetAnimals(requester, duration));
		}
	}

	private IEnumerator ResetAnimals(ZNetPeer requester, Stopwatch duration)
	{
		try
		{
			yield return null;
			yield return null;
			while (individualChanges.Count > 0)
			{
				yield return null;
			}
			Stopwatch scan = Stopwatch.StartNew();
			List<NetworkSterilityWrites.TargetWrite> list = new List<NetworkSterilityWrites.TargetWrite>();
			int scanned = 0;
			foreach (ZDO value in worldObjects.Invoke(ZDOMan.instance).Values)
			{
				scanned++;
				if (ZdoSterilityOperations.IsSterile(value))
				{
					list.Add(new NetworkSterilityWrites.TargetWrite(value.m_uid));
				}
			}
			scan.Stop();
			NetworkSterilityWrites.ChangeResult result = new NetworkSterilityWrites.ChangeResult();
			yield return NetworkSterilityWrites.ApplyChanges(serverSync.CurrentNetwork, list, requestedState: false, result);
			duration.Stop();
			serverSync.Notify(requester, new PlayerNotice(result.Changed, duration.Elapsed.TotalSeconds, result.Unconfirmed));
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "Sterility reset. Scanned {0} ZDO records in {1:F1} ms, cleared {2} flags, {3} records missing, {4} confirmation timeouts, {5:F1} ms total.", scanned, scan.Elapsed.TotalMilliseconds, result.Changed, result.Missing, result.TimedOut, duration.Elapsed.TotalMilliseconds));
		}
		finally
		{
			resetting = false;
		}
	}
}
internal static class Constants
{
	internal const string PluginId = "rehallowed.OffWithTheirNuts";

	internal const string PluginName = "Off With Their Nuts!";

	internal const string PluginVersion = "1.0.0";
}
internal sealed class GameUiLanguage
{
	internal TextResources TextResources { get; private set; } = ReadTextResources();

	internal event Action Changed;

	internal static bool PatchLanguageSetup(Harmony harmony)
	{
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("Localization");
		if (type == null)
		{
			return false;
		}
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "SetupLanguage", new Type[1] { typeof(string) }, (Type[])null);
		if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(bool))
		{
			return false;
		}
		MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(GameUiLanguage), "AfterLanguageSetup", (Type[])null, (Type[])null);
		harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		return true;
	}

	private static void AfterLanguageSetup()
	{
		OffWithTheirNutsPlugin.ActiveUiLanguage?.Refresh();
	}

	private void Refresh()
	{
		TextResources textResources = ReadTextResources();
		if (TextResources != textResources)
		{
			TextResources = textResources;
			this.Changed?.Invoke();
		}
	}

	private static TextResources ReadTextResources()
	{
		return LocalizationCore.ForLanguage(PlatformPrefs.GetString("language", "English"));
	}
}
internal class LocalizationCore
{
	internal const string DefaultLanguage = "English";

	private static readonly TextResources englishTextResources = new EnglishTextResources();

	private static readonly Dictionary<string, TextResources> byLanguage = new Dictionary<string, TextResources>(StringComparer.OrdinalIgnoreCase)
	{
		{ "English", englishTextResources },
		{
			"Russian",
			new RussianTextResources()
		},
		{
			"German",
			new GermanTextResources()
		},
		{
			"Portuguese_Brazilian",
			new BrazilianPortugueseTextResources()
		},
		{
			"Spanish",
			new SpanishTextResources()
		},
		{
			"French",
			new FrenchTextResources()
		},
		{
			"Polish",
			new PolishTextResources()
		},
		{
			"Ukrainian",
			new UkrainianTextResources()
		},
		{
			"Turkish",
			new TurkishTextResources()
		},
		{
			"Chinese",
			new ChineseTextResources()
		},
		{
			"Chinese_Trad",
			new ChineseTextResources()
		},
		{
			"Japanese",
			new JapaneseTextResources()
		}
	};

	internal static TextResources ForLanguage(string language)
	{
		if (language == null || !byLanguage.TryGetValue(language, out var value))
		{
			return englishTextResources;
		}
		return value;
	}
}
internal enum PluralForm
{
	Zero,
	One,
	Two,
	Few,
	Many,
	Other
}
internal sealed class Plural
{
	private readonly PluralRules pluralRules;

	private readonly string other;

	private readonly string zero;

	private readonly string one;

	private readonly string two;

	private readonly string few;

	private readonly string many;

	internal Plural(PluralRules pluralRules, string other, string zero = null, string one = null, string two = null, string few = null, string many = null)
	{
		this.pluralRules = pluralRules ?? throw new ArgumentNullException("pluralRules");
		this.other = other ?? throw new ArgumentNullException("other");
		this.zero = zero;
		this.one = one;
		this.two = two;
		this.few = few;
		this.many = many;
	}

	internal string GetQuantityString(int count)
	{
		return (string)((pluralRules.GetPluralForm(count) switch
		{
			PluralForm.Zero => zero, 
			PluralForm.One => one, 
			PluralForm.Two => two, 
			PluralForm.Few => few, 
			PluralForm.Many => many, 
			_ => other, 
		}) ?? other);
	}
}
internal abstract class PluralRules
{
	internal abstract PluralForm GetPluralForm(int count);
}
internal sealed class EastSlavicPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		long num = Math.Abs((long)count);
		long num2 = num % 10;
		long num3 = num % 100;
		if (num2 == 1 && num3 != 11)
		{
			return PluralForm.One;
		}
		if (num2 >= 2 && num2 <= 4 && (num3 < 12 || num3 > 14))
		{
			return PluralForm.Few;
		}
		return PluralForm.Many;
	}
}
internal sealed class InvariantPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		return PluralForm.Other;
	}
}
internal sealed class OneOrOtherPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		if (Math.Abs((long)count) != 1)
		{
			return PluralForm.Other;
		}
		return PluralForm.One;
	}
}
internal sealed class ZeroAndOneSingularPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		long num = Math.Abs((long)count);
		if (num <= 1)
		{
			return PluralForm.One;
		}
		if (num % 1000000 == 0L)
		{
			return PluralForm.Many;
		}
		return PluralForm.Other;
	}
}
internal class TextMapper
{
	internal static string GetFormattedResetResult(TextResources localization, int count, double seconds, int unconfirmed)
	{
		string text = string.Format(CultureInfo.InvariantCulture, localization.ResetResult.GetQuantityString(count), count, seconds);
		if (unconfirmed > 0)
		{
			text += string.Format(CultureInfo.InvariantCulture, localization.ResetUnconfirmed, unconfirmed);
		}
		return text;
	}
}
internal sealed class GermanTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new OneOrOtherPluralRules();

	internal override string SterileStatus => "Sterilisiert";

	internal override string SterilizeHint => "Sterilisieren";

	internal override string IrreversibleSterilizationHint => "Sterilisieren (unumkehrbar)";

	internal override string RestoreFertilityHint => "Fruchtbarkeit wiederherstellen";

	internal override string ModActivationCategory => "Mod-Aktivierung";

	internal override string PersonalSettingsCategory => "Persönliche Einstellungen";

	internal override string AdministrationCategory => "Verwaltung";

	internal override string EnabledName => "Mod aktivieren";

	internal override string EnabledDescription => "Gespeicherte Zuchtbeschränkungen anwenden. Im Mehrspielermodus bestimmt der Server diese Einstellung.";

	internal override string IrreversibleSterilizationName => "Unumkehrbarkeit der Sterilisation";

	internal override string IrreversibleSterilizationDescription => "Solange diese Einstellung aktiv ist, lässt sich die Sterilisation einzelner Tiere nicht rückgängig machen. Admins können die Sterilisation aller Tiere auf einmal zurücksetzen.";

	internal override string Enabled => "Aktiviert";

	internal override string Disabled => "Deaktiviert";

	internal override string ShortcutName => "Tastenbelegung";

	internal override string ShortcutDescription => "Visiere ein gezähmtes Tier an und drücke diese Taste oder Tastenkombination.";

	internal override string SterilizationEffectsName => "Sterilisationseffekte";

	internal override string SterilizationEffectsDescription => "Ton- und Bildeffekte abspielen, wenn ein Tier sterilisiert oder seine Fruchtbarkeit wiederhergestellt wird.";

	internal override string ResetName => "Aufhebung der Sterilisation";

	internal override string ResetDescription => "Die Fruchtbarkeit aller sterilisierten Tiere in der aktuellen Welt wiederherstellen.";

	internal override string ResetButton => "Alle wieder fruchtbar machen";

	internal override string CleanupName => "Löschen der Mod-Daten";

	internal override string CleanupDescription => "Alle Mod-Daten aus dem Spielstand der aktuellen Welt entfernen. Starte die Bereinigung erst, wenn keine anderen Spieler verbunden sind. Achte darauf, dass bis zum Ende niemand beitritt, da der Mod Verbindungen nicht blockiert. Speichere zum Abschluss die Welt und lade sie neu. Danach kannst du den Mod deinstallieren.";

	internal override string CleanupButton => "Mod-Daten aus der Welt löschen";

	internal override string CleanupPlayersConnected => "Für die Bereinigung müssen alle anderen Spieler die Verbindung trennen";

	internal override string CleanupCompleted => "Mod-Daten gelöscht. Speichere die Welt, um die Änderungen zu übernehmen";

	internal override string ChangePending => "Eine Änderung läuft bereits. Versuche es danach erneut.";

	internal override string TargetUnavailable => "Der Status dieses Tieres konnte nicht geändert werden. Geh näher heran und versuch es erneut.";

	internal override string AlreadySterile => "Dieses Tier ist bereits sterilisiert.";

	internal override string AlreadyFertile => "Dieses Tier kann sich bereits fortpflanzen.";

	internal override string ChangeUnconfirmed => "Die Änderung für dieses Tier konnte nicht bestätigt werden.";

	internal override string Sterilized => "Tier sterilisiert";

	internal override string FertileAgain => "Tier ist wieder fruchtbar";

	internal override string FertilityRestorationBlocked => "Das Wiederherstellen der Fruchtbarkeit wurde vom Admin deaktiviert";

	internal override string ResetRunning => "Die Sterilisation wird bereits zurückgesetzt.";

	internal override string ResetStarted => "Fruchtbarkeit der Tiere wird wiederhergestellt...";

	internal override Plural ResetResult => MakePlural("Fruchtbarkeit bei {0} Tieren in {1:0.00} s wiederhergestellt", null, "Fruchtbarkeit bei {0} Tier in {1:0.00} s wiederhergestellt");

	internal override string ResetUnconfirmed => " ({0} ohne Bestätigung)";
}
internal sealed class EnglishTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new OneOrOtherPluralRules();

	internal override string SterileStatus => "Sterile";

	internal override string SterilizeHint => "Sterilize";

	internal override string IrreversibleSterilizationHint => "Sterilize (irreversible)";

	internal override string RestoreFertilityHint => "Restore fertility";

	internal override string ModActivationCategory => "Mod Activation";

	internal override string PersonalSettingsCategory => "Personal Settings";

	internal override string AdministrationCategory => "Administration";

	internal override string EnabledName => "Enable mod";

	internal override string EnabledDescription => "Apply saved breeding restrictions. In multiplayer, the server controls this setting.";

	internal override string IrreversibleSterilizationName => "Sterilization irreversibility";

	internal override string IrreversibleSterilizationDescription => "Prevent restoring fertility to individual animals while this setting is enabled. Admins can still reset sterilization for all animals at once.";

	internal override string Enabled => "Enabled";

	internal override string Disabled => "Disabled";

	internal override string ShortcutName => "Key binding";

	internal override string ShortcutDescription => "Aim at a tamed animal and press this key or shortcut.";

	internal override string SterilizationEffectsName => "Sterilization effects";

	internal override string SterilizationEffectsDescription => "Play sounds and visual effects when an animal is sterilized or its fertility is restored.";

	internal override string ResetName => "Sterilization reset";

	internal override string ResetDescription => "Restore fertility to all sterile animals in the current world.";

	internal override string ResetButton => "Undo all sterilizations";

	internal override string CleanupName => "Mod data removal";

	internal override string CleanupDescription => "Remove all mod data from the current world's save. Start the cleanup with no other players connected. Make sure no one joins until cleanup is complete - the mod does not block connections. To finish, save and reload the world. You can then uninstall the mod.";

	internal override string CleanupButton => "Remove mod data from world";

	internal override string CleanupPlayersConnected => "Cleanup requires all other players to disconnect";

	internal override string CleanupCompleted => "Mod data removed. Save the world to keep the changes";

	internal override string ChangePending => "A change is already in progress. Try again when it finishes.";

	internal override string TargetUnavailable => "Could not change the animal's status. Move closer and try again.";

	internal override string AlreadySterile => "This animal is already sterile.";

	internal override string AlreadyFertile => "This animal can already breed.";

	internal override string ChangeUnconfirmed => "Could not confirm the change for this animal.";

	internal override string Sterilized => "Animal sterilized";

	internal override string FertileAgain => "Animal is fertile again";

	internal override string FertilityRestorationBlocked => "Fertility restoration is disabled by admin";

	internal override string ResetRunning => "A sterility reset is already in progress.";

	internal override string ResetStarted => "Restoring fertility to animals...";

	internal override Plural ResetResult => MakePlural("Restored fertility to {0} animals in {1:0.00}s", null, "Restored fertility to {0} animal in {1:0.00}s");

	internal override string ResetUnconfirmed => " ({0} unconfirmed)";
}
internal sealed class SpanishPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		long num = Math.Abs((long)count);
		switch (num)
		{
		case 1L:
			return PluralForm.One;
		default:
			if (num % 1000000 == 0L)
			{
				return PluralForm.Many;
			}
			break;
		case 0L:
			break;
		}
		return PluralForm.Other;
	}
}
internal sealed class SpanishTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new SpanishPluralRules();

	internal override string SterileStatus => "Esterilizado";

	internal override string SterilizeHint => "Esterilizar";

	internal override string IrreversibleSterilizationHint => "Esterilizar (irreversible)";

	internal override string RestoreFertilityHint => "Restaurar la fertilidad";

	internal override string ModActivationCategory => "Activación del mod";

	internal override string PersonalSettingsCategory => "Ajustes personales";

	internal override string AdministrationCategory => "Administración";

	internal override string EnabledName => "Activar el mod";

	internal override string EnabledDescription => "Aplicar las restricciones de reproducción guardadas. En multijugador, el servidor controla este ajuste.";

	internal override string IrreversibleSterilizationName => "Irreversibilidad de la esterilización";

	internal override string IrreversibleSterilizationDescription => "Mientras este ajuste esté activo, no se puede revertir la esterilización de un animal por separado. Los administradores pueden restaurar la fertilidad de todos los animales a la vez.";

	internal override string Enabled => "Activado";

	internal override string Disabled => "Desactivado";

	internal override string ShortcutName => "Asignación de tecla";

	internal override string ShortcutDescription => "Apunta a un animal domesticado y pulsa esta tecla o combinación de teclas.";

	internal override string SterilizationEffectsName => "Efectos de esterilización";

	internal override string SterilizationEffectsDescription => "Reproducir sonidos y efectos visuales al esterilizar a un animal o restaurar su fertilidad.";

	internal override string ResetName => "Reversión de la esterilización";

	internal override string ResetDescription => "Restaurar la fertilidad de todos los animales esterilizados del mundo actual.";

	internal override string ResetButton => "Restaurar fertilidad a todos";

	internal override string CleanupName => "Eliminación de datos del mod";

	internal override string CleanupDescription => "Eliminar del archivo de guardado del mundo actual todos los datos del mod. Inicia la limpieza cuando no haya otros jugadores conectados. Asegúrate de que nadie se conecte hasta que termine, ya que el mod no bloquea las conexiones. Para terminar, guarda el mundo y vuelve a cargarlo. Después podrás desinstalar el mod.";

	internal override string CleanupButton => "Borrar los datos del mod del mundo";

	internal override string CleanupPlayersConnected => "Todos los demás jugadores deben desconectarse para iniciar la limpieza";

	internal override string CleanupCompleted => "Datos del mod borrados. Guarda el mundo para conservar los cambios";

	internal override string ChangePending => "Ya hay un cambio en curso. Vuelve a intentarlo cuando termine.";

	internal override string TargetUnavailable => "No se ha podido cambiar el estado del animal. Acércate e inténtalo de nuevo.";

	internal override string AlreadySterile => "Este animal ya está esterilizado.";

	internal override string AlreadyFertile => "Este animal ya puede reproducirse.";

	internal override string ChangeUnconfirmed => "No se ha podido confirmar el cambio para este animal.";

	internal override string Sterilized => "Animal esterilizado";

	internal override string FertileAgain => "El animal vuelve a ser fértil";

	internal override string FertilityRestorationBlocked => "El administrador ha desactivado la restauración de la fertilidad";

	internal override string ResetRunning => "Ya se está restaurando la fertilidad de los animales.";

	internal override string ResetStarted => "Restaurando la fertilidad de los animales...";

	internal override Plural ResetResult => MakePlural("Se ha restaurado la fertilidad de {0} animales en {1:0.00} s", null, "Se ha restaurado la fertilidad de {0} animal en {1:0.00} s");

	internal override string ResetUnconfirmed => " ({0} sin confirmar)";
}
internal sealed class FrenchTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new ZeroAndOneSingularPluralRules();

	internal override string SterileStatus => "Stérilisé";

	internal override string SterilizeHint => "Stériliser";

	internal override string IrreversibleSterilizationHint => "Stériliser (irréversible)";

	internal override string RestoreFertilityHint => "Rétablir la fertilité";

	internal override string ModActivationCategory => "Activation du mod";

	internal override string PersonalSettingsCategory => "Paramètres personnels";

	internal override string AdministrationCategory => "Administration";

	internal override string EnabledName => "Activer le mod";

	internal override string EnabledDescription => "Appliquer les restrictions de reproduction enregistrées. En multijoueur, le serveur contrôle ce paramètre.";

	internal override string IrreversibleSterilizationName => "Irréversibilité de la stérilisation";

	internal override string IrreversibleSterilizationDescription => "Tant que cette option est activée, la stérilisation d'un animal ne peut pas être annulée individuellement. Les administrateurs peuvent toujours rétablir la fertilité de tous les animaux à la fois.";

	internal override string Enabled => "Activé";

	internal override string Disabled => "Désactivé";

	internal override string ShortcutName => "Raccourci clavier";

	internal override string ShortcutDescription => "Vise un animal apprivoisé, puis appuie sur cette touche ou combinaison de touches.";

	internal override string SterilizationEffectsName => "Effets de stérilisation";

	internal override string SterilizationEffectsDescription => "Déclencher les effets sonores et visuels lorsqu'un animal est stérilisé ou retrouve sa fertilité.";

	internal override string ResetName => "Rétablissement de la fertilité";

	internal override string ResetDescription => "Rétablir la fertilité de tous les animaux stérilisés du monde actuel.";

	internal override string ResetButton => "Rendre la fertilité à tous";

	internal override string CleanupName => "Suppression des données du mod";

	internal override string CleanupDescription => "Supprimer les données du mod de la sauvegarde du monde actuel. Lance le nettoyage quand aucun autre joueur n'est connecté. Veille à ce que personne ne rejoigne la partie avant la fin, car le mod ne bloque pas les connexions. Pour terminer, sauvegarde le monde et recharge-le. Tu pourras ensuite désinstaller le mod.";

	internal override string CleanupButton => "Supprimer les données du mod du monde";

	internal override string CleanupPlayersConnected => "Tous les autres joueurs doivent se déconnecter avant le nettoyage";

	internal override string CleanupCompleted => "Données du mod supprimées. Sauvegarde le monde pour conserver les modifications";

	internal override string ChangePending => "Une modification est déjà en cours. Réessaie lorsqu'elle sera terminée.";

	internal override string TargetUnavailable => "Impossible de modifier le statut de cet animal. Approche-toi et réessaie.";

	internal override string AlreadySterile => "Cet animal est déjà stérilisé.";

	internal override string AlreadyFertile => "Cet animal peut déjà se reproduire.";

	internal override string ChangeUnconfirmed => "Impossible de confirmer la modification pour cet animal.";

	internal override string Sterilized => "Animal stérilisé";

	internal override string FertileAgain => "L'animal est de nouveau fertile";

	internal override string FertilityRestorationBlocked => "La restauration de la fertilité a été désactivée par un administrateur";

	internal override string ResetRunning => "La restauration de la fertilité est déjà en cours.";

	internal override string ResetStarted => "Restauration de la fertilité des animaux...";

	internal override Plural ResetResult => MakePlural("Fertilité rétablie pour {0} animaux en {1:0.00} s", null, "Fertilité rétablie pour {0} animal en {1:0.00} s");

	internal override string ResetUnconfirmed => " ({0} sans confirmation)";
}
internal sealed class JapaneseTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new InvariantPluralRules();

	internal override string SterileStatus => "不妊化済み";

	internal override string SterilizeHint => "不妊化する";

	internal override string IrreversibleSterilizationHint => "不妊化する(元に戻せない)";

	internal override string RestoreFertilityHint => "繁殖能力を回復する";

	internal override string ModActivationCategory => "MODの有効化";

	internal override string PersonalSettingsCategory => "個人設定";

	internal override string AdministrationCategory => "管理";

	internal override string EnabledName => "MODを有効にする";

	internal override string EnabledDescription => "保存済みの繁殖制限を適用します。マルチプレイではサーバーがこの設定を管理します。";

	internal override string IrreversibleSterilizationName => "不妊化の不可逆性";

	internal override string IrreversibleSterilizationDescription => "この設定が有効な間は、個別の動物の不妊化を取り消せません。管理者は引き続き、すべての動物の繁殖能力を一括で回復できます。";

	internal override string Enabled => "有効";

	internal override string Disabled => "無効";

	internal override string ShortcutName => "キー設定";

	internal override string ShortcutDescription => "手なずけた動物に照準を合わせ、このキーまたはキーの組み合わせを押してください。";

	internal override string SterilizationEffectsName => "不妊化エフェクト";

	internal override string SterilizationEffectsDescription => "動物を不妊化したときや繁殖能力を回復したときに、効果音と視覚エフェクトを再生します。";

	internal override string ResetName => "不妊化の一括解除";

	internal override string ResetDescription => "現在のワールドで不妊化されたすべての動物の繁殖能力を回復します。";

	internal override string ResetButton => "すべての動物の不妊化を解除";

	internal override string CleanupName => "MODデータの削除";

	internal override string CleanupDescription => "現在のワールドのセーブデータから、このMODのデータをすべて削除します。ほかのプレイヤーが接続していない状態で開始してください。このMODは接続をブロックしないため、削除が終わるまで誰も参加しないようにしてください。最後にワールドを保存し、読み込み直してください。その後、このMODをアンインストールできます。";

	internal override string CleanupButton => "ワールドからMODデータを削除";

	internal override string CleanupPlayersConnected => "削除するには、ほかのプレイヤー全員が切断する必要があります";

	internal override string CleanupCompleted => "MODデータを削除しました。変更を反映するにはワールドを保存してください";

	internal override string ChangePending => "変更を処理中です。完了してからもう一度お試しください。";

	internal override string TargetUnavailable => "動物の状態を変更できませんでした。近づいてからもう一度試してください。";

	internal override string AlreadySterile => "この動物はすでに不妊化されています。";

	internal override string AlreadyFertile => "この動物はすでに繁殖できます。";

	internal override string ChangeUnconfirmed => "この動物の不妊化状態が変わったか確認できませんでした。";

	internal override string Sterilized => "動物を不妊化しました";

	internal override string FertileAgain => "動物の繁殖能力を回復しました";

	internal override string FertilityRestorationBlocked => "管理者が繁殖能力の回復を無効にしています";

	internal override string ResetRunning => "繁殖能力の一括回復はすでに進行中です。";

	internal override string ResetStarted => "動物の繁殖能力を回復しています…";

	internal override Plural ResetResult => MakePlural("{1:0.00}秒で{0}匹の動物の繁殖能力を回復しました");

	internal override string ResetUnconfirmed => "({0}匹は未確認)";
}
internal sealed class PolishPluralRules : PluralRules
{
	internal override PluralForm GetPluralForm(int count)
	{
		long num = Math.Abs((long)count);
		if (num == 1)
		{
			return PluralForm.One;
		}
		long num2 = num % 10;
		long num3 = num % 100;
		if (num2 >= 2 && num2 <= 4 && (num3 < 12 || num3 > 14))
		{
			return PluralForm.Few;
		}
		return PluralForm.Many;
	}
}
internal sealed class PolishTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new PolishPluralRules();

	internal override string SterileStatus => "Wysterylizowane";

	internal override string SterilizeHint => "Wysterylizuj";

	internal override string IrreversibleSterilizationHint => "Wysterylizuj (nieodwracalnie)";

	internal override string RestoreFertilityHint => "Przywróć płodność";

	internal override string ModActivationCategory => "Aktywacja moda";

	internal override string PersonalSettingsCategory => "Ustawienia osobiste";

	internal override string AdministrationCategory => "Administracja";

	internal override string EnabledName => "Włącz mod";

	internal override string EnabledDescription => "Stosuj zapisane ograniczenia rozmnażania. W trybie wieloosobowym o tym ustawieniu decyduje serwer.";

	internal override string IrreversibleSterilizationName => "Nieodwracalność sterylizacji";

	internal override string IrreversibleSterilizationDescription => "Gdy opcja jest włączona, nie można cofnąć sterylizacji pojedynczego zwierzęcia. Administratorzy nadal mogą przywrócić płodność wszystkim zwierzętom naraz.";

	internal override string Enabled => "Włączone";

	internal override string Disabled => "Wyłączone";

	internal override string ShortcutName => "Przypisanie klawisza";

	internal override string ShortcutDescription => "Wyceluj w oswojone zwierzę i naciśnij ten klawisz lub kombinację klawiszy.";

	internal override string SterilizationEffectsName => "Efekty sterylizacji";

	internal override string SterilizationEffectsDescription => "Odtwarzaj dźwięki i efekty wizualne podczas sterylizacji zwierzęcia lub przywracania mu płodności.";

	internal override string ResetName => "Cofnięcie sterylizacji";

	internal override string ResetDescription => "Przywróć płodność wszystkim wysterylizowanym zwierzętom w bieżącym świecie.";

	internal override string ResetButton => "Przywróć płodność wszystkim";

	internal override string CleanupName => "Usuwanie danych moda";

	internal override string CleanupDescription => "Usuń wszystkie dane moda z zapisu bieżącego świata. Rozpocznij czyszczenie tylko wtedy, gdy żaden inny gracz nie jest połączony. Upewnij się, że do końca czyszczenia nikt nie dołączy, ponieważ mod nie blokuje połączeń. Na koniec zapisz świat i wczytaj go ponownie. Potem możesz odinstalować mod.";

	internal override string CleanupButton => "Usuń dane moda ze świata";

	internal override string CleanupPlayersConnected => "Pozostali gracze muszą się rozłączyć przed rozpoczęciem czyszczenia";

	internal override string CleanupCompleted => "Usunięto dane moda. Zapisz świat, aby zachować zmiany";

	internal override string ChangePending => "Zmiana jest już w toku. Spróbuj ponownie po jej zakończeniu.";

	internal override string TargetUnavailable => "Nie udało się zmienić stanu zwierzęcia. Podejdź bliżej i spróbuj ponownie.";

	internal override string AlreadySterile => "To zwierzę jest już wysterylizowane.";

	internal override string AlreadyFertile => "To zwierzę może już się rozmnażać.";

	internal override string ChangeUnconfirmed => "Nie udało się potwierdzić zmiany dla tego zwierzęcia.";

	internal override string Sterilized => "Zwierzę wysterylizowane";

	internal override string FertileAgain => "Zwierzę odzyskało płodność";

	internal override string FertilityRestorationBlocked => "Administrator wyłączył możliwość przywracania płodności";

	internal override string ResetRunning => "Przywracanie płodności jest już w toku.";

	internal override string ResetStarted => "Trwa przywracanie płodności zwierzętom...";

	internal override Plural ResetResult => MakePlural("{0} zwierząt odzyskało płodność w {1:0.00} s", null, "{0} zwierzę odzyskało płodność w {1:0.00} s", null, "{0} zwierzęta odzyskały płodność w {1:0.00} s");

	internal override string ResetUnconfirmed => " ({0} bez potwierdzenia)";
}
internal sealed class BrazilianPortugueseTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new ZeroAndOneSingularPluralRules();

	internal override string SterileStatus => "Esterilizado";

	internal override string SterilizeHint => "Esterilizar";

	internal override string IrreversibleSterilizationHint => "Esterilizar (irreversível)";

	internal override string RestoreFertilityHint => "Restaurar fertilidade";

	internal override string ModActivationCategory => "Ativação do mod";

	internal override string PersonalSettingsCategory => "Configurações pessoais";

	internal override string AdministrationCategory => "Administração";

	internal override string EnabledName => "Ativar mod";

	internal override string EnabledDescription => "Aplicar as restrições de reprodução salvas. No multijogador, o servidor controla esta configuração.";

	internal override string IrreversibleSterilizationName => "Irreversibilidade da esterilização";

	internal override string IrreversibleSterilizationDescription => "Enquanto esta opção estiver ativa, não será possível reverter a esterilização de um único animal. Os administradores ainda podem restaurar a fertilidade de todos os animais de uma vez.";

	internal override string Enabled => "Ativado";

	internal override string Disabled => "Desativado";

	internal override string ShortcutName => "Atalho de teclado";

	internal override string ShortcutDescription => "Mire em um animal domesticado e pressione esta tecla ou combinação de teclas.";

	internal override string SterilizationEffectsName => "Efeitos de esterilização";

	internal override string SterilizationEffectsDescription => "Reproduzir sons e efeitos visuais ao esterilizar um animal ou restaurar sua fertilidade.";

	internal override string ResetName => "Reversão da esterilização";

	internal override string ResetDescription => "Restaurar a fertilidade de todos os animais esterilizados no mundo atual.";

	internal override string ResetButton => "Devolver fertilidade a todos";

	internal override string CleanupName => "Remoção de dados do mod";

	internal override string CleanupDescription => "Remover todos os dados do mod do arquivo de salvamento do mundo atual. Inicie a limpeza sem outros jogadores conectados. Certifique-se de que ninguém entre até o fim da limpeza, pois o mod não bloqueia conexões. Para concluir, salve e recarregue o mundo. Depois disso, você pode desinstalar o mod.";

	internal override string CleanupButton => "Remover dados do mod do mundo";

	internal override string CleanupPlayersConnected => "Todos os outros jogadores precisam se desconectar para iniciar a limpeza";

	internal override string CleanupCompleted => "Dados do mod removidos. Salve o mundo para manter as alterações";

	internal override string ChangePending => "Já há uma alteração em andamento. Tente novamente quando ela terminar.";

	internal override string TargetUnavailable => "Não foi possível alterar o estado do animal. Aproxime-se e tente novamente.";

	internal override string AlreadySterile => "Este animal já foi esterilizado.";

	internal override string AlreadyFertile => "Este animal já pode se reproduzir.";

	internal override string ChangeUnconfirmed => "Não foi possível confirmar a alteração para este animal.";

	internal override string Sterilized => "Animal esterilizado";

	internal override string FertileAgain => "O animal está fértil de novo";

	internal override string FertilityRestorationBlocked => "O administrador desativou a restauração da fertilidade";

	internal override string ResetRunning => "A restauração da fertilidade já está em andamento.";

	internal override string ResetStarted => "Restaurando a fertilidade dos animais...";

	internal override Plural ResetResult => MakePlural("Fertilidade de {0} animais restaurada em {1:0.00} s", null, "Fertilidade de {0} animal restaurada em {1:0.00} s");

	internal override string ResetUnconfirmed => " ({0} sem confirmação)";
}
internal sealed class RussianTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new EastSlavicPluralRules();

	internal override string SterileStatus => "Стерилизован";

	internal override string SterilizeHint => "Стерилизовать";

	internal override string IrreversibleSterilizationHint => "Стерилизовать (необратимо)";

	internal override string RestoreFertilityHint => "Вернуть фертильность";

	internal override string ModActivationCategory => "Включение мода";

	internal override string PersonalSettingsCategory => "Индивидуальные настройки";

	internal override string AdministrationCategory => "Администрирование";

	internal override string EnabledName => "Включить мод";

	internal override string EnabledDescription => "Применять сохранённые статусы стерилизации. В мультиплеере эту настройку задаёт сервер.";

	internal override string IrreversibleSterilizationName => "Необратимость стерилизации";

	internal override string IrreversibleSterilizationDescription => "Пока настройка включена, отмена стерилизации у отдельных животных запрещена. Администраторы по-прежнему могут сбросить стерилизацию у всех животных сразу.";

	internal override string Enabled => "Включено";

	internal override string Disabled => "Выключено";

	internal override string ShortcutName => "Назначение клавиши";

	internal override string ShortcutDescription => "Наведи прицел на приручённое животное и нажми эту клавишу или сочетание.";

	internal override string SterilizationEffectsName => "Эффекты стерилизации";

	internal override string SterilizationEffectsDescription => "Воспроизводить звук и визуальные эффекты при стерилизации животного или её отмене.";

	internal override string ResetName => "Сброс стерилизации";

	internal override string ResetDescription => "Снять статус стерилизации со всех отмеченных животных текущего мира.";

	internal override string ResetButton => "Отменить стерилизацию у всех";

	internal override string CleanupName => "Удаление данных мода";

	internal override string CleanupDescription => "Удалить все данные мода из сохранения текущего мира. Запускай очистку без подключённых игроков. Проследи, чтобы никто не подключался до окончания очистки - мод не блокирует подключения. Для завершения сохрани и перезагрузи мир. После этого мод можно удалить.";

	internal override string CleanupButton => "Удалить данные мода из мира";

	internal override string CleanupPlayersConnected => "Для очистки нужно, чтобы все остальные игроки отключились";

	internal override string CleanupCompleted => "Данные мода удалены. Сохрани мир, чтобы записать изменения";

	internal override string ChangePending => "Изменение уже выполняется. Повтори после завершения.";

	internal override string TargetUnavailable => "Не удалось изменить статус животного. Подойди ближе и попробуй снова.";

	internal override string AlreadySterile => "Животное уже стерилизовано.";

	internal override string AlreadyFertile => "Размножение уже разрешено.";

	internal override string ChangeUnconfirmed => "Не удалось подтвердить изменение для животного.";

	internal override string Sterilized => "Животное стерилизовано";

	internal override string FertileAgain => "Животное снова фертильно";

	internal override string FertilityRestorationBlocked => "Восстановление фертильности запрещено админом";

	internal override string ResetRunning => "Сброс стерилизации уже выполняется.";

	internal override string ResetStarted => "Снимаем стерилизацию с животных...";

	internal override Plural ResetResult => MakePlural("Стерилизация снята у {0} животных за {1:0.00}с", null, "Стерилизация снята у {0} животного за {1:0.00}с");

	internal override string ResetUnconfirmed => " (не подтверждено снятие у {0})";
}
internal abstract class TextResources
{
	internal abstract PluralRules PluralRules { get; }

	internal abstract string SterileStatus { get; }

	internal abstract string SterilizeHint { get; }

	internal abstract string IrreversibleSterilizationHint { get; }

	internal abstract string RestoreFertilityHint { get; }

	internal abstract string ModActivationCategory { get; }

	internal abstract string PersonalSettingsCategory { get; }

	internal abstract string AdministrationCategory { get; }

	internal abstract string EnabledName { get; }

	internal abstract string EnabledDescription { get; }

	internal abstract string IrreversibleSterilizationName { get; }

	internal abstract string IrreversibleSterilizationDescription { get; }

	internal abstract string Enabled { get; }

	internal abstract string Disabled { get; }

	internal abstract string ShortcutName { get; }

	internal abstract string ShortcutDescription { get; }

	internal abstract string SterilizationEffectsName { get; }

	internal abstract string SterilizationEffectsDescription { get; }

	internal abstract string ResetName { get; }

	internal abstract string ResetDescription { get; }

	internal abstract string ResetButton { get; }

	internal abstract string CleanupName { get; }

	internal abstract string CleanupDescription { get; }

	internal abstract string CleanupButton { get; }

	internal abstract string CleanupPlayersConnected { get; }

	internal abstract string CleanupCompleted { get; }

	internal abstract string ChangePending { get; }

	internal abstract string TargetUnavailable { get; }

	internal abstract string AlreadySterile { get; }

	internal abstract string AlreadyFertile { get; }

	internal abstract string ChangeUnconfirmed { get; }

	internal abstract string Sterilized { get; }

	internal abstract string FertileAgain { get; }

	internal abstract string FertilityRestorationBlocked { get; }

	internal abstract string ResetRunning { get; }

	internal abstract string ResetStarted { get; }

	internal abstract Plural ResetResult { get; }

	internal abstract string ResetUnconfirmed { get; }

	protected Plural MakePlural(string other, string zero = null, string one = null, string two = null, string few = null, string many = null)
	{
		return new Plural(PluralRules, other, zero, one, two, few, many);
	}
}
internal sealed class TurkishTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new OneOrOtherPluralRules();

	internal override string SterileStatus => "Kısırlaştırıldı";

	internal override string SterilizeHint => "Kısırlaştır";

	internal override string IrreversibleSterilizationHint => "Kısırlaştır (geri alınamaz)";

	internal override string RestoreFertilityHint => "Üreme yetisini geri kazandır";

	internal override string ModActivationCategory => "Modu Etkinleştirme";

	internal override string PersonalSettingsCategory => "Kişisel Ayarlar";

	internal override string AdministrationCategory => "Yönetim";

	internal override string EnabledName => "Modu etkinleştir";

	internal override string EnabledDescription => "Kayıtlı üreme kısıtlamalarını uygula. Çok oyunculu oyunda bu ayarı sunucu belirler.";

	internal override string IrreversibleSterilizationName => "Kısırlaştırmanın kalıcılığı";

	internal override string IrreversibleSterilizationDescription => "Bu ayar açıkken tek tek hayvanların üreme yetisi geri kazandırılamaz. Yöneticiler tüm hayvanların üreme yetisini bir kerede geri kazandırabilir.";

	internal override string Enabled => "Etkin";

	internal override string Disabled => "Devre dışı";

	internal override string ShortcutName => "Tuş ataması";

	internal override string ShortcutDescription => "Evcilleştirilmiş bir hayvanı hedef al ve bu tuşa veya tuş kombinasyonuna bas.";

	internal override string SterilizationEffectsName => "Kısırlaştırma efektleri";

	internal override string SterilizationEffectsDescription => "Hayvan kısırlaştırıldığında veya üreme yetisini geri kazandığında ses ve görsel efektleri oynat.";

	internal override string ResetName => "Kısırlaştırmayı geri alma";

	internal override string ResetDescription => "Mevcut dünyadaki tüm kısırlaştırılmış hayvanların üreme yetisini geri kazandır.";

	internal override string ResetButton => "Tüm kısırlaştırmaları kaldır";

	internal override string CleanupName => "Mod verilerinin silinmesi";

	internal override string CleanupDescription => "Mevcut dünyanın kayıt dosyasından tüm mod verilerini kaldır. Temizliğe başka oyuncu bağlı değilken başla. Mod bağlantıları engellemediği için temizlik bitene kadar kimsenin katılmadığından emin ol. İşlemi tamamlamak için dünyayı kaydet ve yeniden yükle. Bundan sonra modu kaldırabilirsin.";

	internal override string CleanupButton => "Mod verilerini dünyadan kaldır";

	internal override string CleanupPlayersConnected => "Temizliğe başlamak için diğer tüm oyuncuların bağlantıyı kesmesi gerekir";

	internal override string CleanupCompleted => "Mod verileri kaldırıldı. Değişiklikleri korumak için dünyayı kaydet";

	internal override string ChangePending => "Bir değişiklik zaten yapılıyor. İşlem bitince tekrar dene.";

	internal override string TargetUnavailable => "Hayvanın durumu değiştirilemedi. Yaklaş ve tekrar dene.";

	internal override string AlreadySterile => "Bu hayvan zaten kısırlaştırılmış.";

	internal override string AlreadyFertile => "Bu hayvan zaten üreyebiliyor.";

	internal override string ChangeUnconfirmed => "Bu hayvanın üreme durumundaki değişiklik doğrulanamadı.";

	internal override string Sterilized => "Hayvan kısırlaştırıldı";

	internal override string FertileAgain => "Hayvan yeniden üreyebilir";

	internal override string FertilityRestorationBlocked => "Yönetici üreme yetisini geri kazandırmayı devre dışı bıraktı";

	internal override string ResetRunning => "Hayvanların üreme yetisi zaten geri kazandırılıyor.";

	internal override string ResetStarted => "Hayvanların üreme yetisi geri kazandırılıyor...";

	internal override Plural ResetResult => MakePlural("{0} hayvanın üreme yetisi {1:0.00} saniyede geri kazandırıldı");

	internal override string ResetUnconfirmed => " ({0} doğrulanamadı)";
}
internal sealed class UkrainianTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new EastSlavicPluralRules();

	internal override string SterileStatus => "Стерилізовано";

	internal override string SterilizeHint => "Стерилізувати";

	internal override string IrreversibleSterilizationHint => "Стерилізувати (незворотно)";

	internal override string RestoreFertilityHint => "Відновити фертильність";

	internal override string ModActivationCategory => "Увімкнення мода";

	internal override string PersonalSettingsCategory => "Індивідуальні налаштування";

	internal override string AdministrationCategory => "Адміністрування";

	internal override string EnabledName => "Увімкнути мод";

	internal override string EnabledDescription => "Застосовувати збережені обмеження на розмноження. У багатокористувацькій грі цей параметр визначає сервер.";

	internal override string IrreversibleSterilizationName => "Незворотність стерилізації";

	internal override string IrreversibleSterilizationDescription => "Поки цей параметр увімкнено, скасувати стерилізацію окремої тварини неможливо. Адміністратори можуть відновити фертильність усіх тварин одразу.";

	internal override string Enabled => "Увімкнено";

	internal override string Disabled => "Вимкнено";

	internal override string ShortcutName => "Призначення клавіші";

	internal override string ShortcutDescription => "Наведи приціл на приручену тварину й натисни цю клавішу або комбінацію клавіш.";

	internal override string SterilizationEffectsName => "Ефекти стерилізації";

	internal override string SterilizationEffectsDescription => "Відтворювати звукові й візуальні ефекти під час стерилізації тварини або відновлення її фертильності.";

	internal override string ResetName => "Скасування стерилізації";

	internal override string ResetDescription => "Відновити фертильність усіх стерилізованих тварин у поточному світі.";

	internal override string ResetButton => "Зняти стерилізацію в усіх";

	internal override string CleanupName => "Видалення даних мода";

	internal override string CleanupDescription => "Видалити всі дані мода зі збереження поточного світу. Починай очищення, лише якщо жоден інший гравець не підключений. Стеж, щоб ніхто не приєднався до завершення очищення, оскільки мод не блокує підключення. Щоб завершити очищення, збережи та перезавантаж світ. Після цього мод можна видалити.";

	internal override string CleanupButton => "Видалити дані мода зі світу";

	internal override string CleanupPlayersConnected => "Для очищення всі інші гравці мають від'єднатися";

	internal override string CleanupCompleted => "Дані мода видалено. Збережи світ, щоб записати зміни";

	internal override string ChangePending => "Зміна вже триває. Спробуй ще раз після завершення.";

	internal override string TargetUnavailable => "Не вдалося змінити стан тварини. Підійди ближче й спробуй ще раз.";

	internal override string AlreadySterile => "Цю тварину вже стерилізовано.";

	internal override string AlreadyFertile => "Ця тварина вже може розмножуватися.";

	internal override string ChangeUnconfirmed => "Не вдалося підтвердити зміну для цієї тварини.";

	internal override string Sterilized => "Тварину стерилізовано";

	internal override string FertileAgain => "Тварина знову фертильна";

	internal override string FertilityRestorationBlocked => "Адміністратор заборонив відновлення фертильності";

	internal override string ResetRunning => "Відновлення фертильності вже триває.";

	internal override string ResetStarted => "Відновлюємо фертильність тварин...";

	internal override Plural ResetResult => MakePlural("Фертильність відновлено у {0} тварин за {1:0.00}с", null, "Фертильність відновлено у {0} тварини за {1:0.00}с");

	internal override string ResetUnconfirmed => " (не підтверджено відновлення у {0})";
}
internal sealed class ChineseTextResources : TextResources
{
	internal override PluralRules PluralRules { get; } = new InvariantPluralRules();

	internal override string SterileStatus => "已絕育";

	internal override string SterilizeHint => "絕育";

	internal override string IrreversibleSterilizationHint => "絕育(不可逆)";

	internal override string RestoreFertilityHint => "恢復繁殖能力";

	internal override string ModActivationCategory => "模組啟用";

	internal override string PersonalSettingsCategory => "個人設定";

	internal override string AdministrationCategory => "管理";

	internal override string EnabledName => "啟用模組";

	internal override string EnabledDescription => "套用已儲存的繁殖限制。多人遊戲中,此設定由伺服器控制。";

	internal override string IrreversibleSterilizationName => "絕育不可逆性";

	internal override string IrreversibleSterilizationDescription => "啟用此設定時,無法恢復個別動物的繁殖能力。管理員仍可一次恢復所有動物的繁殖能力。";

	internal override string Enabled => "已啟用";

	internal override string Disabled => "已停用";

	internal override string ShortcutName => "按鍵設定";

	internal override string ShortcutDescription => "瞄準已馴服的動物,再按下此按鍵或組合鍵。";

	internal override string SterilizationEffectsName => "絕育效果";

	internal override string SterilizationEffectsDescription => "將動物絕育或恢復其繁殖能力時,播放音效與視覺效果。";

	internal override string ResetName => "解除絕育狀態";

	internal override string ResetDescription => "恢復目前世界中所有已絕育動物的繁殖能力。";

	internal override string ResetButton => "解除所有動物的絕育狀態";

	internal override string CleanupName => "模組資料清除";

	internal override string CleanupDescription => "從目前世界的存檔中移除所有模組資料。請在沒有其他玩家連線時開始清除。請確保清除完成前無人加入,因為模組不會阻擋連線。最後請儲存並重新載入世界,之後就可以解除安裝模組。";

	internal override string CleanupButton => "清除世界中的模組資料";

	internal override string CleanupPlayersConnected => "請等所有其他玩家離線後再清除";

	internal override string CleanupCompleted => "已清除模組資料,請儲存世界以保留變更";

	internal override string ChangePending => "正在處理變更,請在完成後再試一次。";

	internal override string TargetUnavailable => "無法變更這隻動物的狀態。請靠近後再試一次。";

	internal override string AlreadySterile => "這隻動物已經絕育。";

	internal override string AlreadyFertile => "這隻動物已經可以繁殖。";

	internal override string ChangeUnconfirmed => "無法確認這隻動物的狀態是否已變更。";

	internal override string Sterilized => "動物已絕育";

	internal override string FertileAgain => "動物已恢復繁殖能力";

	internal override string FertilityRestorationBlocked => "管理員已停用繁殖能力恢復功能";

	internal override string ResetRunning => "正在重設絕育狀態。";

	internal override string ResetStarted => "正在恢復動物的繁殖能力……";

	internal override Plural ResetResult => MakePlural("已在 {1:0.00} 秒內恢復 {0} 隻動物的繁殖能力");

	internal override string ResetUnconfirmed => "(有 {0} 隻尚未確認)";
}
internal enum NetworkCommand : byte
{
	AskSettings = 1,
	Settings,
	SetEnabled,
	Toggle,
	ResetAll,
	OwnerWrites,
	LocalizedNotice,
	SterilityChangeEffect,
	SetIrreversibleSterilization
}
internal static class NetworkConfig
{
	internal const string RpcName = "rehallowed.OffWithTheirNuts.control";

	internal const int MaxBatch = 128;

	internal const int TargetWireSize = 12;

	internal const int MaxPacketSize = 4096;

	internal const double ChangeTimeout = 8.0;

	internal const double ResendInterval = 0.65;
}
internal static class NetworkSterilityWrites
{
	internal struct TargetWrite
	{
		internal readonly ZDOID Id;

		internal long LastOwner;

		internal ushort LastRevision;

		internal double ResendAt;

		internal TargetWrite(ZDOID id)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			this = default(TargetWrite);
			Id = id;
		}
	}

	internal sealed class ChangeResult
	{
		internal int Changed;

		internal int Missing;

		internal int TimedOut;

		internal int Unconfirmed => Missing + TimedOut;
	}

	internal static IEnumerator ApplyChanges(ZNet network, List<TargetWrite> remaining, bool requestedState, ChangeResult result)
	{
		if (remaining.Count == 0)
		{
			yield break;
		}
		double timeoutAt = Time.realtimeSinceStartupAsDouble + 8.0;
		double expiresAt = network.GetTimeSeconds() + 8.0;
		WaitForSecondsRealtime wait = new WaitForSecondsRealtime(0.1f);
		Dictionary<ZNetPeer, List<TargetWrite>> byOwner = new Dictionary<ZNetPeer, List<TargetWrite>>();
		while (remaining.Count > 0)
		{
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			ProcessPendingWrites(network, remaining, requestedState, result, byOwner, realtimeSinceStartupAsDouble);
			SendQueuedWrites(byOwner, requestedState, expiresAt);
			if (remaining.Count == 0 || realtimeSinceStartupAsDouble >= timeoutAt)
			{
				break;
			}
			yield return wait;
		}
		result.TimedOut += remaining.Count;
	}

	private static void ProcessPendingWrites(ZNet network, List<TargetWrite> remaining, bool requestedState, ChangeResult result, Dictionary<ZNetPeer, List<TargetWrite>> byOwner, double now)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		for (int num = remaining.Count - 1; num >= 0; num--)
		{
			TargetWrite write = remaining[num];
			ZDO zDO = ZDOMan.instance.GetZDO(write.Id);
			if (zDO == null)
			{
				result.Missing++;
				remaining.RemoveAt(num);
			}
			else
			{
				bool flag = ZdoSterilityOperations.IsSterile(zDO) == requestedState;
				if (!flag && !zDO.IsOwner() && zDO.HasOwner())
				{
					if (TryQueueOwnerWrite(network, zDO, ref write, byOwner, now))
					{
						remaining[num] = write;
					}
				}
				else
				{
					if (!flag)
					{
						ZdoSterilityOperations.SetSterility(zDO, requestedState);
					}
					result.Changed++;
					remaining.RemoveAt(num);
				}
			}
		}
	}

	private static bool TryQueueOwnerWrite(ZNet network, ZDO zdo, ref TargetWrite write, Dictionary<ZNetPeer, List<TargetWrite>> byOwner, double now)
	{
		long owner = zdo.GetOwner();
		ushort ownerRevision = zdo.OwnerRevision;
		if (write.LastOwner == owner && write.LastRevision == ownerRevision && now < write.ResendAt)
		{
			return false;
		}
		ZNetPeer peer = network.GetPeer(owner);
		if (peer == null || !peer.IsReady())
		{
			return false;
		}
		write.LastOwner = owner;
		write.LastRevision = ownerRevision;
		write.ResendAt = now + 0.65;
		if (!byOwner.TryGetValue(peer, out var value))
		{
			value = new List<TargetWrite>();
			byOwner.Add(peer, value);
		}
		value.Add(write);
		return true;
	}

	private static void SendQueuedWrites(Dictionary<ZNetPeer, List<TargetWrite>> byOwner, bool requestedState, double expiresAt)
	{
		foreach (KeyValuePair<ZNetPeer, List<TargetWrite>> item in byOwner)
		{
			if (item.Value.Count != 0)
			{
				SendOwnerWrites(item.Key, item.Value, requestedState, expiresAt);
				item.Value.Clear();
			}
		}
	}

	private static void SendOwnerWrites(ZNetPeer peer, List<TargetWrite> writes, bool requestedState, double expiresAt)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < writes.Count; i += 128)
		{
			int num = Math.Min(128, writes.Count - i);
			ZPackage val = new ZPackage();
			val.Write((byte)6);
			val.Write(requestedState);
			val.Write(expiresAt);
			val.Write(num);
			for (int j = i; j < i + num; j++)
			{
				val.Write(writes[j].Id);
				val.Write(writes[j].LastRevision);
			}
			peer.m_rpc.Invoke("rehallowed.OffWithTheirNuts.control", new object[1] { val });
		}
	}

	internal static void ApplyOwnerWrites(ZNet network, ZPackage packet)
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		if (packet.Size() - packet.GetPos() < 13)
		{
			return;
		}
		bool requestedState = packet.ReadBool();
		double num = packet.ReadDouble();
		int num2 = packet.ReadInt();
		if (num2 < 1 || num2 > 128 || ZDOMan.instance == null || network.GetTimeSeconds() > num || packet.Size() - packet.GetPos() != num2 * 14)
		{
			return;
		}
		for (int i = 0; i < num2; i++)
		{
			ZDOID val = packet.ReadZDOID();
			ushort num3 = packet.ReadUShort();
			ZDO zDO = ZDOMan.instance.GetZDO(val);
			if (zDO != null && zDO.IsOwner() && zDO.OwnerRevision == num3)
			{
				ZdoSterilityOperations.SetSterility(zDO, requestedState);
				ZDOMan.instance.ForceSendZDO(val);
			}
		}
	}
}
internal sealed class ServerSync
{
	[HarmonyPatch(typeof(ZNet), "Awake")]
	private static class WorldAwakePatch
	{
		private static void Postfix(ZNet __instance)
		{
			OffWithTheirNutsPlugin.ActiveServerSync?.OpenWorld(__instance);
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnDestroy")]
	private static class WorldDestroyPatch
	{
		private static void Prefix(ZNet __instance)
		{
			ServerSync activeServerSync = OffWithTheirNutsPlugin.ActiveServerSync;
			if (activeServerSync != null && activeServerSync.IsCurrentNetwork(__instance))
			{
				activeServerSync.CloseWorld();
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	private static class PeerConnectionPatch
	{
		private static void Postfix(ZNet __instance, ZNetPeer __0)
		{
			ServerSync activeServerSync = OffWithTheirNutsPlugin.ActiveServerSync;
			if (activeServerSync != null && activeServerSync.IsCurrentNetwork(__instance))
			{
				activeServerSync.RegisterPeer(__0);
			}
		}
	}

	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	private static class PeerInfoPatch
	{
		private static void Postfix(ZNet __instance, ZRpc __0)
		{
			ServerSync activeServerSync = OffWithTheirNutsPlugin.ActiveServerSync;
			if (activeServerSync != null && activeServerSync.IsCurrentNetwork(__instance) && !__instance.IsServer())
			{
				ZNetPeer serverPeer = __instance.GetServerPeer();
				if (serverPeer != null && serverPeer.m_rpc == __0)
				{
					Send(serverPeer, NetworkCommand.AskSettings);
				}
			}
		}
	}

	private readonly ConfigEntry<bool> enabledSetting;

	private readonly ConfigEntry<bool> irreversibleSterilizationSetting;

	private readonly Action refreshHotkey;

	private readonly Action onWorldClosed;

	private readonly Action<ZNetPeer, ZDOID, bool> startChange;

	private readonly Action<ZNetPeer> startReset;

	private readonly Action<PlayerNotice> showNotice;

	private readonly Action<ZDOID, bool> playSterilityChangeEffect;

	private ZNet network;

	private bool canManageWorld;

	private bool irreversibleSterilization;

	internal ZNet CurrentNetwork => network;

	internal bool HasWorld => network != null;

	internal bool SettingsReady { get; private set; }

	internal bool RestrictionsEnabled { get; private set; }

	internal bool RestrictionsActive
	{
		get
		{
			if (SettingsReady)
			{
				return RestrictionsEnabled;
			}
			return false;
		}
	}

	internal bool Enabled
	{
		get
		{
			if (!((Object)(object)network == (Object)null))
			{
				return RestrictionsEnabled;
			}
			return enabledSetting.Value;
		}
	}

	internal bool IsIrreversibleSterilizationEnabled
	{
		get
		{
			if (!((Object)(object)network == (Object)null))
			{
				return irreversibleSterilization;
			}
			return irreversibleSterilizationSetting.Value;
		}
	}

	internal bool CanChangeWorldSettings
	{
		get
		{
			if (!((Object)(object)network == (Object)null))
			{
				return CanReset;
			}
			return true;
		}
	}

	internal bool CanReset
	{
		get
		{
			if ((Object)(object)network != (Object)null)
			{
				if (!network.IsServer())
				{
					if (SettingsReady)
					{
						return canManageWorld;
					}
					return false;
				}
				return true;
			}
			return false;
		}
	}

	internal ServerSync(ConfigEntry<bool> enabledSetting, ConfigEntry<bool> irreversibleSterilizationSetting, Action refreshHotkey, Action onWorldClosed, Action<ZNetPeer, ZDOID, bool> startChange, Action<ZNetPeer> startReset, Action<PlayerNotice> showNotice, Action<ZDOID, bool> playSterilityChangeEffect)
	{
		this.enabledSetting = enabledSetting;
		this.irreversibleSterilizationSetting = irreversibleSterilizationSetting;
		this.refreshHotkey = refreshHotkey;
		this.onWorldClosed = onWorldClosed;
		this.startChange = startChange;
		this.startReset = startReset;
		this.showNotice = showNotice;
		this.playSterilityChangeEffect = playSterilityChangeEffect;
	}

	private void OpenWorld(ZNet current)
	{
		CloseWorld();
		network = current;
		SettingsReady = current.IsServer();
		RestrictionsEnabled = SettingsReady && enabledSetting.Value;
		irreversibleSterilization = SettingsReady && irreversibleSterilizationSetting.Value;
		refreshHotkey();
	}

	internal void CloseWorld()
	{
		network = null;
		SettingsReady = false;
		RestrictionsEnabled = false;
		canManageWorld = false;
		irreversibleSterilization = false;
		onWorldClosed();
	}

	internal void RequestEnabled(bool requested)
	{
		if ((Object)(object)network == (Object)null || network.IsServer())
		{
			enabledSetting.Value = requested;
			return;
		}
		SendToServer(NetworkCommand.SetEnabled, delegate(ZPackage package)
		{
			package.Write(requested);
		});
	}

	internal void RequestIrreversibleSterilization(bool requested)
	{
		if ((Object)(object)network == (Object)null || network.IsServer())
		{
			irreversibleSterilizationSetting.Value = requested;
			return;
		}
		SendToServer(NetworkCommand.SetIrreversibleSterilization, delegate(ZPackage package)
		{
			package.Write(requested);
		});
	}

	internal void RefreshWorldSettings()
	{
		if ((Object)(object)network != (Object)null && network.IsServer())
		{
			RestrictionsEnabled = enabledSetting.Value;
			irreversibleSterilization = irreversibleSterilizationSetting.Value;
			PublishSettings();
			refreshHotkey();
		}
	}

	internal void RequestChange(ZDOID id, bool requested)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		SendToServer(NetworkCommand.Toggle, delegate(ZPackage package)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			package.Write(id);
			package.Write(requested);
		});
	}

	internal void RequestReset()
	{
		if (network.IsServer())
		{
			startReset(null);
		}
		else
		{
			SendToServer(NetworkCommand.ResetAll);
		}
	}

	private void RegisterPeer(ZNetPeer peer)
	{
		peer.m_rpc.Register<ZPackage>("rehallowed.OffWithTheirNuts.control", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage package)
		{
			Receive(peer, package);
		});
	}

	private void Receive(ZNetPeer peer, ZPackage package)
	{
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)network == (Object)null || package == null || package.Size() < 1 || package.Size() > 4096 || !peer.IsReady() || network.GetPeer(peer.m_uid) != peer)
		{
			return;
		}
		try
		{
			NetworkCommand networkCommand = (NetworkCommand)package.ReadByte();
			int num = package.Size() - package.GetPos();
			bool num2 = network.IsServer();
			bool flag = !num2 && peer.m_server && network.GetServerPeer() == peer;
			if (num2)
			{
				switch (networkCommand)
				{
				case NetworkCommand.AskSettings:
					if (num == 0)
					{
						SendSettings(peer);
					}
					break;
				case NetworkCommand.SetEnabled:
					if (num == 1 && IsWorldAdmin(peer))
					{
						enabledSetting.Value = package.ReadBool();
					}
					break;
				case NetworkCommand.SetIrreversibleSterilization:
					if (num == 1 && IsWorldAdmin(peer))
					{
						irreversibleSterilizationSetting.Value = package.ReadBool();
					}
					break;
				case NetworkCommand.Toggle:
					if (num == 13)
					{
						startChange(peer, package.ReadZDOID(), package.ReadBool());
					}
					break;
				case NetworkCommand.ResetAll:
					if (num == 0 && IsWorldAdmin(peer))
					{
						startReset(peer);
					}
					break;
				case NetworkCommand.Settings:
				case NetworkCommand.OwnerWrites:
				case NetworkCommand.LocalizedNotice:
				case NetworkCommand.SterilityChangeEffect:
					break;
				}
			}
			else
			{
				if (!flag)
				{
					return;
				}
				switch (networkCommand)
				{
				case NetworkCommand.Settings:
					if (num == 3)
					{
						RestrictionsEnabled = package.ReadBool();
						canManageWorld = package.ReadBool();
						irreversibleSterilization = package.ReadBool();
						SettingsReady = true;
						refreshHotkey();
					}
					break;
				case NetworkCommand.OwnerWrites:
					if (SettingsReady)
					{
						NetworkSterilityWrites.ApplyOwnerWrites(network, package);
					}
					break;
				case NetworkCommand.LocalizedNotice:
				{
					if (PlayerNotice.TryRead(package, num, out var notice))
					{
						showNotice(notice);
					}
					break;
				}
				case NetworkCommand.SterilityChangeEffect:
					if (num == 13)
					{
						playSterilityChangeEffect(package.ReadZDOID(), package.ReadBool());
					}
					break;
				case NetworkCommand.SetEnabled:
				case NetworkCommand.Toggle:
				case NetworkCommand.ResetAll:
					break;
				}
			}
		}
		catch (IOException)
		{
		}
	}

	private void SendToServer(NetworkCommand command, Action<ZPackage> fill = null)
	{
		ZNet obj = network;
		ZNetPeer val = ((obj != null) ? obj.GetServerPeer() : null);
		if (val != null && val.IsReady())
		{
			Send(val, command, fill);
		}
	}

	private static void Send(ZNetPeer peer, NetworkCommand command, Action<ZPackage> fill = null)
	{
		//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((byte)command);
		fill?.Invoke(val);
		peer.m_rpc.Invoke("rehallowed.OffWithTheirNuts.control", new object[1] { val });
	}

	internal bool IsWorldAdmin(ZNetPeer peer)
	{
		if ((Object)(object)network != (Object)null && network.IsServer())
		{
			if (peer != null)
			{
				return network.IsAdmin(peer.m_socket.GetHostName());
			}
			return true;
		}
		return false;
	}

	private void PublishSettings()
	{
		foreach (ZNetPeer peer in network.GetPeers())
		{
			if (peer.IsReady())
			{
				SendSettings(peer);
			}
		}
	}

	private void SendSettings(ZNetPeer peer)
	{
		Send(peer, NetworkCommand.Settings, delegate(ZPackage package)
		{
			package.Write(RestrictionsEnabled);
			package.Write(IsWorldAdmin(peer));
			package.Write(irreversibleSterilization);
		});
	}

	internal static ZDO GetRequestingPlayer(ZNetPeer requester)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		ZDO zDO = ZDOMan.instance.GetZDO(requester.m_characterID);
		if (zDO == null || zDO.GetOwner() != requester.m_uid)
		{
			return null;
		}
		return zDO;
	}

	internal void PublishSterilityChangeEffect(ZDOID id, bool isSterile)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)network == (Object)null || !network.IsServer())
		{
			return;
		}
		foreach (ZNetPeer peer in network.GetPeers())
		{
			if (peer.IsReady())
			{
				Send(peer, NetworkCommand.SterilityChangeEffect, delegate(ZPackage package)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					package.Write(id);
					package.Write(isSterile);
				});
			}
		}
		playSterilityChangeEffect(id, isSterile);
	}

	internal void Notify(ZNetPeer peer, PlayerNoticeKind kind)
	{
		Notify(peer, new PlayerNotice(kind));
	}

	internal void Notify(ZNetPeer peer, PlayerNotice notice)
	{
		if (peer == null)
		{
			showNotice(notice);
		}
		else if (peer.IsReady())
		{
			Send(peer, NetworkCommand.LocalizedNotice, ((PlayerNotice)notice).Write);
		}
	}

	private bool IsCurrentNetwork(ZNet current)
	{
		return network == current;
	}
}
internal enum PlayerNoticeKind : byte
{
	ChangePending = 1,
	TargetUnavailable,
	AlreadySterile,
	AlreadyFertile,
	ChangeUnconfirmed,
	Sterilized,
	FertileAgain,
	ResetRunning,
	ResetStarted,
	ResetResult,
	FertilityRestorationBlocked
}
internal readonly struct PlayerNotice
{
	private readonly PlayerNoticeKind kind;

	private readonly int count;

	private readonly double seconds;

	private readonly int unconfirmed;

	internal PlayerNotice(PlayerNoticeKind kind)
	{
		this = default(PlayerNotice);
		this.kind = kind;
	}

	internal PlayerNotice(int count, double seconds, int unconfirmed)
	{
		kind = PlayerNoticeKind.ResetResult;
		this.count = count;
		this.seconds = seconds;
		this.unconfirmed = unconfirmed;
	}

	internal void Write(ZPackage package)
	{
		package.Write((byte)kind);
		if (kind == PlayerNoticeKind.ResetResult)
		{
			package.Write(count);
			package.Write(seconds);
			package.Write(unconfirmed);
		}
	}

	internal static bool TryRead(ZPackage package, int remaining, out PlayerNotice notice)
	{
		notice = default(PlayerNotice);
		if (remaining < 1)
		{
			return false;
		}
		PlayerNoticeKind playerNoticeKind = (PlayerNoticeKind)package.ReadByte();
		if (playerNoticeKind == PlayerNoticeKind.ResetResult)
		{
			if (remaining != 17)
			{
				return false;
			}
			int num = package.ReadInt();
			double num2 = package.ReadDouble();
			int num3 = package.ReadInt();
			if (num < 0 || num2 < 0.0 || double.IsNaN(num2) || double.IsInfinity(num2) || num3 < 0)
			{
				return false;
			}
			notice = new PlayerNotice(num, num2, num3);
			return true;
		}
		if (remaining != 1 || !Enum.IsDefined(typeof(PlayerNoticeKind), playerNoticeKind))
		{
			return false;
		}
		notice = new PlayerNotice(playerNoticeKind);
		return true;
	}

	internal string Format(TextResources textResources)
	{
		return kind switch
		{
			PlayerNoticeKind.ChangePending => textResources.ChangePending, 
			PlayerNoticeKind.TargetUnavailable => textResources.TargetUnavailable, 
			PlayerNoticeKind.AlreadySterile => textResources.AlreadySterile, 
			PlayerNoticeKind.AlreadyFertile => textResources.AlreadyFe