Decompiled source of Quality of Cacao v1.3.0

plugins/Quality_of_Cacao.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace QualityOfCacao
{
	internal static class CraftFromContainers
	{
		[ThreadStatic]
		private static int _depth;

		private static bool? _conflict;

		private static readonly FieldRef<Container, ZNetView> ContainerNView = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		private static readonly MethodInfo ContainerLoad = AccessTools.Method(typeof(Container), "Load", (Type[])null, (Type[])null);

		private const float CacheTime = 0.5f;

		private static float _nearbyTime = -1f;

		private static readonly List<Container> Nearby = new List<Container>();

		private static float _countTime = -1f;

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

		private static readonly Dictionary<ItemData, Container> ItemSource = new Dictionary<ItemData, Container>();

		internal static int FindCookableDepth;

		internal static bool FindCookableSecondPass;

		private static bool FeatureOn
		{
			get
			{
				if (!QualityOfCacaoPlugin.CraftEnabled.Value)
				{
					return false;
				}
				if (!_conflict.HasValue)
				{
					_conflict = false;
					foreach (PluginInfo value in Chainloader.PluginInfos.Values)
					{
						BepInPlugin val = ((value != null) ? value.Metadata : null);
						if (val != null && ((val.Name != null && val.Name.IndexOf("CraftyBoxes", StringComparison.OrdinalIgnoreCase) >= 0) || (val.GUID != null && val.GUID.IndexOf("CraftyBoxes", StringComparison.OrdinalIgnoreCase) >= 0)))
						{
							_conflict = true;
							QualityOfCacaoPlugin.Log.LogWarning((object)"Обнаружен AzuCraftyBoxes — крафт из сундуков Quality_of_Cacao отключён, чтобы не было двойного учёта ресурсов. Отключите один из модов.");
							break;
						}
					}
				}
				return !_conflict.Value;
			}
		}

		internal static bool IsActiveFor(Inventory inv)
		{
			return Active(inv);
		}

		internal static void Enter()
		{
			_depth++;
		}

		internal static void Exit()
		{
			if (_depth > 0)
			{
				_depth--;
			}
			if (_depth == 0)
			{
				ItemSource.Clear();
			}
		}

		private static bool Active(Inventory inv)
		{
			if (_depth <= 0 || inv == null)
			{
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || inv != ((Humanoid)localPlayer).GetInventory())
			{
				return false;
			}
			return FeatureOn;
		}

		private static List<Container> GetNearby()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			float time = Time.time;
			if (time - _nearbyTime < 0.5f && time >= _nearbyTime)
			{
				return Nearby;
			}
			_nearbyTime = time;
			Nearby.Clear();
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return Nearby;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			float num = QualityOfCacaoPlugin.CraftRadius.Value * QualityOfCacaoPlugin.CraftRadius.Value;
			long playerId = (((Object)(object)Game.instance != (Object)null) ? Game.instance.GetPlayerProfile().GetPlayerID() : 0);
			List<KeyValuePair<float, Container>> list = new List<KeyValuePair<float, Container>>();
			List<Container> containers = QualityOfCacaoPlugin.Containers;
			for (int num2 = containers.Count - 1; num2 >= 0; num2--)
			{
				Container val = containers[num2];
				if ((Object)(object)val == (Object)null)
				{
					containers.RemoveAt(num2);
				}
				else
				{
					Vector3 val2 = ((Component)val).transform.position - position;
					float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
					if (!(sqrMagnitude > num) && QualityOfCacaoPlugin.IsUsable(val, playerId))
					{
						list.Add(new KeyValuePair<float, Container>(sqrMagnitude, val));
					}
				}
			}
			list.Sort((KeyValuePair<float, Container> a, KeyValuePair<float, Container> b) => a.Key.CompareTo(b.Key));
			foreach (KeyValuePair<float, Container> item in list)
			{
				Nearby.Add(item.Value);
			}
			return Nearby;
		}

		private static void Invalidate()
		{
			_nearbyTime = -1f;
			_countTime = -1f;
			CountCache.Clear();
		}

		private static bool Matches(ItemData item, string name, int quality, bool worldLevel)
		{
			if (item?.m_shared != null && (name == null || item.m_shared.m_name == name) && (quality < 0 || item.m_quality == quality))
			{
				if (worldLevel)
				{
					return item.m_worldLevel >= Game.m_worldLevel;
				}
				return true;
			}
			return false;
		}

		private static int CountDirect(Inventory inv, string name, int quality, bool worldLevel)
		{
			int num = 0;
			foreach (ItemData allItem in inv.GetAllItems())
			{
				if (Matches(allItem, name, quality, worldLevel))
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static int CountInContainers(string name, int quality, bool worldLevel)
		{
			if (name == null)
			{
				return 0;
			}
			float time = Time.time;
			if (time - _countTime >= 0.5f || time < _countTime)
			{
				_countTime = time;
				CountCache.Clear();
			}
			string key = name + "|" + quality + "|" + (worldLevel ? 1 : 0);
			if (CountCache.TryGetValue(key, out var value))
			{
				return value;
			}
			int num = 0;
			foreach (Container item in GetNearby())
			{
				Inventory val = (((Object)(object)item != (Object)null) ? item.GetInventory() : null);
				if (val != null)
				{
					num += CountDirect(val, name, quality, worldLevel);
				}
			}
			CountCache[key] = num;
			return num;
		}

		internal static bool TryGetCounts(string name, out int inInventory, out int inChests)
		{
			inInventory = 0;
			inChests = 0;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || name == null || !FeatureOn)
			{
				return false;
			}
			inInventory = CountDirect(((Humanoid)localPlayer).GetInventory(), name, -1, worldLevel: false);
			inChests = CountInContainers(name, -1, worldLevel: false);
			return true;
		}

		internal static bool TryTakeOne(string name)
		{
			if (!FeatureOn || name == null)
			{
				return false;
			}
			if (CountInContainers(name, -1, worldLevel: false) <= 0)
			{
				return false;
			}
			return TakeFromContainers(name, 1, -1, worldLevel: false) == 0;
		}

		private static bool PrepareForWrite(Container c)
		{
			if ((Object)(object)c == (Object)null)
			{
				return false;
			}
			ZNetView val = ContainerNView.Invoke(c);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			if (!val.IsOwner())
			{
				if (val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
				{
					return false;
				}
				val.ClaimOwnership();
			}
			try
			{
				ContainerLoad?.Invoke(c, null);
			}
			catch (Exception)
			{
			}
			return c.GetInventory() != null;
		}

		private static int TakeFromContainers(string name, int amount, int quality, bool worldLevel, Container preferred = null)
		{
			if (amount <= 0)
			{
				return 0;
			}
			_nearbyTime = -1f;
			List<Container> list = new List<Container>(GetNearby());
			if ((Object)(object)preferred != (Object)null)
			{
				list.Remove(preferred);
				list.Insert(0, preferred);
			}
			foreach (Container item in list)
			{
				if (amount <= 0)
				{
					break;
				}
				if (PrepareForWrite(item))
				{
					Inventory inventory = item.GetInventory();
					int num = CountDirect(inventory, name, quality, worldLevel);
					if (num > 0)
					{
						int num2 = Mathf.Min(num, amount);
						inventory.RemoveItem(name, num2, quality, worldLevel);
						amount -= num2;
					}
				}
			}
			Invalidate();
			return amount;
		}

		internal static void CountItemsPostfix(Inventory inv, string name, int quality, bool matchWorldLevel, ref int result)
		{
			if (Active(inv))
			{
				result += CountInContainers(name, quality, matchWorldLevel);
			}
		}

		internal static void HaveItemPostfix(Inventory inv, string name, bool matchWorldLevel, ref bool result)
		{
			if (!result && Active(inv))
			{
				result = CountInContainers(name, -1, matchWorldLevel) > 0;
			}
		}

		internal static void GetItemPostfix(Inventory inv, string name, int quality, bool isPrefabName, ref ItemData result)
		{
			if (result != null || !Active(inv) || name == null || (FindCookableDepth > 0 && !FindCookableSecondPass))
			{
				return;
			}
			foreach (Container item in GetNearby())
			{
				Inventory val = (((Object)(object)item != (Object)null) ? item.GetInventory() : null);
				if (val == null)
				{
					continue;
				}
				foreach (ItemData allItem in val.GetAllItems())
				{
					if (allItem?.m_shared == null)
					{
						continue;
					}
					bool num;
					if (!isPrefabName)
					{
						num = allItem.m_shared.m_name == name;
					}
					else
					{
						if (!((Object)(object)allItem.m_dropPrefab != (Object)null))
						{
							continue;
						}
						num = ((Object)allItem.m_dropPrefab).name == name;
					}
					if (num && (quality < 0 || allItem.m_quality == quality) && !((Object)(object)allItem.m_dropPrefab == (Object)null))
					{
						ItemSource[allItem] = item;
						result = allItem;
						return;
					}
				}
			}
		}

		internal static void RemoveByNamePrefix(Inventory inv, string name, ref int amount, int itemQuality, bool worldLevelBased)
		{
			if (amount <= 0 || !Active(inv))
			{
				return;
			}
			int num = CountDirect(inv, name, itemQuality, worldLevelBased);
			if (num < amount)
			{
				int amount2 = amount - num;
				amount = num;
				int num2 = TakeFromContainers(name, amount2, itemQuality, worldLevelBased);
				if (num2 > 0)
				{
					QualityOfCacaoPlugin.Log.LogWarning((object)$"Не удалось списать {num2} x {name} из сундуков.");
				}
			}
		}

		internal static bool RemoveByRefPrefix(Inventory inv, ItemData item, int amount, ref bool result)
		{
			if (item == null || !Active(inv))
			{
				return true;
			}
			if (inv.GetAllItems().Contains(item))
			{
				return true;
			}
			ItemSource.TryGetValue(item, out var value);
			if ((Object)(object)value == (Object)null)
			{
				foreach (Container item2 in GetNearby())
				{
					if ((Object)(object)item2 != (Object)null && item2.GetInventory() != null && item2.GetInventory().GetAllItems().Contains(item))
					{
						value = item2;
						break;
					}
				}
			}
			if ((Object)(object)value == (Object)null)
			{
				return true;
			}
			ItemSource.Remove(item);
			int num = Mathf.Max(1, Mathf.Min(amount, item.m_stack));
			int num2 = TakeFromContainers(item.m_shared.m_name, num, item.m_quality, worldLevel: false, value);
			result = num2 < num;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class CraftScopes
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(Player), "HaveRequirements", new Type[4]
			{
				typeof(Recipe),
				typeof(bool),
				typeof(int),
				typeof(int)
			}, (Type[])null);
			yield return AccessTools.Method(typeof(Player), "HaveRequirements", new Type[2]
			{
				typeof(Piece),
				typeof(RequirementMode)
			}, (Type[])null);
			yield return AccessTools.Method(typeof(Player), "GetFirstRequiredItem", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(Player), "ConsumeResources", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(InventoryGui), "SetupRequirement", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null);
		}

		[HarmonyPriority(0)]
		private static void Prefix(out bool __state)
		{
			CraftFromContainers.Enter();
			__state = true;
		}

		[HarmonyPriority(800)]
		private static void Postfix(ref bool __state)
		{
			if (__state)
			{
				__state = false;
				CraftFromContainers.Exit();
			}
		}

		private static void Finalizer(bool __state)
		{
			if (__state)
			{
				CraftFromContainers.Exit();
			}
		}
	}
	[HarmonyPatch]
	internal static class StationScopes
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] array = new MethodInfo[4]
			{
				AccessTools.Method(typeof(Smelter), "OnAddOre", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Smelter), "OnAddFuel", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Fermenter), "Interact", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Fireplace), "Interact", (Type[])null, (Type[])null)
			};
			MethodInfo[] array2 = array;
			foreach (MethodInfo methodInfo in array2)
			{
				if (methodInfo != null)
				{
					yield return methodInfo;
				}
			}
		}

		[HarmonyPriority(0)]
		private static void Prefix(out bool __state)
		{
			CraftFromContainers.Enter();
			__state = true;
		}

		[HarmonyPriority(800)]
		private static void Postfix(ref bool __state)
		{
			if (__state)
			{
				__state = false;
				CraftFromContainers.Exit();
			}
		}

		private static void Finalizer(bool __state)
		{
			if (__state)
			{
				CraftFromContainers.Exit();
			}
		}
	}
	[HarmonyPatch]
	internal static class FindCookableItemPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] array = new MethodInfo[2]
			{
				AccessTools.Method(typeof(Smelter), "FindCookableItem", (Type[])null, (Type[])null),
				AccessTools.Method(typeof(Fermenter), "FindCookableItem", (Type[])null, (Type[])null)
			};
			MethodInfo[] array2 = array;
			foreach (MethodInfo methodInfo in array2)
			{
				if (methodInfo != null)
				{
					yield return methodInfo;
				}
			}
		}

		private static void Prefix()
		{
			CraftFromContainers.FindCookableDepth++;
		}

		private static void Postfix(object __instance, Inventory inventory, MethodBase __originalMethod, ref ItemData __result)
		{
			if (__result != null || CraftFromContainers.FindCookableSecondPass || !CraftFromContainers.IsActiveFor(inventory))
			{
				return;
			}
			CraftFromContainers.FindCookableSecondPass = true;
			try
			{
				object? obj = __originalMethod.Invoke(__instance, new object[1] { inventory });
				__result = (ItemData)((obj is ItemData) ? obj : null);
			}
			catch (Exception)
			{
			}
			finally
			{
				CraftFromContainers.FindCookableSecondPass = false;
			}
		}

		private static void Finalizer()
		{
			if (CraftFromContainers.FindCookableDepth > 0)
			{
				CraftFromContainers.FindCookableDepth--;
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "CountItems")]
	internal static class InventoryCountItemsPatch
	{
		private static void Postfix(Inventory __instance, string name, int quality, bool matchWorldLevel, ref int __result)
		{
			CraftFromContainers.CountItemsPostfix(__instance, name, quality, matchWorldLevel, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "HaveItem", new Type[]
	{
		typeof(string),
		typeof(bool)
	})]
	internal static class InventoryHaveItemPatch
	{
		private static void Postfix(Inventory __instance, string name, bool matchWorldLevel, ref bool __result)
		{
			CraftFromContainers.HaveItemPostfix(__instance, name, matchWorldLevel, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "GetItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(bool)
	})]
	internal static class InventoryGetItemPatch
	{
		private static void Postfix(Inventory __instance, string name, int quality, bool isPrefabName, ref ItemData __result)
		{
			CraftFromContainers.GetItemPostfix(__instance, name, quality, isPrefabName, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	internal static class InventoryRemoveByNamePatch
	{
		private static void Prefix(Inventory __instance, string name, ref int amount, int itemQuality, bool worldLevelBased)
		{
			CraftFromContainers.RemoveByNamePrefix(__instance, name, ref amount, itemQuality, worldLevelBased);
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })]
	internal static class InventoryRemoveRefPatch
	{
		private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
		{
			return CraftFromContainers.RemoveByRefPrefix(__instance, item, item?.m_stack ?? 1, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(ItemData),
		typeof(int)
	})]
	internal static class InventoryRemoveRefAmountPatch
	{
		private static bool Prefix(Inventory __instance, ItemData item, int amount, ref bool __result)
		{
			return CraftFromContainers.RemoveByRefPrefix(__instance, item, amount, ref __result);
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveOneItem")]
	internal static class InventoryRemoveOnePatch
	{
		private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
		{
			return CraftFromContainers.RemoveByRefPrefix(__instance, item, 1, ref __result);
		}
	}
	internal static class AutoRepairer
	{
		private static readonly List<ItemData> Worn = new List<ItemData>();

		internal static void Tick()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			if (!QualityOfCacaoPlugin.AutoRepair.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			float value = QualityOfCacaoPlugin.AutoRepairRadius.Value;
			float num = value * value;
			Vector3 position = ((Component)localPlayer).transform.position;
			Worn.Clear();
			((Humanoid)localPlayer).GetInventory().GetWornItems(Worn);
			if (Worn.Count == 0)
			{
				return;
			}
			foreach (IMonoUpdater instance in CraftingStation.Instances)
			{
				CraftingStation val = (CraftingStation)(object)((instance is CraftingStation) ? instance : null);
				if ((Object)(object)val == (Object)null || !val.m_canRepair)
				{
					continue;
				}
				Vector3 val2 = ((Component)val).transform.position - position;
				if (((Vector3)(ref val2)).sqrMagnitude > num || !val.CheckUsable(localPlayer, false))
				{
					continue;
				}
				foreach (ItemData item in Worn)
				{
					if (!(item.m_durability >= item.GetMaxDurability()) && CanRepair(item, val))
					{
						((Character)localPlayer).RaiseSkill((SkillType)107, 1f - item.m_durability / item.GetMaxDurability());
						item.m_durability = item.GetMaxDurability();
						((Character)localPlayer).Message((MessageType)1, Localization.instance.Localize("$msg_repaired", new string[1] { item.m_shared.m_name }), 0, (Sprite)null, false);
					}
				}
			}
		}

		private static bool CanRepair(ItemData item, CraftingStation st)
		{
			if (item?.m_shared == null || !item.m_shared.m_canBeReparied)
			{
				return false;
			}
			Recipe recipe = ObjectDB.instance.GetRecipe(item);
			if ((Object)(object)recipe == (Object)null || ((Object)(object)recipe.m_craftingStation == (Object)null && (Object)(object)recipe.m_repairStation == (Object)null))
			{
				return false;
			}
			if (((Object)(object)recipe.m_repairStation != (Object)null && recipe.m_repairStation.m_name == st.m_name) || ((Object)(object)recipe.m_craftingStation != (Object)null && recipe.m_craftingStation.m_name == st.m_name) || item.m_worldLevel < Game.m_worldLevel)
			{
				return Mathf.Min(st.GetLevel(true), 4) >= recipe.m_minStationLevel;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	internal static class RequirementCountsPatch
	{
		[HarmonyAfter(new string[] { "maximods.valheim.multicraft" })]
		[HarmonyPriority(0)]
		private static void Postfix(Transform elementRoot, Requirement req, bool __result)
		{
			if (__result && QualityOfCacaoPlugin.ShowCounts.Value && !((Object)(object)req?.m_resItem == (Object)null) && CraftFromContainers.TryGetCounts(req.m_resItem.m_itemData.m_shared.m_name, out var inInventory, out var inChests))
			{
				Transform obj = elementRoot.Find("res_amount");
				TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null);
				if (!((Object)(object)val == (Object)null))
				{
					string text = val.text ?? "";
					int num = text.IndexOf('/');
					val.text = ((num > 0) ? $"{text.Substring(0, num)}/{inInventory}+{inChests}" : $"{text} ({inInventory}+{inChests})");
				}
			}
		}
	}
	internal static class AutoFeeder
	{
		internal static readonly List<Smelter> Smelters = new List<Smelter>();

		internal static readonly List<Fireplace> Fireplaces = new List<Fireplace>();

		internal static readonly List<Fermenter> Fermenters = new List<Fermenter>();

		private static readonly FieldRef<Fireplace, ZNetView> FireNView = AccessTools.FieldRefAccess<Fireplace, ZNetView>("m_nview");

		private static readonly FieldRef<Fermenter, ZNetView> FermNView = AccessTools.FieldRefAccess<Fermenter, ZNetView>("m_nview");

		private static readonly MethodInfo FermGetStatus = AccessTools.Method(typeof(Fermenter), "GetStatus", (Type[])null, (Type[])null);

		private static readonly FieldRef<Smelter, ZNetView> SmelterNView = AccessTools.FieldRefAccess<Smelter, ZNetView>("m_nview");

		private static readonly MethodInfo GetFuel = AccessTools.Method(typeof(Smelter), "GetFuel", (Type[])null, (Type[])null);

		private static readonly MethodInfo GetQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize", (Type[])null, (Type[])null);

		internal static void Tick()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			if (!QualityOfCacaoPlugin.AutoFeed.Value || !QualityOfCacaoPlugin.CraftEnabled.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				return;
			}
			float value = QualityOfCacaoPlugin.AutoFeedRadius.Value;
			float num = value * value;
			Vector3 position = ((Component)localPlayer).transform.position;
			TickOthers(position, num);
			for (int num2 = Smelters.Count - 1; num2 >= 0; num2--)
			{
				Smelter val = Smelters[num2];
				if ((Object)(object)val == (Object)null)
				{
					Smelters.RemoveAt(num2);
				}
				else
				{
					Vector3 val2 = ((Component)val).transform.position - position;
					if (!(((Vector3)(ref val2)).sqrMagnitude > num))
					{
						ZNetView val3 = SmelterNView.Invoke(val);
						if (!((Object)(object)val3 == (Object)null) && val3.IsValid())
						{
							try
							{
								Feed(val, val3);
							}
							catch (Exception ex)
							{
								QualityOfCacaoPlugin.Log.LogWarning((object)("AutoFeed: " + ex.Message));
							}
						}
					}
				}
			}
		}

		private static void TickOthers(Vector3 pos, float r2)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val2;
			for (int num = Fireplaces.Count - 1; num >= 0; num--)
			{
				Fireplace val = Fireplaces[num];
				if ((Object)(object)val == (Object)null)
				{
					Fireplaces.RemoveAt(num);
				}
				else
				{
					val2 = ((Component)val).transform.position - pos;
					if (!(((Vector3)(ref val2)).sqrMagnitude > r2))
					{
						try
						{
							ZNetView val3 = FireNView.Invoke(val);
							if (!((Object)(object)val3 == (Object)null) && val3.IsValid() && !val.m_infiniteFuel && !((Object)(object)val.m_fuelItem == (Object)null) && val.IsBurning() && !((float)Mathf.CeilToInt(val3.GetZDO().GetFloat(ZDOVars.s_fuel, 0f)) >= val.m_maxFuel) && CraftFromContainers.TryTakeOne(val.m_fuelItem.m_itemData.m_shared.m_name))
							{
								val3.InvokeRPC("RPC_AddFuel", Array.Empty<object>());
							}
						}
						catch (Exception ex)
						{
							QualityOfCacaoPlugin.Log.LogWarning((object)("AutoFeed fireplace: " + ex.Message));
						}
					}
				}
			}
			for (int num2 = Fermenters.Count - 1; num2 >= 0; num2--)
			{
				Fermenter val4 = Fermenters[num2];
				if ((Object)(object)val4 == (Object)null)
				{
					Fermenters.RemoveAt(num2);
				}
				else
				{
					val2 = ((Component)val4).transform.position - pos;
					if (!(((Vector3)(ref val2)).sqrMagnitude > r2))
					{
						try
						{
							ZNetView val5 = FermNView.Invoke(val4);
							if (!((Object)(object)val5 == (Object)null) && val5.IsValid())
							{
								switch ((int)FermGetStatus.Invoke(val4, null))
								{
								case 3:
									val5.InvokeRPC("RPC_Tap", Array.Empty<object>());
									break;
								case 0:
									foreach (ItemConversion item in val4.m_conversion)
									{
										if (!((Object)(object)item?.m_from == (Object)null) && CraftFromContainers.TryTakeOne(item.m_from.m_itemData.m_shared.m_name))
										{
											val5.InvokeRPC("RPC_AddItem", new object[2]
											{
												StringExtensionMethods.GetStableHashCode(((Object)((Component)item.m_from).gameObject).name),
												false
											});
											break;
										}
									}
									break;
								}
							}
						}
						catch (Exception ex2)
						{
							QualityOfCacaoPlugin.Log.LogWarning((object)("AutoFeed fermenter: " + ex2.Message));
						}
					}
				}
			}
		}

		private static void Feed(Smelter sm, ZNetView nview)
		{
			if (sm.m_maxFuel > 0 && (Object)(object)sm.m_fuelItem != (Object)null && (float)GetFuel.Invoke(sm, null) <= (float)(sm.m_maxFuel - 1) && CraftFromContainers.TryTakeOne(sm.m_fuelItem.m_itemData.m_shared.m_name))
			{
				nview.InvokeRPC("RPC_AddFuel", Array.Empty<object>());
			}
			if (sm.m_maxOre <= 0 || (int)GetQueueSize.Invoke(sm, null) >= sm.m_maxOre)
			{
				return;
			}
			foreach (ItemConversion item in sm.m_conversion)
			{
				if (!((Object)(object)item?.m_from == (Object)null) && CraftFromContainers.TryTakeOne(item.m_from.m_itemData.m_shared.m_name))
				{
					nview.InvokeRPC("RPC_AddOre", new object[2]
					{
						((Object)((Component)item.m_from).gameObject).name,
						false
					});
					break;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Smelter), "Awake")]
	internal static class SmelterAwakePatch
	{
		private static void Postfix(Smelter __instance)
		{
			if (!AutoFeeder.Smelters.Contains(__instance))
			{
				AutoFeeder.Smelters.Add(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Fireplace), "Awake")]
	internal static class FireplaceAwakePatch
	{
		private static void Postfix(Fireplace __instance)
		{
			if (!AutoFeeder.Fireplaces.Contains(__instance))
			{
				AutoFeeder.Fireplaces.Add(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Fermenter), "Awake")]
	internal static class FermenterAwakePatch
	{
		private static void Postfix(Fermenter __instance)
		{
			if (!AutoFeeder.Fermenters.Contains(__instance))
			{
				AutoFeeder.Fermenters.Add(__instance);
			}
		}
	}
	[BepInPlugin("local.qualityofcacao.valheim", "Quality_of_Cacao", "1.2.0")]
	public class QualityOfCacaoPlugin : BaseUnityPlugin
	{
		private class PendingDrop
		{
			public ItemDrop Drop;

			public ZNetView NView;

			public float DropTime;

			public float NextRetarget;

			public Container Target;
		}

		public const string ModGuid = "local.qualityofcacao.valheim";

		public const string ModName = "Quality_of_Cacao";

		public const string ModVersion = "1.2.0";

		internal static QualityOfCacaoPlugin Instance;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> Delay;

		internal static ConfigEntry<float> Radius;

		internal static ConfigEntry<Color> ItemColor;

		internal static ConfigEntry<Color> ContainerColor;

		internal static ConfigEntry<bool> ShowMessage;

		internal static ConfigEntry<bool> CraftEnabled;

		internal static ConfigEntry<float> CraftRadius;

		internal static ConfigEntry<bool> ShowCounts;

		internal static ConfigEntry<bool> AutoRepair;

		internal static ConfigEntry<float> AutoRepairRadius;

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> AutoFeed;

		internal static ConfigEntry<float> AutoFeedRadius;

		private float _nextRepair;

		private float _nextFeed;

		internal static readonly List<Container> Containers = new List<Container>();

		private readonly List<PendingDrop> _pending = new List<PendingDrop>();

		private readonly HashSet<GameObject> _highlightedNow = new HashSet<GameObject>();

		private HashSet<GameObject> _highlightedPrev = new HashSet<GameObject>();

		private static readonly int EmissionColorId = Shader.PropertyToID("_EmissionColor");

		private static readonly int ColorId = Shader.PropertyToID("_Color");

		private static readonly FieldRef<Container, ZNetView> ContainerNView = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		private static readonly MethodInfo ContainerLoad = AccessTools.Method(typeof(Container), "Load", (Type[])null, (Type[])null);

		private const float RetargetInterval = 0.25f;

		private const float OwnershipGrace = 3f;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00ef: 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_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Expected O, but got Unknown
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Включить автоскладывание выброшенных предметов.");
			Delay = ((BaseUnityPlugin)this).Config.Bind<float>("General", "DelaySeconds", 5f, new ConfigDescription("Через сколько секунд после выброса предмет складывается в сундук.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 60f), Array.Empty<object>()));
			Radius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "SearchRadius", 20f, new ConfigDescription("Радиус (в метрах) поиска сундуков вокруг выброшенного предмета.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			ShowMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowMessage", true, "Показывать сообщение в левом верхнем углу при складывании.");
			ItemColor = ((BaseUnityPlugin)this).Config.Bind<Color>("Highlight", "ItemColor", new Color(0.2f, 1f, 0.2f, 1f), "Цвет подсветки предмета, который будет сложен.");
			ContainerColor = ((BaseUnityPlugin)this).Config.Bind<Color>("Highlight", "ContainerColor", new Color(0.25f, 0.45f, 1f, 1f), "Цвет подсветки сундука, в который предмет будет сложен.");
			CraftEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("CraftFromChests", "Enabled", true, "Использовать предметы из ближайших сундуков для крафта, готовки, строительства, посадки и заправки печей/костров.");
			CraftRadius = ((BaseUnityPlugin)this).Config.Bind<float>("CraftFromChests", "Radius", 20f, new ConfigDescription("Радиус (в метрах) вокруг игрока, в котором сундуки участвуют в крафте и строительстве.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			ShowCounts = ((BaseUnityPlugin)this).Config.Bind<bool>("CraftFromChests", "ShowCounts", true, "В требованиях верстака показывать количество ресурса: (в инвентаре+в сундуках).");
			AutoRepair = ((BaseUnityPlugin)this).Config.Bind<bool>("AutoRepair", "Enabled", true, "Автоматически чинить предметы рядом с верстаком/станцией.");
			AutoRepairRadius = ((BaseUnityPlugin)this).Config.Bind<float>("AutoRepair", "Radius", 5f, new ConfigDescription("Радиус (в метрах) до станции, в котором предметы чинятся сами.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			AutoFeed = ((BaseUnityPlugin)this).Config.Bind<bool>("AutoFeed", "Enabled", true, "Автоматически заправлять печи/плавильни (руда и топливо) из ближайших сундуков.");
			AutoFeedRadius = ((BaseUnityPlugin)this).Config.Bind<float>("AutoFeed", "Radius", 10f, new ConfigDescription("Радиус (в метрах) от игрока, в котором печи заправляются сами.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			_harmony = new Harmony("local.qualityofcacao.valheim");
			_harmony.PatchAll(typeof(QualityOfCacaoPlugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Quality_of_Cacao 1.2.0 loaded");
		}

		private void OnDestroy()
		{
			ClearAll();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		internal void Register(ItemDrop drop)
		{
			if (!Enabled.Value || (Object)(object)drop == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)drop).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			foreach (PendingDrop item in _pending)
			{
				if ((Object)(object)item.Drop == (Object)(object)drop)
				{
					return;
				}
			}
			_pending.Add(new PendingDrop
			{
				Drop = drop,
				NView = component,
				DropTime = Time.time,
				NextRetarget = 0f
			});
		}

		private void Update()
		{
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time >= _nextRepair)
			{
				_nextRepair = Time.time + 1f;
				AutoRepairer.Tick();
			}
			if (Time.time >= _nextFeed)
			{
				_nextFeed = Time.time + 1.5f;
				AutoFeeder.Tick();
			}
			if (_pending.Count == 0 && _highlightedPrev.Count == 0)
			{
				return;
			}
			if (!Enabled.Value || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)MaterialMan.instance == (Object)null)
			{
				ClearAll();
				return;
			}
			_highlightedNow.Clear();
			float time = Time.time;
			float value = Delay.Value;
			for (int num = _pending.Count - 1; num >= 0; num--)
			{
				PendingDrop pendingDrop = _pending[num];
				if ((Object)(object)pendingDrop.Drop == (Object)null || (Object)(object)pendingDrop.NView == (Object)null || !pendingDrop.NView.IsValid())
				{
					_pending.RemoveAt(num);
				}
				else
				{
					if (time >= pendingDrop.NextRetarget || (pendingDrop.Target != null && (Object)(object)pendingDrop.Target == (Object)null))
					{
						pendingDrop.NextRetarget = time + 0.25f;
						pendingDrop.Target = FindBestTarget(pendingDrop.Drop);
					}
					float num2 = time - pendingDrop.DropTime;
					if ((Object)(object)pendingDrop.Target == (Object)null)
					{
						ResetHighlight(((Component)pendingDrop.Drop).gameObject);
						if (num2 >= value)
						{
							_pending.RemoveAt(num);
						}
					}
					else if (num2 >= value)
					{
						if (!pendingDrop.NView.IsOwner())
						{
							pendingDrop.Drop.RequestOwn();
							if (num2 < value + 3f)
							{
								Highlight(((Component)pendingDrop.Drop).gameObject, ItemColor.Value);
								MarkContainer(pendingDrop.Target);
							}
							else
							{
								ResetHighlight(((Component)pendingDrop.Drop).gameObject);
								_pending.RemoveAt(num);
							}
						}
						else
						{
							ResetHighlight(((Component)pendingDrop.Drop).gameObject);
							Deposit(pendingDrop.Drop, pendingDrop.NView);
							_pending.RemoveAt(num);
						}
					}
					else
					{
						Highlight(((Component)pendingDrop.Drop).gameObject, ItemColor.Value);
						MarkContainer(pendingDrop.Target);
					}
				}
			}
			foreach (GameObject item in _highlightedPrev)
			{
				if ((Object)(object)item != (Object)null && !_highlightedNow.Contains(item))
				{
					ResetHighlight(item);
				}
			}
			HashSet<GameObject> highlightedPrev = _highlightedPrev;
			_highlightedPrev = new HashSet<GameObject>(_highlightedNow);
			highlightedPrev.Clear();
		}

		private void MarkContainer(Container c)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = HighlightRoot(c);
			if (!((Object)(object)val == (Object)null))
			{
				Highlight(val, ContainerColor.Value);
				_highlightedNow.Add(val);
			}
		}

		private static GameObject HighlightRoot(Container c)
		{
			if ((Object)(object)c == (Object)null)
			{
				return null;
			}
			if (!((Object)(object)c.m_rootObjectOverride != (Object)null))
			{
				return ((Component)c).gameObject;
			}
			return ((Component)c.m_rootObjectOverride).gameObject;
		}

		private static void Highlight(GameObject go, Color color)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)go == (Object)null) && !((Object)(object)MaterialMan.instance == (Object)null))
			{
				MaterialMan.instance.SetValue<Color>(go, EmissionColorId, color * 0.6f, false);
				MaterialMan.instance.SetValue<Color>(go, ColorId, color, false);
			}
		}

		private static void ResetHighlight(GameObject go)
		{
			if (!((Object)(object)go == (Object)null) && !((Object)(object)MaterialMan.instance == (Object)null))
			{
				MaterialMan.instance.ResetValue(go, ColorId);
				MaterialMan.instance.ResetValue(go, EmissionColorId);
			}
		}

		private void ClearAll()
		{
			foreach (PendingDrop item in _pending)
			{
				if ((Object)(object)item.Drop != (Object)null)
				{
					ResetHighlight(((Component)item.Drop).gameObject);
				}
			}
			foreach (GameObject item2 in _highlightedPrev)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					ResetHighlight(item2);
				}
			}
			_pending.Clear();
			_highlightedPrev.Clear();
			_highlightedNow.Clear();
		}

		private static Container FindBestTarget(ItemDrop drop)
		{
			List<Container> list = FindCandidates(drop);
			if (list.Count <= 0)
			{
				return null;
			}
			return list[0];
		}

		private static List<Container> FindCandidates(ItemDrop drop)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			if ((Object)(object)drop == (Object)null || drop.m_itemData?.m_shared == null)
			{
				return list;
			}
			ItemData itemData = drop.m_itemData;
			string name = itemData.m_shared.m_name;
			Vector3 position = ((Component)drop).transform.position;
			float num = Radius.Value * Radius.Value;
			long playerId = (((Object)(object)Game.instance != (Object)null) ? Game.instance.GetPlayerProfile().GetPlayerID() : 0);
			List<KeyValuePair<float, Container>> list2 = new List<KeyValuePair<float, Container>>();
			for (int num2 = Containers.Count - 1; num2 >= 0; num2--)
			{
				Container val = Containers[num2];
				if ((Object)(object)val == (Object)null)
				{
					Containers.RemoveAt(num2);
				}
				else
				{
					Vector3 val2 = ((Component)val).transform.position - position;
					float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
					if (!(sqrMagnitude > num) && IsUsable(val, playerId))
					{
						Inventory inventory = val.GetInventory();
						if (inventory.ContainsItemByName(name) && (inventory.FindFreeStackSpace(name, (float)itemData.m_worldLevel) > 0 || inventory.HaveEmptySlot()))
						{
							list2.Add(new KeyValuePair<float, Container>(sqrMagnitude, val));
						}
					}
				}
			}
			list2.Sort((KeyValuePair<float, Container> a, KeyValuePair<float, Container> b) => a.Key.CompareTo(b.Key));
			foreach (KeyValuePair<float, Container> item in list2)
			{
				list.Add(item.Value);
			}
			return list;
		}

		internal static bool IsUsable(Container c, long playerId)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (!((Behaviour)c).isActiveAndEnabled)
			{
				return false;
			}
			if (c.GetInventory() == null)
			{
				return false;
			}
			if (c.m_autoDestroyEmpty)
			{
				return false;
			}
			if ((Object)(object)((Component)c).GetComponent<TombStone>() != (Object)null)
			{
				return false;
			}
			if ((Object)(object)c.m_wagon != (Object)null && c.m_wagon.InUse())
			{
				return false;
			}
			ZNetView val = ContainerNView.Invoke(c);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			PrivacySetting privacy = c.m_privacy;
			if ((int)privacy != 0)
			{
				if ((int)privacy == 1)
				{
					return false;
				}
			}
			else
			{
				Piece component = ((Component)c).GetComponent<Piece>();
				if ((Object)(object)component == (Object)null || component.GetCreator() != playerId)
				{
					return false;
				}
			}
			if (c.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)c).transform.position, 0f, false, false))
			{
				return false;
			}
			if (!val.IsOwner() && val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
			{
				return false;
			}
			return true;
		}

		private static void Deposit(ItemDrop drop, ZNetView dropView)
		{
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			ItemData itemData = drop.m_itemData;
			if (itemData == null || itemData.m_shared == null)
			{
				return;
			}
			ItemData val = itemData.Clone();
			if ((Object)(object)val.m_dropPrefab == (Object)null && (Object)(object)ObjectDB.instance != (Object)null)
			{
				val.m_dropPrefab = ObjectDB.instance.GetItemPrefab(Utils.GetPrefabName(((Component)drop).gameObject));
			}
			if ((Object)(object)val.m_dropPrefab == (Object)null)
			{
				return;
			}
			int stack = val.m_stack;
			Container val2 = null;
			foreach (Container item in FindCandidates(drop))
			{
				ZNetView val3 = ContainerNView.Invoke(item);
				if (!val3.IsOwner())
				{
					if (val3.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
					{
						continue;
					}
					val3.ClaimOwnership();
				}
				try
				{
					ContainerLoad?.Invoke(item, null);
				}
				catch (Exception)
				{
				}
				if (item.GetInventory().ContainsItemByName(itemData.m_shared.m_name))
				{
					int stack2 = val.m_stack;
					bool num = item.GetInventory().AddItem(val);
					if ((num || val.m_stack < stack2) && (Object)(object)val2 == (Object)null)
					{
						val2 = item;
					}
					if (num)
					{
						val = null;
						break;
					}
				}
			}
			int num2 = val?.m_stack ?? 0;
			int num3 = stack - num2;
			if (num3 > 0)
			{
				if (num2 <= 0)
				{
					dropView.Destroy();
				}
				else
				{
					drop.SetStack(num2);
				}
				if ((Object)(object)val2 != (Object)null && (Object)(object)InventoryGui.instance != (Object)null)
				{
					InventoryGui.instance.m_moveItemEffects.Create(((Component)val2).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
				if (ShowMessage.Value && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					((Character)Player.m_localPlayer).Message((MessageType)1, "Quality_of_Cacao: " + Localization.instance.Localize(itemData.m_shared.m_name), num3, itemData.GetIcon(), false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerAwakePatch
	{
		private static void Postfix(Container __instance)
		{
			if (__instance.GetInventory() != null && !QualityOfCacaoPlugin.Containers.Contains(__instance))
			{
				QualityOfCacaoPlugin.Containers.Add(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "DropItem")]
	internal static class HumanoidDropItemPatch
	{
		internal static bool DroppingFromPlayerInventory;

		private static void Prefix(Humanoid __instance, Inventory inventory)
		{
			DroppingFromPlayerInventory = (Object)(object)__instance != (Object)null && (Object)(object)__instance == (Object)(object)Player.m_localPlayer && (inventory == null || inventory == __instance.GetInventory());
		}

		private static void Finalizer()
		{
			DroppingFromPlayerInventory = false;
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "OnPlayerDrop")]
	internal static class ItemDropOnPlayerDropPatch
	{
		private static void Postfix(ItemDrop __instance)
		{
			if (HumanoidDropItemPatch.DroppingFromPlayerInventory)
			{
				QualityOfCacaoPlugin.Instance?.Register(__instance);
			}
		}
	}
}