Decompiled source of Better Beehives v1.2.3

plugins/BetterBeehives.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BetterBeehives.Compatibility;
using BetterBeehives.Data;
using BetterBeehives.Scripts;
using HarmonyLib;
using JetBrains.Annotations;
using LazyVikings;
using Microsoft.CodeAnalysis;
using SeedBed;
using SeedBed.Functions;
using ServerSync;
using TMPro;
using UnityEngine;
using ZenBeehive;

[assembly: AssemblyProduct("BetterBeehives")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCompany("BetterBeehives")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyTitle("BetterBeehives")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<bfc8511e-5ea9-4e8e-9611-2581564a31d3>Embedded]
	internal sealed class <bfc8511e-5ea9-4e8e-9611-2581564a31d3>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<bfc8511e-5ea9-4e8e-9611-2581564a31d3>Embedded]
	[CompilerGenerated]
	internal sealed class <7fd18e28-3a80-47a0-ad89-44d3c18f95ae>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <7fd18e28-3a80-47a0-ad89-44d3c18f95ae>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <7fd18e28-3a80-47a0-ad89-44d3c18f95ae>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<bfc8511e-5ea9-4e8e-9611-2581564a31d3>Embedded]
	[CompilerGenerated]
	internal sealed class <490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace BetterBeehives
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("maxfoxgaming.betterbeehives", "BetterBeehives", "1.2.3")]
	public class Main : BaseUnityPlugin
	{
		public const string PluginGUID = "maxfoxgaming.betterbeehives";

		public const string PluginName = "BetterBeehives";

		public const string PluginVersion = "1.2.3";

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static Main instance;

		public static Harmony harmony = new Harmony("maxfoxgaming.betterbeehives");

		public static readonly string ModPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static ManualLogSource Log;

		public static bool ZenBeehivePatchDone = false;

		public static bool SeedBedPatchDone = false;

		public static bool LazyVikingsPatchDone = false;

		public static readonly string Queen = "QueenBee";

		public static readonly string Jelly = "RoyalJelly";

		public void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			instance = this;
			ConfigManager.CreateConfigValues((BaseUnityPlugin)(object)this);
			Harmony val = harmony;
			if (val != null)
			{
				val.PatchAll();
			}
			if (ZenBeehiveCompatibility.Enabled && !ZenBeehivePatchDone)
			{
				ZenBeehivePatchDone = ZenBeehiveCompatibility.DoCompatibilityPatching(val);
			}
			if (SeedBedCompatibility.Enabled && !SeedBedPatchDone)
			{
				SeedBedPatchDone = SeedBedCompatibility.DoCompatibilityPatching(val);
			}
			if (LazyVikingsCompatibility.Enabled && !LazyVikingsPatchDone)
			{
				LazyVikingsPatchDone = LazyVikingsCompatibility.DoCompatibilityPatching(val);
			}
		}

		public void OnDestroy()
		{
			Harmony val = harmony;
			if (val != null)
			{
				val.UnpatchSelf();
			}
			instance = null;
		}

		[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(2)]
		public static Main GetInstance()
		{
			return instance;
		}

		public static void LogMessage(string message)
		{
			if (ConfigManager.DebugLogging.Value)
			{
				Log.LogMessage((object)message);
			}
		}
	}
}
namespace BetterBeehives.Scripts
{
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(2)]
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	public class BeePollinate : MonoBehaviour
	{
		public ZNetView m_nview;

		public GameObject m_beeEffect;

		public bool m_isSeedBed = false;

		public void Awake()
		{
			m_nview = ((Component)this).gameObject.GetComponent<ZNetView>();
			m_isSeedBed = ((Object)((Component)this).gameObject).name.NoClone() == "BSB_SeedBed";
			if (!((Object)(object)m_nview == (Object)null) && m_nview.GetZDO() != null)
			{
				m_beeEffect = Object.Instantiate<GameObject>(ZNetScene.instance.GetPrefab("piece_beehive").GetComponent<Beehive>().m_beeEffect, ((Component)this).transform);
				((MonoBehaviour)this).InvokeRepeating("SlowUpdate", 0f, Random.Range(8f, 10f));
			}
		}

		public void SlowUpdate()
		{
			if (ConfigManager.NearbyPlantGrowthChance.Value != 0f && ConfigManager.NearbyPlantGrowthRange.Value != 0f)
			{
				bool flag = Random.Range(0f, 1f) < ConfigManager.BeeDensity.Value;
				bool flag2 = CheckSeedBed();
				m_beeEffect.SetActive(flag && flag2 && HasActiveHiveNearby());
			}
		}

		public bool HasActiveHiveNearby()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(((Component)this).transform.position, ConfigManager.NearbyPlantGrowthRange.Value);
			Collider[] array2 = array;
			foreach (Collider val in array2)
			{
				Beehive component = ((Component)((Component)val).transform.root).gameObject.GetComponent<Beehive>();
				if (!((Object)(object)component == (Object)null) && component.ShouldActivateEffect())
				{
					return true;
				}
			}
			return false;
		}

		public bool CheckSeedBed()
		{
			if (SeedBedCompatibility.Enabled && Main.SeedBedPatchDone && m_isSeedBed)
			{
				return ((Component)this).gameObject.IsGerminatingOrFinished() && ((Component)this).gameObject.HasCorrectPlant();
			}
			return true;
		}
	}
}
namespace BetterBeehives.Patch
{
	internal class Beehive_Extract
	{
		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
		[HarmonyPatch(typeof(Beehive), "RPC_Extract")]
		[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
		public static class Beehive_RPC_Extract_Patches
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_010a: Expected O, but got Unknown
				//IL_0112: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Expected O, but got Unknown
				//IL_0124: Unknown result type (might be due to invalid IL or missing references)
				//IL_012e: Expected O, but got Unknown
				Main.LogMessage("Applying transpiler patch to Beehive.RPC_Extract()");
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				if (!typeof(Beehive).TryGetMethod("ResetLevel", out var method))
				{
					return instructions;
				}
				if (!typeof(Beehive_RPC_Extract_Patches).TryGetMethod("DropQueenBeeAndJelly", out var method2))
				{
					return instructions;
				}
				int num = -1;
				for (int i = 0; i < list.Count - 1; i++)
				{
					if (!(list[i].opcode != OpCodes.Ldarg_0) && !(list[i + 1].opcode != OpCodes.Call) && !(list[i + 1].operand as MethodInfo != method))
					{
						num = i;
						break;
					}
				}
				if (num == -1)
				{
					return instructions;
				}
				List<CodeInstruction> collection = new List<CodeInstruction>
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Ldloc_0, (object)null),
					new CodeInstruction(OpCodes.Call, (object)method2)
				};
				list.InsertRange(num, collection);
				Main.LogMessage("Patch done");
				return list.AsEnumerable();
			}

			public static void DropQueenBeeAndJelly(Beehive beehive, int __state)
			{
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0127: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0132: Unknown result type (might be due to invalid IL or missing references)
				//IL_0137: Unknown result type (might be due to invalid IL or missing references)
				//IL_013c: Unknown result type (might be due to invalid IL or missing references)
				//IL_013e: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Unknown result type (might be due to invalid IL or missing references)
				Main.LogMessage("DropQueenBeeAndJelly");
				if (ZenBeehiveCompatibility.Enabled && Main.ZenBeehivePatchDone && ((Object)((Component)beehive).gameObject).name.Replace("(Clone)", "") == "piece_beehive")
				{
					Main.LogMessage("ZenBeehive detected. Extract cancelling.");
					return;
				}
				if (!beehive.ShouldAddQueenBee(__state))
				{
					Main.LogMessage("No queen will drop.");
					return;
				}
				Vector2 val = Random.insideUnitCircle * 0.5f;
				Vector3 val2 = beehive.m_spawnPoint.position + new Vector3(val.x, 0.25f * (float)__state, val.y);
				ItemDrop component = ObjectDB.instance.GetItemPrefab(Main.Queen).GetComponent<ItemDrop>();
				Main.LogMessage("Queen Bee Dropped!");
				Object.Instantiate<ItemDrop>(component, val2, Quaternion.identity);
				ItemDrop component2 = ObjectDB.instance.GetItemPrefab(Main.Jelly).GetComponent<ItemDrop>();
				int num = 0;
				for (int i = 0; i < ConfigManager.RoyalJellyDropAttempts.Value; i++)
				{
					if (!(Random.Range(0f, 1f) > ConfigManager.RoyalJellyDropChance.Value))
					{
						num++;
						val2 += 0.25f * Vector3.up;
						Object.Instantiate<ItemDrop>(component2, val2, Quaternion.identity);
					}
				}
				Main.LogMessage("Dropping " + num + " royal jelly.");
			}
		}
	}
	internal class Beehive_IncreaseLevel
	{
		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
		[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
		[HarmonyPatch(typeof(Beehive), "IncreseLevel")]
		public static class Beehive_IncreaseLevel_Patches
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator il)
			{
				//IL_0180: Unknown result type (might be due to invalid IL or missing references)
				//IL_018a: Expected O, but got Unknown
				//IL_0192: Unknown result type (might be due to invalid IL or missing references)
				//IL_019c: Expected O, but got Unknown
				//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b5: Expected O, but got Unknown
				//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c7: Expected O, but got Unknown
				//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d9: Expected O, but got Unknown
				//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01eb: Expected O, but got Unknown
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fd: Expected O, but got Unknown
				//IL_0205: Unknown result type (might be due to invalid IL or missing references)
				//IL_020f: Expected O, but got Unknown
				//IL_0217: Unknown result type (might be due to invalid IL or missing references)
				//IL_0221: Expected O, but got Unknown
				//IL_0229: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Expected O, but got Unknown
				//IL_023c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0246: 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_0260: Unknown result type (might be due to invalid IL or missing references)
				//IL_026a: Expected O, but got Unknown
				//IL_0273: Unknown result type (might be due to invalid IL or missing references)
				//IL_027d: Expected O, but got Unknown
				Main.LogMessage("Applying transpiler patch to Beehive.IncreseLevel()");
				LocalBuilder localBuilder = il.DeclareLocal(typeof(int));
				LocalBuilder localBuilder2 = il.DeclareLocal(typeof(bool));
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				if (!typeof(Beehive).TryGetMethod("GetHoneyLevel", out var method))
				{
					return instructions;
				}
				if (!typeof(Beehive_IncreaseLevel_Patches).TryGetMethod("GrowPlants", out var method2))
				{
					return instructions;
				}
				if (!typeof(Beehive_IncreaseLevel_Patches).TryGetMethod("FillContainer", out var method3))
				{
					return instructions;
				}
				int num = -1;
				int index = list.Count - 1;
				for (int i = 2; i < list.Count; i++)
				{
					if (!(list[i - 2].opcode != OpCodes.Ldarg_0) && !(list[i - 1].opcode != OpCodes.Call) && !(list[i - 1].operand as MethodInfo != method) && !(list[i].opcode != OpCodes.Stloc_0))
					{
						num = i + 1;
						break;
					}
				}
				if (num == -1)
				{
					return instructions;
				}
				List<CodeInstruction> collection = new List<CodeInstruction>
				{
					new CodeInstruction(OpCodes.Ldloc_0, (object)null),
					new CodeInstruction(OpCodes.Stloc_S, (object)localBuilder)
				};
				List<CodeInstruction> collection2 = new List<CodeInstruction>
				{
					new CodeInstruction(OpCodes.Ldloc_0, (object)null),
					new CodeInstruction(OpCodes.Ldloc_S, (object)localBuilder),
					new CodeInstruction(OpCodes.Ceq, (object)null),
					new CodeInstruction(OpCodes.Ldc_I4_0, (object)null),
					new CodeInstruction(OpCodes.Ceq, (object)null),
					new CodeInstruction(OpCodes.Stloc_S, (object)localBuilder2),
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Ldloc_S, (object)localBuilder2),
					new CodeInstruction(OpCodes.Call, (object)method2),
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Ldloc_S, (object)localBuilder2),
					new CodeInstruction(OpCodes.Call, (object)method3)
				};
				list.InsertRange(index, collection2);
				list.InsertRange(num, collection);
				Main.LogMessage("Patch Done");
				return list;
			}

			public static void GrowPlants(Beehive __instance, bool changed)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				Main.LogMessage("GrowPlants");
				if (!changed)
				{
					Main.LogMessage("Invalid State");
					return;
				}
				if (!__instance.m_nview.IsOwner())
				{
					Main.LogMessage("Not the owner.");
					return;
				}
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					Main.LogMessage("No beehive.");
					return;
				}
				Collider[] array = Physics.OverlapSphere(gameObject.transform.position, ConfigManager.NearbyPlantGrowthRange.Value);
				Collider[] array2 = array;
				foreach (Collider val in array2)
				{
					GameObject gameObject2 = ((Component)((Component)val).transform.root).gameObject;
					HandlePlantGrowth(gameObject2);
					HandlePickableGrowth(gameObject2);
					if (SeedBedCompatibility.Enabled && Main.SeedBedPatchDone)
					{
						SeedBedCompatibility.HandleSeedBedGrowth(gameObject2);
					}
				}
			}

			public static void FillContainer(Beehive beehive, bool changed)
			{
				Main.LogMessage("FillContainer");
				if (!ZenBeehiveCompatibility.Enabled)
				{
					Main.LogMessage("ZenBeehive not enabled. Skipping.");
					return;
				}
				if (!changed)
				{
					Main.LogMessage("No change to honey level");
					return;
				}
				Container component = ((Component)beehive).gameObject.GetComponent<Container>();
				if ((Object)(object)component == (Object)null)
				{
					Main.LogMessage("Container not found.");
					return;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)beehive.m_honeyItem).name);
				GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(Main.Queen);
				GameObject itemPrefab3 = ObjectDB.instance.GetItemPrefab(Main.Jelly);
				int honeyLevel = beehive.GetHoneyLevel();
				Inventory inventory = component.GetInventory();
				inventory.SetItem(itemPrefab, honeyLevel, 0, 0);
				Main.LogMessage("Set honey level to " + honeyLevel + " in hive.");
				if (!inventory.HasItemInSlot(itemPrefab2, 1, 0) && inventory.GetItemAt(1, 0) != null)
				{
					inventory.RemoveItemAt(1, 0);
				}
				if (!inventory.HasItemInSlot(itemPrefab3, 2, 0) && inventory.GetItemAt(2, 0) != null)
				{
					inventory.RemoveItemAt(2, 0);
				}
				if (!beehive.ShouldAddQueenBee())
				{
					Main.LogMessage("Queen bee conditions not met. Not adding.");
					return;
				}
				if (!inventory.SetItem(itemPrefab2, 1, 1, 0))
				{
					Main.LogMessage("Tried to add queen bee but failed. Inventory has no room.");
					return;
				}
				Main.LogMessage("Added queen bee to internal inventory.");
				if (inventory.HasItemInSlot(itemPrefab3, 2, 0))
				{
					Main.LogMessage("Royal Jelly already present in hive. No need to add more.");
					return;
				}
				int num = 0;
				for (int i = 0; i < ConfigManager.RoyalJellyDropAttempts.Value; i++)
				{
					if (!(Random.Range(0f, 1f) > ConfigManager.RoyalJellyDropChance.Value))
					{
						num++;
					}
				}
				if (num != 0)
				{
					inventory.SetItem(itemPrefab3, num, 2, 0);
					Main.LogMessage("Added " + num + " royal jelly to container.");
				}
			}

			public static void HandlePlantGrowth(GameObject gameObject)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				if (gameObject.TryGetPlantComponent(out var plant))
				{
					float num = Random.Range(0f, 1f);
					if (num <= ConfigManager.NearbyPlantGrowthChance.Value)
					{
						string text = ((Object)gameObject).name.NoClone();
						Vector3 position = gameObject.transform.position;
						Main.LogMessage("Growing plant " + text + " at coordinate " + ((object)(Vector3)(ref position)).ToString());
						gameObject.SetGrowthEffects();
						plant.Grow();
					}
				}
			}

			public static void HandlePickableGrowth(GameObject gameObject)
			{
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				if (gameObject.TryGetPickableComponent(out var pickable) && !pickable.CanBePicked())
				{
					float num = Random.Range(0f, 1f);
					if (num <= ConfigManager.NearbyPlantGrowthChance.Value)
					{
						string text = ((Object)gameObject).name.NoClone();
						Vector3 position = gameObject.transform.position;
						Main.LogMessage("Growing plant " + text + " at coordinate " + ((object)(Vector3)(ref position)).ToString());
						gameObject.SetGrowthEffects();
						pickable.m_nview.InvokeRPC(ZNetView.Everybody, "RPC_SetPicked", new object[1] { false });
					}
				}
			}
		}
	}
	internal class ZNetScene_Awake
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		public static class ZNetScene_Awake_Patches
		{
			[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
			public static void Postfix(ZNetScene __instance)
			{
				foreach (string item in ConfigManager.NearbyPlantsGrowthList.Value)
				{
					__instance.AddBeePollinateComponent(item);
				}
				foreach (string item2 in ConfigManager.NearbyPickablesGrowthList.Value)
				{
					__instance.AddBeePollinateComponent(item2);
				}
			}
		}
	}
}
namespace BetterBeehives.Data
{
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(2)]
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	public class ConfigManager
	{
		public static ConfigSync configSync;

		public static ConfigEntry<bool> DebugLogging;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1 })]
		public static ConfigEntry<string> BeehivePrefabs;

		public static ConfigEntry<float> QueenBeeDropChance;

		public static ConfigEntry<float> RoyalJellyDropChance;

		public static ConfigEntry<int> RoyalJellyDropAttempts;

		public static ConfigEntry<float> NearbyPlantGrowthChance;

		public static ConfigEntry<float> NearbyPlantGrowthRange;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1 })]
		public static ConfigEntry<string> NearbyPlantsGrowth;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1 })]
		public static ConfigEntry<string> NearbyPickablesGrowth;

		public static ConfigEntry<float> BeeDensity;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1, 1 })]
		public static CustomSyncedValue<List<string>> BeehivePrefabsList;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1, 1 })]
		public static CustomSyncedValue<List<string>> NearbyPlantsGrowthList;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(new byte[] { 2, 1, 1 })]
		public static CustomSyncedValue<List<string>> NearbyPickablesGrowthList;

		[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
		public static void CreateConfigValues(BaseUnityPlugin plugin)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Expected O, but got Unknown
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Expected O, but got Unknown
			configSync = new ConfigSync("maxfoxgaming.betterbeehives")
			{
				DisplayName = "BetterBeehives",
				CurrentVersion = "1.2.3",
				MinimumRequiredVersion = "1.2.3"
			};
			plugin.Config.SaveOnConfigSet = true;
			DebugLogging = plugin.Config.BindServer("0. Logging", "Logs Enabled", value: false, new ConfigDescription("Whether the mod should print outputs and data to the console. Only needed for debugging.", (AcceptableValueBase)null, Array.Empty<object>()));
			BeehivePrefabs = plugin.Config.BindServer("1. Beehives", "Beehive Prefabs", "piece_beehive", new ConfigDescription("A comma separated list of build pieces that should be considered for Better Beehives.", (AcceptableValueBase)null, Array.Empty<object>()));
			QueenBeeDropChance = plugin.Config.BindServer("1. Beehives", "Queen Bee Drop Chance", 0.05f, new ConfigDescription("When the beehive has full honey level, this is the chance that a queen bee will also be collected.\nYou can still harvest with less than full honey and the resulting chance will be scaled down to match how full the hive is.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			RoyalJellyDropChance = plugin.Config.BindServer("1. Beehives", "Royal Jelly Drop Chance", 0.6f, new ConfigDescription("If a queen bee is successfully retrieved, this is the chance that you will also get royal jelly.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			RoyalJellyDropAttempts = plugin.Config.BindServer("1. Beehives", "Royal Jelly Drop Attempts", 3, new ConfigDescription("How many attempts are made to drop a piece of Royal Jelly. Each piece will haev the configured set chance to spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
			NearbyPlantGrowthChance = plugin.Config.BindServer("2. Plants", "Nearby Plants Growth Chance", 0.05f, new ConfigDescription("When the beehive ticks and generates a honey, this value determines how likely a nearby plant is to grow (per plant).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			NearbyPlantGrowthRange = plugin.Config.BindServer("2. Plants", "Nearby Plants Range", 5f, new ConfigDescription("The range around a beehive that plants grow. Spherical.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
			NearbyPlantsGrowth = plugin.Config.BindServer("2. Plants", "Nearby Growable Plants", "sapling_barley,sapling_carrot,sapling_flax,sapling_jotunpuffs,sapling_magecap,sapling_onion,sapling_turnip,sapling_seedcarrot,sapling_seedonion,sapling_seedturnip,VineAsh_sapling,VineGreen_sapling", new ConfigDescription("Player placed plants that can be grown faster by nearby beehives.", (AcceptableValueBase)null, Array.Empty<object>()));
			NearbyPickablesGrowth = plugin.Config.BindServer("2. Plants", "Nearby Growable Pickables", "Pickable_Dandelion,Pickable_Fiddlehead,Pickable_Mushroom,Pickable_Mushroom_yellow,Pickable_Mushroom_JotunPuffs,Pickable_Mushroom_Magecap,Pickable_SmokePuff,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", new ConfigDescription("Pickable items that can be regrown by nearby beehives that are not player placed crops and plants.", (AcceptableValueBase)null, Array.Empty<object>()));
			BeeDensity = plugin.Config.Bind<float>("3. Client", "Bee Density", 0.4f, new ConfigDescription("If bees are set to nearby plants, this will control how many bee particles appear around plants that are affected.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			BeehivePrefabsList = new CustomSyncedValue<List<string>>(configSync, "BetterBeehivesBeehivePrefabsList", BeehivePrefabs.Value.Replace(" ", "").Split().ToList());
			NearbyPlantsGrowthList = new CustomSyncedValue<List<string>>(configSync, "BetterBeehivesPlantsGrowthList", NearbyPlantsGrowth.Value.Replace(" ", "").Split(new char[1] { ',' }).ToList());
			NearbyPickablesGrowthList = new CustomSyncedValue<List<string>>(configSync, "BetterBeehivesPickablesGrowthList", NearbyPickablesGrowth.Value.Replace(" ", "").Split(new char[1] { ',' }).ToList());
		}
	}
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
	public static class Helper
	{
		public static ConfigEntry<T> BindServer<[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] T>(this ConfigFile config, string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = config.Bind<T>(group, name, value, description);
			SyncedConfigEntry<T> syncedConfigEntry = ConfigManager.configSync.AddConfigEntry<T>(val);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val;
		}

		public static void PrintInstructions(this List<CodeInstruction> instructions)
		{
			for (int i = 0; i < instructions.Count; i++)
			{
				Main.LogMessage(((object)instructions[i]).ToString());
			}
		}

		public static bool TryGetField(this Assembly assembly, string typeName, string fieldName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out FieldInfo field)
		{
			field = null;
			Type type = assembly.GetType(typeName);
			if (type == null)
			{
				Main.LogMessage(typeName + " class not found.");
				return false;
			}
			return type.TryGetField(fieldName, out field);
		}

		public static bool TryGetField(this Type type, string fieldName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out FieldInfo field)
		{
			field = type.GetField(fieldName, AccessTools.all);
			return field != null;
		}

		public static bool TryGetMethod(this Assembly assembly, string typeName, string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = null;
			Type type = assembly.GetType(typeName);
			if (type == null)
			{
				Main.LogMessage(typeName + " class not found.");
				return false;
			}
			return type.TryGetMethod(methodName, out method);
		}

		public static bool TryGetMethod(this Type type, string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = type.GetMethod(methodName, AccessTools.all);
			return method != null;
		}

		public static void SetupPollinatePrefab(this GameObject prefab)
		{
			BeePollinate component = prefab.GetComponent<BeePollinate>();
			if ((Object)(object)component == (Object)null)
			{
				prefab.AddComponent<BeePollinate>();
			}
			Main.LogMessage("Applied BeePollinate MonoBehaviour to " + ((Object)prefab).name);
		}

		public static void AddBeePollinateComponent(this ZNetScene zNetScene, string prefabName)
		{
			GameObject prefab = zNetScene.GetPrefab(prefabName);
			if (!((Object)(object)prefab == (Object)null))
			{
				prefab.SetupPollinatePrefab();
			}
		}

		public static bool TryGetBeePollinateComponent(this GameObject gameObject, out BeePollinate beePollinate)
		{
			return (Object)(object)(beePollinate = gameObject.GetComponent<BeePollinate>()) != (Object)null;
		}

		public static bool TryGetPlantComponent(this GameObject gameObject, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out Plant plant)
		{
			return (Object)(object)(plant = gameObject.GetComponent<Plant>()) != (Object)null && ConfigManager.NearbyPlantsGrowthList.Value.Contains(((Object)gameObject).name.NoClone());
		}

		public static bool TryGetPickableComponent(this GameObject gameObject, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out Pickable pickable)
		{
			return (Object)(object)(pickable = gameObject.GetComponent<Pickable>()) != (Object)null && ConfigManager.NearbyPickablesGrowthList.Value.Contains(((Object)gameObject).name.NoClone());
		}

		public static bool ShouldAddQueenBee(this Beehive beehive, int honeyLevel = -1)
		{
			int num = ((honeyLevel == -1) ? beehive.GetHoneyLevel() : honeyLevel);
			float num2 = (float)num / (float)beehive.m_maxHoney * ConfigManager.QueenBeeDropChance.Value;
			return Random.Range(0f, 1f) <= num2;
		}

		public static bool ShouldActivateEffect(this Beehive beehive)
		{
			if (!beehive.CheckBiome() || !beehive.HaveFreeSpace())
			{
				return false;
			}
			if (beehive.m_effectOnlyInDaylight && !EnvMan.IsDaylight())
			{
				return false;
			}
			return true;
		}

		public static void SetGrowthEffects(this GameObject gameObject)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			EffectList val = new EffectList();
			val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
			{
				new EffectData
				{
					m_prefab = ZNetScene.s_instance.GetPrefab("fx_BonusYield"),
					m_enabled = true,
					m_variant = -1
				}
			};
			val.Create(gameObject.transform.position, gameObject.transform.rotation, (Transform)null, 1f, -1);
		}

		public static List<BeePollinate> GetNearbyBeePollinatePlants(this GameObject beehive)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			List<BeePollinate> list = new List<BeePollinate>();
			Collider[] array = Physics.OverlapSphere(beehive.transform.position, ConfigManager.NearbyPlantGrowthRange.Value);
			Collider[] array2 = array;
			foreach (Collider val in array2)
			{
				GameObject gameObject = ((Component)val).gameObject;
				if (gameObject.TryGetBeePollinateComponent(out var beePollinate))
				{
					list.Add(beePollinate);
				}
			}
			return list;
		}

		public static List<GameObject> GetNearbyPickablesPlants(this GameObject beehive)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			Collider[] array = Physics.OverlapSphere(beehive.transform.position, ConfigManager.NearbyPlantGrowthRange.Value);
			Collider[] array2 = array;
			foreach (Collider val in array2)
			{
				GameObject gameObject = ((Component)val).gameObject;
				if (gameObject.TryGetPlantComponent(out var _) || gameObject.TryGetPickableComponent(out var _))
				{
					list.Add(gameObject);
				}
			}
			return list;
		}

		public static bool AddBeeEffectToPlant(this Beehive beehive, GameObject plant, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out GameObject effect)
		{
			effect = null;
			if ((Object)(object)beehive.m_beeEffect == (Object)null)
			{
				return false;
			}
			if (beehive.TryGetBeeEffect(plant, out effect))
			{
				return true;
			}
			effect = Object.Instantiate<GameObject>(beehive.m_beeEffect, plant.transform);
			effect.SetActive(false);
			return true;
		}

		public static bool TryGetBeeEffect(this Beehive beehive, GameObject plant, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out GameObject effect)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			effect = null;
			if ((Object)(object)beehive.m_beeEffect == (Object)null)
			{
				return false;
			}
			string text = ((Object)beehive.m_beeEffect.transform).name.NoClone();
			foreach (Transform item in plant.transform)
			{
				Transform val = item;
				if (((Object)val).name.NoClone() != text)
				{
					continue;
				}
				effect = ((Component)val).gameObject;
				return true;
			}
			return false;
		}

		public static string NoClone(this string str)
		{
			return str.Replace("(Clone)", "").Trim();
		}

		public static bool SetItem(this Inventory inventory, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] GameObject prefab, int amount, int x, int y)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			inventory.RemoveItemAt(x, y);
			if ((Object)(object)prefab == (Object)null || amount <= 0)
			{
				return true;
			}
			ItemData val = prefab.GetComponent<ItemDrop>().m_itemData.Clone();
			val.m_dropPrefab = prefab;
			val.m_stack = Mathf.Min(amount, val.m_shared.m_maxStackSize);
			val.m_worldLevel = (byte)Game.m_worldLevel;
			return inventory.AddItem(val, new Vector2i(x, y));
		}

		public static bool RemoveItemAt(this Inventory inventory, int x, int y)
		{
			if (inventory.GetItemAt(x, y) == null)
			{
				return false;
			}
			int num = y * inventory.m_width + x;
			return inventory.RemoveItem(num);
		}

		public static bool HasItemInSlot(this Inventory inventory, GameObject prefab, int x, int y)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null)
			{
				return false;
			}
			ItemData itemData = component.m_itemData;
			Vector2i val = default(Vector2i);
			((Vector2i)(ref val))..ctor(x, y);
			foreach (ItemData item in inventory.m_inventory)
			{
				if (item.m_shared.m_name != itemData.m_shared.m_name || item.m_gridPos != val)
				{
					continue;
				}
				return true;
			}
			return false;
		}

		public static void SetMaxStackValueAtIndex(this InventoryGrid grid, int index, int maxStack)
		{
			Inventory inventory = grid.GetInventory();
			if (inventory.m_inventory.Count > index)
			{
				ItemData item = grid.GetInventory().GetItem(index);
				if (item != null)
				{
					int num = Math.Min(item.m_shared.m_maxStackSize, maxStack);
					grid.m_elements[index].m_amount.text = $"{item.m_stack}/{num}";
				}
			}
		}
	}
}
namespace BetterBeehives.Compatibility
{
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	public static class LazyVikingsCompatibility
	{
		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo DepositToContainersM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo DepositToContainersTranspilerM;

		private static readonly string ModGUID = "blacks7ar.LazyVikings";

		private static bool? _enabled;

		public static bool Enabled
		{
			get
			{
				if (!_enabled.HasValue)
				{
					_enabled = Chainloader.PluginInfos.ContainsKey(ModGUID);
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool DoCompatibilityPatching(Harmony harmony)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			Main.LogMessage("LazyVikings is installed. Starting compatibility patches...");
			bool flag = true;
			flag &= TryGetLazyVikingsMethod("LazyVikings.Patches.BeehivePatch", "DepositToContainers", out DepositToContainersM);
			if (!(flag & TryGetBetterBeehivesMethod("DepositToContainersTranspiler", out DepositToContainersTranspilerM)))
			{
				Main.LogMessage("A problem occurred when attempting to patch LazyVikings. Operation cancelled.");
				return false;
			}
			harmony.Patch((MethodBase)DepositToContainersM, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(DepositToContainersTranspilerM), (HarmonyMethod)null, (HarmonyMethod)null);
			Main.LogMessage("All patches done.");
			return true;
		}

		public static bool TryGetBetterBeehivesMethod(string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = typeof(LazyVikingsCompatibility).GetMethod(methodName, AccessTools.all);
			return method != null;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool TryGetLazyVikingsField(string typeName, string fieldName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out FieldInfo field)
		{
			field = null;
			if (!Enabled)
			{
				Main.LogMessage("LazyVikings not found.");
				return false;
			}
			Assembly assembly = Assembly.GetAssembly(typeof(Plugin));
			return assembly.TryGetField(typeName, fieldName, out field);
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool TryGetLazyVikingsMethod(string typeName, string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = null;
			if (!Enabled)
			{
				Main.LogMessage("LazyVikings not found.");
				return false;
			}
			Assembly assembly = Assembly.GetAssembly(typeof(Plugin));
			return assembly.TryGetMethod(typeName, methodName, out method);
		}

		public static IEnumerable<CodeInstruction> DepositToContainersTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Expected O, but got Unknown
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Expected O, but got Unknown
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Expected O, but got Unknown
			//IL_034e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0358: Expected O, but got Unknown
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Expected O, but got Unknown
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Expected O, but got Unknown
			Main.LogMessage("Applying transpiler patch to LazyVikings.Patch.DepositToContainers()");
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			if (!TryGetBetterBeehivesMethod("AddItemsToContainers", out var method))
			{
				return instructions;
			}
			if (!TryGetLazyVikingsMethod("LazyVikings.Utils.Helper", "GetNearbyContainers", out var method2))
			{
				return instructions;
			}
			if (!typeof(Beehive).TryGetMethod("GetHoneyLevel", out var method3))
			{
				return instructions;
			}
			int num = -1;
			for (int i = 2; i < list.Count; i++)
			{
				if (!(list[i - 2].opcode != OpCodes.Ldarg_0) && !(list[i - 1].opcode != OpCodes.Ldind_Ref) && !(list[i].opcode != OpCodes.Stfld))
				{
					num = i;
					break;
				}
			}
			if (num == -1)
			{
				return instructions;
			}
			FieldInfo fieldInfo = (FieldInfo)list[num].operand;
			if (fieldInfo == null)
			{
				return instructions;
			}
			int num2 = -1;
			for (int j = num; j < list.Count; j++)
			{
				if (!(list[j - 3].opcode != OpCodes.Ldloc_1) && !(list[j - 2].opcode != OpCodes.Ldc_I4_1) && !(list[j - 1].opcode != OpCodes.Call) && !(list[j - 1].operand as MethodInfo != method2) && !(list[j].opcode != OpCodes.Stfld))
				{
					num2 = j;
					break;
				}
			}
			if (num2 == -1)
			{
				return instructions;
			}
			FieldInfo fieldInfo2 = (FieldInfo)list[num2].operand;
			if (fieldInfo2 == null)
			{
				return instructions;
			}
			int num3 = -1;
			for (int k = num2; k < list.Count; k++)
			{
				if (!(list[k - 2].opcode != OpCodes.Callvirt) && !(list[k - 2].operand as MethodInfo != method3) && !(list[k - 1].opcode != OpCodes.Ldc_I4_0) && !(list[k].opcode != OpCodes.Bgt))
				{
					num3 = k + 1;
					break;
				}
			}
			if (num3 == -1)
			{
				return instructions;
			}
			List<CodeInstruction> collection = new List<CodeInstruction>
			{
				new CodeInstruction(OpCodes.Ldloc_0, (object)null),
				new CodeInstruction(OpCodes.Ldfld, (object)fieldInfo),
				new CodeInstruction(OpCodes.Ldloc_0, (object)null),
				new CodeInstruction(OpCodes.Ldfld, (object)fieldInfo2),
				new CodeInstruction(OpCodes.Ldloc_3, (object)null),
				new CodeInstruction(OpCodes.Call, (object)method)
			};
			list.InsertRange(num3, collection);
			Main.LogMessage("Patch Done");
			return list.AsEnumerable();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void AddItemsToContainers(Beehive beehive, List<Container> nearbyContainers, bool mustHaveItem)
		{
			if (!beehive.ShouldAddQueenBee(beehive.m_maxHoney) || !AddItemToContainer(nearbyContainers, Main.Queen, mustHaveItem))
			{
				return;
			}
			int num = 0;
			for (int i = 0; i < ConfigManager.RoyalJellyDropAttempts.Value; i++)
			{
				if (Random.Range(0f, 1f) <= ConfigManager.RoyalJellyDropChance.Value)
				{
					num++;
				}
			}
			AddItemToContainer(nearbyContainers, Main.Jelly, mustHaveItem, num);
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool AddItemToContainer(List<Container> nearbyContainers, string prefabName, bool mustHaveItem, int amount = 1)
		{
			if (amount < 1)
			{
				return false;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName);
			if ((Object)(object)itemPrefab == (Object)null)
			{
				return false;
			}
			ZNetView.m_forceDisableInit = true;
			GameObject val = Object.Instantiate<GameObject>(itemPrefab);
			ZNetView.m_forceDisableInit = false;
			ItemDrop component = val.GetComponent<ItemDrop>();
			bool result = false;
			if ((Object)(object)component != (Object)null)
			{
				component.m_itemData.m_stack = amount;
				result = SpawnInsideContainers(nearbyContainers, component, mustHaveItem);
			}
			Object.Destroy((Object)(object)val);
			return result;
		}

		private static bool SpawnInsideContainers(List<Container> nearbyContainers, ItemDrop item, bool mustHaveItem)
		{
			using (List<Container>.Enumerator enumerator = nearbyContainers.GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					Container current = enumerator.Current;
					Inventory inventory = current.GetInventory();
					if ((mustHaveItem && !inventory.HaveItem(item.m_itemData.m_shared.m_name, true)) || !inventory.AddItem(item.m_itemData))
					{
						return false;
					}
					current.Save();
					current.GetInventory().Changed();
					return true;
				}
			}
			if (mustHaveItem)
			{
				return SpawnInsideContainers(nearbyContainers, item, mustHaveItem: false);
			}
			return false;
		}
	}
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
	public static class SeedBedCompatibility
	{
		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo GerminationAwakeM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo ZNetSceneAwakeM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo GerminationAwakeTranspilerM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		private static MethodInfo ZNetSceneAwakePostfixM;

		private static readonly string ModGUID = "blacks7ar.SeedBed";

		private static float _germinationHalfDuration = 0f;

		private static bool? _enabled;

		public static bool Enabled
		{
			get
			{
				if (!_enabled.HasValue)
				{
					_enabled = Chainloader.PluginInfos.ContainsKey(ModGUID);
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool DoCompatibilityPatching(Harmony harmony)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			Main.LogMessage("SeedBed is installed. Starting compatibility patches...");
			bool flag = true;
			flag &= TryGetSeedBedMethod("SeedBed.Functions.Germination", "Awake", out GerminationAwakeM);
			flag &= typeof(ZNetScene).TryGetMethod("Awake", out ZNetSceneAwakeM);
			flag &= TryGetBetterBeehivesMethod("GerminationAwakeTranspiler", out GerminationAwakeTranspilerM);
			if (!(flag & TryGetBetterBeehivesMethod("ZNetSceneAwakePostfix", out ZNetSceneAwakePostfixM)))
			{
				Main.LogMessage("A problem occurred when attempting to patch SeedBed. Operation cancelled.");
				return false;
			}
			harmony.Patch((MethodBase)GerminationAwakeM, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(GerminationAwakeTranspilerM), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)ZNetSceneAwakeM, (HarmonyMethod)null, new HarmonyMethod(ZNetSceneAwakePostfixM), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Main.LogMessage("All patches done.");
			return true;
		}

		public static bool TryGetBetterBeehivesMethod(string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = typeof(SeedBedCompatibility).GetMethod(methodName, AccessTools.all);
			return method != null;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool TryGetSeedBedMethod(string typeName, string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = null;
			if (!Enabled)
			{
				Main.LogMessage("SeedBed not found.");
				return false;
			}
			Assembly assembly = Assembly.GetAssembly(typeof(Plugin));
			if (assembly == null)
			{
				Main.LogMessage("Could not find SeedBed assembly.");
				return false;
			}
			return assembly.TryGetMethod(typeName, methodName, out method);
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void ZNetSceneAwakePostfix(ZNetScene __instance)
		{
			if (Enabled && Main.SeedBedPatchDone)
			{
				__instance.AddBeePollinateComponent("BSB_SeedBed");
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static IEnumerable<CodeInstruction> GerminationAwakeTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			Main.LogMessage("Applying transpiler patch to SeedBed.Germination.Awake()");
			if (!TryGetBetterBeehivesMethod("RegisterUpdateTimeRPC", out var method))
			{
				return instructions;
			}
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = -1;
			for (int num2 = list.Count - 1; num2 >= 0; num2--)
			{
				if (!(list[num2].opcode != OpCodes.Ret))
				{
					num = num2;
					break;
				}
			}
			if (num == -1)
			{
				return instructions;
			}
			list[num].opcode = OpCodes.Ldarg_0;
			list.Add(new CodeInstruction(OpCodes.Callvirt, (object)method));
			list.Add(new CodeInstruction(OpCodes.Ret, (object)null));
			Main.LogMessage("Patch Done");
			return list.AsEnumerable();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void RegisterUpdateTimeRPC(Germination germination)
		{
			germination.m_nview.Register("RPC_BetterBeehivesUpdateSeedBedTime", (Action<long>)delegate
			{
				long ticks = new DateTime(germination.m_nview.GetZDO().GetLong(ZDOVars.s_startTime, 0L)).Ticks;
				if (germination.m_nview.IsOwner() && ticks != 0)
				{
					long num = (long)((double)GetGerminationHalfDuration() * 1000.0 * 10000.0);
					long num2 = ticks - num;
					germination.m_nview.GetZDO().Set(ZDOVars.s_startTime, num2);
				}
			});
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void HandleSeedBedGrowth(GameObject gameObject)
		{
			if (gameObject.TryGetGerminationComponent(out var germination) && germination.HasCorrectPlant())
			{
				float num = Random.Range(0f, 1f);
				if (num <= ConfigManager.NearbyPlantGrowthChance.Value)
				{
					gameObject.SetGrowthEffects();
					germination.UpdateTime();
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool IsGerminatingOrFinished(this GameObject gameObject)
		{
			if (!gameObject.TryGetGerminationComponent(out var germination))
			{
				return true;
			}
			return germination.IsGerminatingOrFinished();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool IsGerminatingOrFinished(this Germination germination)
		{
			if ((Object)(object)germination.m_nview == (Object)null)
			{
				return false;
			}
			return new DateTime(germination.m_nview.GetZDO().GetLong(ZDOVars.s_startTime, 0L)).Ticks > 0;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool HasCorrectPlant(this GameObject gameObject)
		{
			if (!gameObject.TryGetGerminationComponent(out var germination))
			{
				return true;
			}
			return germination.HasCorrectPlant();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool HasCorrectPlant(this Germination germination)
		{
			List<Transform> list = new List<Transform>
			{
				germination.m_saplingT5x5.transform.GetChild(0),
				germination.m_saplingT3x1.transform.GetChild(0),
				germination.m_saplingVine.transform.GetChild(0)
			};
			string text = "";
			foreach (Transform item in list)
			{
				string firstChildName = item.GetFirstChildName();
				if (firstChildName != "")
				{
					text = firstChildName;
					break;
				}
			}
			if (text == "")
			{
				return false;
			}
			return ConfigManager.NearbyPickablesGrowthList.Value.Contains(text) || ConfigManager.NearbyPlantsGrowthList.Value.Contains(text);
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static string GetFirstChildName(this Transform parent)
		{
			if (parent.childCount == 0)
			{
				return "";
			}
			return ((Object)parent.GetChild(0)).name;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void UpdateTime(this Germination germination)
		{
			if (!((Object)(object)germination.m_nview == (Object)null))
			{
				germination.m_nview.InvokeRPC("RPC_BetterBeehivesUpdateSeedBedTime", Array.Empty<object>());
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool TryGetGerminationComponent(this GameObject gameObject, out Germination germination)
		{
			germination = gameObject.GetComponentInChildren<Germination>();
			return (Object)(object)germination != (Object)null;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static float GetGerminationHalfDuration()
		{
			if (_germinationHalfDuration > 0f)
			{
				return _germinationHalfDuration;
			}
			if (!Enabled)
			{
				return _germinationHalfDuration = 1200f;
			}
			if (Plugin._germinationDuration == null)
			{
				return _germinationHalfDuration = 1200f;
			}
			return _germinationHalfDuration = Plugin._germinationDuration.Value / 3f;
		}
	}
	[<490b26f6-e8ae-48e2-a0c5-ed5389bf6f35>NullableContext(1)]
	[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(0)]
	public static class ZenBeehiveCompatibility
	{
		private static readonly string ModGUID = "ZenDragon.ZenBeehive";

		private static bool? _enabled;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo SetupPrefabM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo BeehiveUpdateBeesM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo InventoryGridUpdateGuiM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo SetupPrefabTranspilerM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo BeehiveUpdateBeesTranspilerM;

		[<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)]
		public static MethodInfo InventoryGridUpdateGuiTranspilerM;

		public static bool Enabled
		{
			get
			{
				if (!_enabled.HasValue)
				{
					_enabled = Chainloader.PluginInfos.ContainsKey(ModGUID);
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool DoCompatibilityPatching(Harmony harmony)
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			Main.LogMessage("ZenBeehive is installed. Starting compatibility patches...");
			bool flag = true;
			flag &= TryGetZenBeehiveMethod("ZenBeehive.BeehivePatches", "SetupPrefab", out SetupPrefabM);
			flag &= TryGetZenBeehiveMethod("ZenBeehive.BeehivePatches", "Beehive_UpdateBees", out BeehiveUpdateBeesM);
			flag &= TryGetZenBeehiveMethod("ZenBeehive.BeehivePatches", "InventoryGrid_UpdateGui", out InventoryGridUpdateGuiM);
			flag &= TryGetBetterBeehivesMethod("SetupPrefabTranspiler", out SetupPrefabTranspilerM);
			flag &= TryGetBetterBeehivesMethod("Beehive_UpdateBeesTranspiler", out BeehiveUpdateBeesTranspilerM);
			if (!(flag & TryGetBetterBeehivesMethod("InventoryGrid_UpdateGuiTranspiler", out InventoryGridUpdateGuiTranspilerM)))
			{
				Main.LogMessage("A problem occurred when attempting to patch ZenBeehive. Operation cancelled.");
				return false;
			}
			harmony.Patch((MethodBase)SetupPrefabM, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(SetupPrefabTranspilerM), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)BeehiveUpdateBeesM, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(BeehiveUpdateBeesTranspilerM), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)InventoryGridUpdateGuiM, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(InventoryGridUpdateGuiTranspilerM), (HarmonyMethod)null, (HarmonyMethod)null);
			Main.LogMessage("All patches done.");
			return true;
		}

		public static bool TryGetBetterBeehivesMethod(string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = typeof(ZenBeehiveCompatibility).GetMethod(methodName, AccessTools.all);
			return method != null;
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool TryGetZenBeehiveMethod(string typeName, string methodName, [<7fd18e28-3a80-47a0-ad89-44d3c18f95ae>Nullable(2)] out MethodInfo method)
		{
			method = null;
			if (!Enabled)
			{
				Main.LogMessage("ZenBeehive not found.");
				return false;
			}
			Assembly assembly = Assembly.GetAssembly(typeof(Configs));
			return assembly.TryGetMethod(typeName, methodName, out method);
		}

		public static IEnumerable<CodeInstruction> InventoryGrid_UpdateGuiTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator il)
		{
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Expected O, but got Unknown
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Expected O, but got Unknown
			Main.LogMessage("Applying transpiler patch to ZenBeehive.InventoryGrid_UpdateGui()");
			if (!TryGetBetterBeehivesMethod("ZenBeehiveInventoryGuiAdditions", out var method))
			{
				return instructions;
			}
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = -1;
			int num2 = -1;
			for (int i = 0; i < list.Count - 2; i++)
			{
				if (!(list[i].opcode != OpCodes.Call) && !(list[i + 1].opcode != OpCodes.Brtrue) && !(list[i + 2].opcode != OpCodes.Ret))
				{
					num = i + 1;
					num2 = i + 2;
					break;
				}
			}
			if (num == -1 || num2 == -1)
			{
				return instructions;
			}
			Label label = il.DefineLabel();
			list[num].operand = label;
			List<CodeInstruction> list2 = new List<CodeInstruction>();
			for (int j = 0; j <= num2; j++)
			{
				list2.Add(list[j]);
			}
			CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			val.labels.Add(label);
			list2.Add(val);
			list2.Add(new CodeInstruction(OpCodes.Call, (object)method));
			list2.Add(new CodeInstruction(OpCodes.Ret, (object)null));
			Main.LogMessage("Patch Done");
			return list2.AsEnumerable();
		}

		public static IEnumerable<CodeInstruction> Beehive_UpdateBeesTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			Main.LogMessage("Applying transpiler patch to ZenBeehive.Beehive_UpdateBees()");
			Main.LogMessage("Patch Donr");
			return new List<CodeInstruction>
			{
				new CodeInstruction(OpCodes.Ret, (object)null)
			}.AsEnumerable();
		}

		public static IEnumerable<CodeInstruction> SetupPrefabTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			Main.LogMessage("Applying transpiler patch to ZenBeehive.SetupPrefab()");
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			FieldInfo fieldInfo = AccessTools.Field(typeof(Container), "m_width");
			if (fieldInfo == null)
			{
				return instructions;
			}
			int num = -1;
			for (int i = 1; i < list.Count - 1; i++)
			{
				if (!(list[i - 1].opcode != OpCodes.Ldloc_1) && !(list[i].opcode != OpCodes.Ldc_I4_1) && !(list[i + 1].opcode != OpCodes.Stfld) && !((FieldInfo)list[i + 1].operand != fieldInfo))
				{
					num = i;
					break;
				}
			}
			if (num == -1)
			{
				return instructions;
			}
			list[num].opcode = OpCodes.Ldc_I4_3;
			Main.LogMessage("Patch Done");
			return list.AsEnumerable();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void ZenBeehiveInventoryGuiAdditions(InventoryGrid grid)
		{
			grid.SetMaxStackValueAtIndex(0, Configs.MaxHoney.Value);
			grid.SetMaxStackValueAtIndex(1, 1);
			grid.SetMaxStackValueAtIndex(2, ConfigManager.RoyalJellyDropAttempts.Value);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

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

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

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

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
			base..ctor();
		}

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

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

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

		public event Action? ValueChanged;

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

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

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

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

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

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

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

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

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

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

				public volatile int versionMatchQueued = -1;

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

				public readonly ISocket Original;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

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

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

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

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

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

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

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

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

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

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

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

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

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

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

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

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typ