Decompiled source of SorosQualityOfLifeAddon v1.0.1

plugins/SorosQualityOfLifeAddon.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[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("SorosQualityOfLifeAddon")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("SorosQualityOfLifeAddon")]
[assembly: AssemblyTitle("SorosQualityOfLifeAddon")]
[assembly: AssemblyVersion("1.0.1.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 SorosQualityOfLifeAddon
{
	internal static class ItemNet
	{
		public static void Write(ZPackage p, ItemData it)
		{
			p.Write(Object.op_Implicit((Object)(object)it.m_dropPrefab) ? ((Object)it.m_dropPrefab).name : "");
			p.Write(it.m_stack);
			p.Write(it.m_quality);
			p.Write(it.m_variant);
			p.Write(it.m_durability);
			p.Write(it.m_crafterID);
			p.Write(it.m_crafterName ?? "");
			p.Write(it.m_worldLevel);
			p.Write(it.m_customData?.Count ?? 0);
			if (it.m_customData == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> customDatum in it.m_customData)
			{
				p.Write(customDatum.Key);
				p.Write(customDatum.Value);
			}
		}

		public static ItemData Read(ZPackage p)
		{
			string text = p.ReadString();
			int stack = p.ReadInt();
			int quality = p.ReadInt();
			int variant = p.ReadInt();
			float durability = p.ReadSingle();
			long crafterID = p.ReadLong();
			string crafterName = p.ReadString();
			int worldLevel = p.ReadInt();
			int num = p.ReadInt();
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			for (int i = 0; i < num; i++)
			{
				dictionary[p.ReadString()] = p.ReadString();
			}
			GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(text) : null);
			ItemDrop val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Unknown item prefab in RPC: " + text));
				return null;
			}
			ItemData obj = val2.m_itemData.Clone();
			obj.m_dropPrefab = val;
			obj.m_stack = stack;
			obj.m_quality = quality;
			obj.m_variant = variant;
			obj.m_durability = durability;
			obj.m_crafterID = crafterID;
			obj.m_crafterName = crafterName;
			obj.m_worldLevel = worldLevel;
			obj.m_customData = dictionary;
			return obj;
		}

		public static ItemData FromPrefab(string prefabName, int stack)
		{
			GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(prefabName) : null);
			ItemDrop val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			ItemData obj = val2.m_itemData.Clone();
			obj.m_dropPrefab = val;
			obj.m_stack = stack;
			return obj;
		}

		public static int AddAsMuch(Inventory inv, ItemData item)
		{
			int num = item.m_stack;
			int num2 = Mathf.Max(1, item.m_shared.m_maxStackSize);
			while (num > 0)
			{
				int num3 = Mathf.Min(num, num2);
				ItemData val = item.Clone();
				val.m_stack = num3;
				if (inv.CanAddItem(val, num3) && inv.AddItem(val))
				{
					num -= num3;
					continue;
				}
				ItemData val2 = item.Clone();
				val2.m_stack = 1;
				if (!inv.CanAddItem(val2, 1) || !inv.AddItem(val2))
				{
					break;
				}
				num--;
			}
			return num;
		}

		public static void Drop(ItemData item, int amount, Vector3 pos)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//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)
			if (item != null && amount > 0)
			{
				ItemDrop.DropItem(item, amount, pos + Vector3.up, Quaternion.identity);
			}
		}

		public static void GiveLocalPlayer(ItemData item)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && item != null)
			{
				int num = AddAsMuch(((Humanoid)localPlayer).GetInventory(), item);
				if (num > 0)
				{
					Drop(item, num, ((Component)localPlayer).transform.position);
				}
			}
		}
	}
	internal static class MainCompat
	{
		internal static Type SpecialChestType;

		private static FieldInfo _isTransfer;

		private static FieldInfo _container;

		private static FieldInfo _nview;

		private static PropertyInfo _targetName;

		private const float Range = 50f;

		internal static void Init(Harmony h)
		{
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			SpecialChestType = AccessTools.TypeByName("SorosQualityOfLife.SpecialChest");
			if (SpecialChestType == null)
			{
				Plugin.Log.LogInfo((object)"Main mod not found: naming only.");
				return;
			}
			_isTransfer = AccessTools.Field(SpecialChestType, "IsTransfer");
			_container = AccessTools.Field(SpecialChestType, "m_container");
			_nview = AccessTools.Field(SpecialChestType, "m_nview");
			_targetName = AccessTools.Property(SpecialChestType, "TargetName");
			MethodInfo methodInfo = AccessTools.Method(SpecialChestType, "TransferTick", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(SpecialChestType, "TransferStatus", (Type[])null, (Type[])null);
			if (_isTransfer == null || _container == null || _nview == null || _targetName == null || methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Main mod found, but its Transfer Chest API differs: vanilla targets disabled.");
				return;
			}
			h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(MainCompat), "TickPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (methodInfo2 != null)
			{
				h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(MainCompat), "StatusPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Plugin.Log.LogInfo((object)"Main mod found: named vanilla chests are Transfer Chest targets.");
		}

		private static List<Container> Targets(Component chest, out Container own, out ZNetView ownNv)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			object? value = _container.GetValue(chest);
			own = (Container)((value is Container) ? value : null);
			object? value2 = _nview.GetValue(chest);
			ownNv = (ZNetView)((value2 is ZNetView) ? value2 : null);
			List<Container> list = new List<Container>();
			if (!Names.Enabled || !(bool)_isTransfer.GetValue(chest))
			{
				return list;
			}
			string text = ((_targetName.GetValue(chest, null) as string) ?? "").Trim();
			if (text.Length == 0)
			{
				return list;
			}
			Vector3 pos = chest.transform.position;
			Names.All.RemoveAll((Container c) => (Object)(object)c == (Object)null);
			foreach (Container item in Names.All)
			{
				if (!((Object)(object)item == (Object)(object)own) && !(Vector3.Distance(((Component)item).transform.position, pos) > 50f))
				{
					ZNetView val = Acc.NView(item);
					if (!((Object)(object)val == (Object)null) && val.IsValid() && item.GetInventory() != null && string.Equals(Names.Get(item), text, StringComparison.OrdinalIgnoreCase))
					{
						list.Add(item);
					}
				}
			}
			return list.OrderBy((Container c) => Vector3.Distance(((Component)c).transform.position, pos)).ToList();
		}

		private static void TickPostfix(object __instance)
		{
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Component val = (Component)((__instance is Component) ? __instance : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				Container own;
				ZNetView ownNv;
				List<Container> list = Targets(val, out own, out ownNv);
				if (list.Count == 0 || (Object)(object)own == (Object)null || (Object)(object)ownNv == (Object)null || !ownNv.IsValid() || !ownNv.IsOwner())
				{
					return;
				}
				Inventory inventory = own.GetInventory();
				if (inventory == null)
				{
					return;
				}
				int num = 0;
				foreach (ItemData item in inventory.GetAllItems().ToList())
				{
					if (item == null || item.m_stack <= 0 || (Object)(object)item.m_dropPrefab == (Object)null)
					{
						continue;
					}
					foreach (Container item2 in list)
					{
						if (item.m_stack <= 0)
						{
							break;
						}
						Inventory inventory2 = item2.GetInventory();
						if (!inventory2.CanAddItem(item, 1))
						{
							continue;
						}
						ZNetView val2 = Acc.NView(item2);
						if (val2.IsOwner())
						{
							int stack = item.m_stack;
							int num2 = ItemNet.AddAsMuch(inventory2, item);
							if (stack - num2 > 0)
							{
								inventory.RemoveItem(item, stack - num2);
							}
						}
						else if (num < 1)
						{
							ItemData val3 = item.Clone();
							if (inventory.RemoveItem(item, val3.m_stack))
							{
								ZPackage val4 = new ZPackage();
								ItemNet.Write(val4, val3);
								val2.InvokeRPC("SoroQoL_Transfer", new object[2]
								{
									ownNv.GetZDO().m_uid,
									val4
								});
								num++;
								break;
							}
						}
					}
				}
			}
			catch (Exception e)
			{
				Safe.Report("MainCompat.Tick", e);
			}
		}

		private static void StatusPostfix(object __instance, ref string __result)
		{
			try
			{
				if (__result != "target not found" && __result != "target full")
				{
					return;
				}
				Container own;
				ZNetView ownNv;
				List<Container> list = Targets((Component)((__instance is Component) ? __instance : null), out own, out ownNv);
				if (list.Count == 0)
				{
					return;
				}
				Inventory val = (((Object)(object)own != (Object)null) ? own.GetInventory() : null);
				if (val == null || val.GetAllItems().Count == 0)
				{
					__result = "ready, nothing to move";
					return;
				}
				foreach (ItemData allItem in val.GetAllItems())
				{
					foreach (Container item in list)
					{
						if (item.GetInventory().CanAddItem(allItem, 1))
						{
							__result = "ready";
							return;
						}
					}
				}
				__result = "target full";
			}
			catch (Exception e)
			{
				Safe.Report("MainCompat.Status", e);
			}
		}
	}
	internal static class NamePanel
	{
		[HarmonyPatch(typeof(InventoryGui), "Update")]
		private static class Button
		{
			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static UnityAction <>9__3_0;

				internal void <Create>b__3_0()
				{
					Open = !Open;
				}
			}

			private static Button _btn;

			private static Container _last;

			private static void Postfix(InventoryGui __instance)
			{
				try
				{
					Container val = (InventoryGui.IsVisible() ? Acc.CurrentContainer(__instance) : null);
					if ((Object)(object)val != (Object)(object)_last)
					{
						Open = false;
						_last = val;
					}
					bool flag = (Object)(object)val != (Object)null && Names.Enabled && Names.Eligible(val);
					if (flag && (Object)(object)_btn == (Object)null)
					{
						Create(__instance);
					}
					if ((Object)(object)_btn != (Object)null && ((Component)_btn).gameObject.activeSelf != flag)
					{
						((Component)_btn).gameObject.SetActive(flag);
					}
				}
				catch (Exception e)
				{
					Safe.Report("NameButton", e);
				}
			}

			private static void Create(InventoryGui gui)
			{
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Expected O, but got Unknown
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Unknown result type (might be due to invalid IL or missing references)
				//IL_0118: Expected O, but got Unknown
				//IL_0119: Unknown result type (might be due to invalid IL or missing references)
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0124: Unknown result type (might be due to invalid IL or missing references)
				//IL_0138: Unknown result type (might be due to invalid IL or missing references)
				//IL_013d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0173: Unknown result type (might be due to invalid IL or missing references)
				//IL_017d: Expected O, but got Unknown
				//IL_019b: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a6: Expected O, but got Unknown
				Button stackAllButton = gui.m_stackAllButton;
				if ((Object)(object)stackAllButton == (Object)null)
				{
					return;
				}
				GameObject val = Object.Instantiate<GameObject>(((Component)stackAllButton).gameObject, ((Component)stackAllButton).transform.parent);
				((Object)val).name = "SoroQoLAddon_Name";
				MonoBehaviour[] componentsInChildren = val.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val2 in componentsInChildren)
				{
					string name = ((object)val2).GetType().Name;
					if (name == "UIGamePad" || name == "Localize")
					{
						Object.DestroyImmediate((Object)(object)val2);
					}
				}
				foreach (Transform item in val.transform)
				{
					Transform val3 = item;
					if (((Object)val3).name.ToLowerInvariant().Contains("gamepad") || ((Object)val3).name.ToLowerInvariant().Contains("hint"))
					{
						((Component)val3).gameObject.SetActive(false);
					}
				}
				RectTransform val4 = (RectTransform)val.transform;
				RectTransform val5 = (RectTransform)((Component)stackAllButton).transform;
				Vector2 anchoredPosition = val5.anchoredPosition;
				Rect rect = val5.rect;
				val4.anchoredPosition = anchoredPosition + new Vector2(((Rect)(ref rect)).width + 10f, 0f);
				TMP_Text componentInChildren = val.GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.text = "Name";
				}
				_btn = val.GetComponent<Button>();
				_btn.onClick = new ButtonClickedEvent();
				ButtonClickedEvent onClick = _btn.onClick;
				object obj = <>c.<>9__3_0;
				if (obj == null)
				{
					UnityAction val6 = delegate
					{
						Open = !Open;
					};
					<>c.<>9__3_0 = val6;
					obj = (object)val6;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				((Selectable)_btn).interactable = true;
			}
		}

		internal static bool Open;

		internal static bool Typing;

		private static Rect _rect = new Rect(20f, 120f, 260f, 0f);

		private static Container _for;

		private static string _buf = "";

		private const string Ctl = "SoroQoLAddon_Name";

		public static void Draw()
		{
			//IL_0066: 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_0086: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			InventoryGui instance = InventoryGui.instance;
			Container cur = (((Object)(object)instance != (Object)null && InventoryGui.IsVisible()) ? Acc.CurrentContainer(instance) : null);
			if ((Object)(object)cur == (Object)null || !Open || !Names.Enabled || !Names.Eligible(cur))
			{
				Typing = false;
				_for = null;
				return;
			}
			_rect = GUILayout.Window(20641, _rect, (WindowFunction)delegate
			{
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Invalid comparison between Unknown and I4
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Invalid comparison between Unknown and I4
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Invalid comparison between Unknown and I4
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Invalid comparison between Unknown and I4
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Invalid comparison between Unknown and I4
				if ((Object)(object)_for != (Object)(object)cur)
				{
					_for = cur;
					_buf = Names.Get(cur);
				}
				GUILayout.Label("Name (empty = default):", Array.Empty<GUILayoutOption>());
				Event current = Event.current;
				bool num = GUI.GetNameOfFocusedControl() == "SoroQoLAddon_Name";
				bool flag = num && (int)current.type == 4 && ((int)current.keyCode == 13 || (int)current.keyCode == 271);
				bool flag2 = num && (int)current.type == 4 && (int)current.keyCode == 27;
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUI.SetNextControlName("SoroQoLAddon_Name");
				_buf = GUILayout.TextField(_buf ?? "", 30, Array.Empty<GUILayoutOption>());
				bool num2 = GUILayout.Button("Save", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) });
				GUILayout.EndHorizontal();
				if (num2 || flag)
				{
					Names.Request(cur, _buf);
					_buf = Names.Sanitize(_buf);
					GUI.FocusControl((string)null);
					if (flag)
					{
						current.Use();
					}
				}
				else if (flag2)
				{
					GUI.FocusControl((string)null);
					_buf = Names.Get(cur);
					current.Use();
				}
				Typing = GUI.GetNameOfFocusedControl() == "SoroQoLAddon_Name";
				GUI.DragWindow();
			}, "Chest name", Array.Empty<GUILayoutOption>());
		}
	}
	internal static class Names
	{
		[HarmonyPatch(typeof(Container), "Awake")]
		private static class Register
		{
			private static void Postfix(Container __instance)
			{
				try
				{
					if (!Candidate(__instance))
					{
						return;
					}
					ZNetView nv = Acc.NView(__instance);
					if ((Object)(object)nv == (Object)null || nv.GetZDO() == null)
					{
						return;
					}
					All.Add(__instance);
					nv.Register<string>("SoroQoL_SetName", (Action<long, string>)delegate(long sender, string name)
					{
						Safe.Run("SetName", delegate
						{
							if (nv.IsOwner() && Enabled && Eligible(__instance))
							{
								nv.GetZDO().Set("soro_name", Sanitize(name));
							}
						});
					});
					nv.Register<ZDOID, ZPackage>("SoroQoL_Transfer", (Action<long, ZDOID, ZPackage>)delegate(long sender, ZDOID src, ZPackage p)
					{
						//IL_000c: Unknown result type (might be due to invalid IL or missing references)
						Receive(nv, __instance, src, p);
					});
				}
				catch (Exception e)
				{
					Safe.Report("Register", e);
				}
			}
		}

		[HarmonyPatch(typeof(Container), "GetHoverText")]
		private static class Hover
		{
			private static void Postfix(Container __instance, ref string __result)
			{
				try
				{
					string text = Get(__instance);
					if (text.Length != 0 && __result != null)
					{
						string text2 = ((Localization.instance != null) ? Localization.instance.Localize(__instance.m_name ?? "") : (__instance.m_name ?? ""));
						int num = ((text2.Length > 0) ? __result.IndexOf(text2, StringComparison.Ordinal) : (-1));
						__result = ((num >= 0) ? (__result.Substring(0, num) + "\"" + text + "\" (" + text2 + ")" + __result.Substring(num + text2.Length)) : ("\"" + text + "\"\n" + __result));
					}
				}
				catch (Exception e)
				{
					Safe.Report("Hover", e);
				}
			}
		}

		[HarmonyPatch(typeof(Container), "GetHoverName")]
		private static class Title
		{
			private static void Postfix(Container __instance, ref string __result)
			{
				try
				{
					string text = Get(__instance);
					if (text.Length > 0)
					{
						__result = text;
					}
				}
				catch (Exception e)
				{
					Safe.Report("Title", e);
				}
			}
		}

		[HarmonyPatch(typeof(Chat), "HasFocus")]
		private static class BlockInput
		{
			private static void Postfix(ref bool __result)
			{
				try
				{
					if (NamePanel.Typing)
					{
						__result = true;
					}
				}
				catch (Exception e)
				{
					Safe.Report("BlockInput", e);
				}
			}
		}

		internal const string NameKey = "soro_name";

		internal const string RpcSetName = "SoroQoL_SetName";

		internal const string RpcTransfer = "SoroQoL_Transfer";

		internal const string RpcReturn = "SoroQoL_Return";

		internal const int MaxLen = 30;

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

		internal static bool Enabled => Plugin.EnableNaming.Value;

		internal static bool IsMainModChest(Container c)
		{
			if (MainCompat.SpecialChestType != null)
			{
				return (Object)(object)((Component)c).GetComponent(MainCompat.SpecialChestType) != (Object)null;
			}
			return false;
		}

		internal static bool Candidate(Container c)
		{
			if ((Object)(object)c != (Object)null && (Object)(object)c.m_wagon == (Object)null && (Object)(object)((Component)c).GetComponentInParent<Ship>() == (Object)null && (Object)(object)((Component)c).GetComponent<TombStone>() == (Object)null && (Object)(object)((Component)c).GetComponentInParent<Piece>() != (Object)null)
			{
				return !IsMainModChest(c);
			}
			return false;
		}

		internal static bool Eligible(Container c)
		{
			if (!Candidate(c))
			{
				return false;
			}
			Piece componentInParent = ((Component)c).GetComponentInParent<Piece>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				return componentInParent.IsPlacedByPlayer();
			}
			return false;
		}

		internal static string Sanitize(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			s = Regex.Replace(s, "<[^>]*>", "");
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			string text = s;
			foreach (char c in text)
			{
				if (!char.IsControl(c) && c != '<' && c != '>')
				{
					stringBuilder.Append(c);
				}
			}
			s = stringBuilder.ToString().Trim();
			if (s.Length > 30)
			{
				s = s.Substring(0, 30).Trim();
			}
			return s;
		}

		internal static string Get(Container c)
		{
			if (!Enabled || !Eligible(c))
			{
				return "";
			}
			ZNetView val = Acc.NView(c);
			ZDO val2 = (((Object)(object)val != (Object)null && val.IsValid()) ? val.GetZDO() : null);
			if (val2 != null)
			{
				return Sanitize(val2.GetString("soro_name", ""));
			}
			return "";
		}

		internal static void Request(Container c, string name)
		{
			ZNetView val = Acc.NView(c);
			if ((Object)(object)val != (Object)null && val.IsValid())
			{
				val.InvokeRPC("SoroQoL_SetName", new object[1] { Sanitize(name) });
			}
		}

		internal static void Receive(ZNetView nv, Container c, ZDOID source, ZPackage p)
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			ItemData val = null;
			try
			{
				if ((Object)(object)nv == (Object)null || !nv.IsOwner())
				{
					return;
				}
				val = ItemNet.Read(p);
				if (val == null)
				{
					return;
				}
				int num = ItemNet.AddAsMuch(c.GetInventory(), val);
				if (num <= 0)
				{
					val = null;
					return;
				}
				val.m_stack = num;
				GameObject val2 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.FindInstance(source) : null);
				ZNetView val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetComponent<ZNetView>() : null);
				if ((Object)(object)val3 != (Object)null && val3.IsValid())
				{
					ZPackage val4 = new ZPackage();
					ItemNet.Write(val4, val);
					val3.InvokeRPC("SoroQoL_Return", new object[1] { val4 });
				}
				else
				{
					ItemNet.Drop(val, num, ((Component)c).transform.position);
				}
				val = null;
			}
			catch (Exception e)
			{
				Safe.Report("Receive", e);
				if (val != null)
				{
					ItemNet.Drop(val, val.m_stack, ((Component)c).transform.position);
				}
			}
		}
	}
	internal static class PityDrops
	{
		private const string Key = "NoPseudoDrops";

		private static ZoneSystem _appliedFor;

		private static float _nextCheck;

		internal static void Tick()
		{
			if (Plugin.DisablePityDrops == null || !Plugin.DisablePityDrops.Value || Time.unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.unscaledTime + 2f;
			ZoneSystem instance = ZoneSystem.instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && instance != _appliedFor && !((Object)(object)Game.instance == (Object)null))
			{
				_appliedFor = instance;
				if (instance.GetGlobalKey("NoPseudoDrops"))
				{
					Plugin.Log.LogInfo((object)"World key NoPseudoDrops already set: pity drops disabled.");
					return;
				}
				instance.SetGlobalKey("NoPseudoDrops");
				Plugin.Log.LogInfo((object)"Set world key NoPseudoDrops: Valheim's 30% pity drop system disabled (purely random drops).");
			}
		}
	}
	[BepInPlugin("soro.qol.addon", "Soro's Quality of life mod Addon", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "soro.qol.addon";

		public const string ModName = "Soro's Quality of life mod Addon";

		public const string Version = "1.0.1";

		public const string MainGuid = "soro.qualityoflife";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> EnableNaming;

		internal static ConfigEntry<bool> DisablePityDrops;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			EnableNaming = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Vanilla chest naming", true, "Adds a Settings button with a name field to player-built vanilla chests. Named chests can be targets of the main mod's Transfer Chests.");
			DisablePityDrops = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisablePityDrops", true, "Host/server only: sets the vanilla world key NoPseudoDrops on world load, turning off the 30% pity (pseudo-random) drop system. Turning this off does NOT remove the key; use `removekey NoPseudoDrops` in the console.");
			_harmony = new Harmony("soro.qol.addon");
			Type[] types = typeof(Plugin).Assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0)
				{
					try
					{
						_harmony.CreateClassProcessor(type).Patch();
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("Patch " + type.Name + " failed: " + ex.Message));
					}
				}
			}
			try
			{
				MainCompat.Init(_harmony);
			}
			catch (Exception ex2)
			{
				Log.LogWarning((object)("Main mod integration failed (naming still works): " + ex2.Message));
			}
			Log.LogInfo((object)"Soro's Quality of life mod Addon 1.0.1 loaded.");
		}

		private void Update()
		{
			Safe.Run("PityDrops", PityDrops.Tick);
		}

		private void OnGUI()
		{
			Safe.Run("NamePanel", NamePanel.Draw);
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class Safe
	{
		private static readonly Dictionary<string, float> _last = new Dictionary<string, float>();

		public static void Run(string where, Action a)
		{
			try
			{
				a();
			}
			catch (Exception e)
			{
				Report(where, e);
			}
		}

		public static void Report(string where, Exception e)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!_last.TryGetValue(where, out var value) || !(realtimeSinceStartup - value < 10f))
			{
				_last[where] = realtimeSinceStartup;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[" + where + "] " + e));
				}
			}
		}
	}
	internal static class Acc
	{
		private static FieldRef<InventoryGui, Container> _cur;

		private static FieldRef<Container, ZNetView> _nview;

		private static bool _init;

		private static void Init()
		{
			if (_init)
			{
				return;
			}
			_init = true;
			try
			{
				_cur = AccessTools.FieldRefAccess<InventoryGui, Container>("m_currentContainer");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("m_currentContainer: " + ex.Message));
			}
			try
			{
				_nview = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Container.m_nview: " + ex2.Message));
			}
		}

		internal static Container CurrentContainer(InventoryGui g)
		{
			Init();
			if (!((Object)(object)g != (Object)null) || _cur == null)
			{
				return null;
			}
			return _cur.Invoke(g);
		}

		internal static ZNetView NView(Container c)
		{
			Init();
			if (!((Object)(object)c != (Object)null) || _nview == null)
			{
				return null;
			}
			return _nview.Invoke(c);
		}
	}
}