Decompiled source of SimpleLabels v2.2.1

Mods\SimpleLabels.dll

Decompiled 19 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Building;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Management;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.StationFramework;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.Tiles;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Management;
using Il2CppScheduleOne.UI.Stations;
using Il2CppSteamworks;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using SimpleLabels;
using SimpleLabels.Data;
using SimpleLabels.Services;
using SimpleLabels.Settings;
using SimpleLabels.UI;
using SimpleLabels.Utils;
using SteamNetworkLib;
using SteamNetworkLib.Core;
using SteamNetworkLib.Models;
using SteamNetworkLib.Sync;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(LabelMod), "SimpleLabels", "2.2.1", "tiagovito", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: AssemblyMetadata("NexusModID", "680")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SimpleLabels")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("SimpleLabels Mod")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SimpleLabels")]
[assembly: AssemblyTitle("SimpleLabels")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	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 SimpleLabels
{
	public class LabelMod : MelonMod
	{
		[CompilerGenerated]
		private sealed class <SaveLabelsAfterGameSave>d__5 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <SaveLabelsAfterGameSave>d__5(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(2f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					LabelDataManager.SaveLabelTrackerData();
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private static string _previousSceneName = string.Empty;

		public override void OnInitializeMelon()
		{
			((MelonBase)this).OnInitializeMelon();
			MelonLogger.Msg("[Mod] Initializing SimpleLabels mod...");
			ModSettings.Initialize();
			LabelDataManager.Initialize();
			LabelNetworkManager.Initialize();
			Logger.Msg("[Mod] SimpleLabels mod initialized successfully");
		}

		public override void OnDeinitializeMelon()
		{
			LabelNetworkManager.Terminate();
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (!(sceneName == "Main"))
			{
				if (sceneName == "Menu" && _previousSceneName == "Main")
				{
					DeactivateMod();
				}
			}
			else
			{
				ActivateMod();
			}
			_previousSceneName = sceneName;
		}

		private static void ActivateMod()
		{
			Logger.Msg("[Mod] Activating mod in Main scene");
			LabelPrefabManager.Initialize();
			InputFieldManager.Initialize();
			Singleton<SaveManager>.Instance.onSaveStart.AddListener(UnityAction.op_Implicit((Action)delegate
			{
				MelonCoroutines.Start(SaveLabelsAfterGameSave());
			}));
			if (MelonTypeBase<MelonMod>.RegisteredMelons.Any((MelonMod mod) => ((MelonBase)mod).Info.Name == "Mod Manager & Phone App"))
			{
				Logger.Msg("[Mod] Mod Manager & Phone App detected, initializing integration");
				ModManagerIntegration.Initialize();
			}
		}

		[IteratorStateMachine(typeof(<SaveLabelsAfterGameSave>d__5))]
		private static IEnumerator SaveLabelsAfterGameSave()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <SaveLabelsAfterGameSave>d__5(0);
		}

		private static void DeactivateMod()
		{
			Logger.Msg("[Mod] Deactivating mod");
			InputFieldManager.Terminate();
			LabelPrefabManager.Terminate();
			LabelApplier.Terminate();
			Logger.Msg("[Mod] Resetting label data for new game session");
			LabelDataManager.Initialize();
		}

		public override void OnUpdate()
		{
			LabelNetworkManager.Update();
		}
	}
}
namespace SimpleLabels.Utils
{
	public class DevUtils
	{
		public static bool IsStorageOrStationOpen()
		{
			return Singleton<StorageMenu>.Instance.IsOpen || Singleton<BrickPressCanvas>.Instance.isOpen || Singleton<CauldronCanvas>.Instance.isOpen || Singleton<ChemistryStationCanvas>.Instance.isOpen || Singleton<DryingRackCanvas>.Instance.isOpen || Singleton<LabOvenCanvas>.Instance.isOpen || Singleton<MixingStationCanvas>.Instance.isOpen || Singleton<PackagingStationCanvas>.Instance.isOpen || Singleton<MushroomSpawnStationInterface>.Instance.IsOpen;
		}
	}
	public static class Logger
	{
		public static void Msg(string message)
		{
			if (ModSettings.ShowDebug != null && ModSettings.ShowDebug.Value)
			{
				MelonLogger.Msg(message);
			}
		}

		public static void Warning(string message)
		{
			MelonLogger.Warning(message);
		}

		public static void Error(string message)
		{
			MelonLogger.Error(message);
		}
	}
	public class SpriteManager
	{
		public static Sprite LoadEmbeddedSprite(string resourceName, Vector4 customBorders)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_00a6: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetName().Name + ".Resources." + resourceName;
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, Il2CppStructArray<byte>.op_Implicit(array)))
			{
				MelonLogger.Error("Failed to load texture");
				return null;
			}
			((Object)val).name = resourceName.Replace(".png", "");
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0, customBorders);
		}

		public static Sprite LoadGameSprite(string spriteName, Vector4 customBorders = default(Vector4))
		{
			Sprite val = null;
			val = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).Where((Sprite s) => ((Object)s).name == spriteName).FirstOrDefault();
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			Logger.Warning("Could not find sprite '" + spriteName + "'");
			return null;
		}

		public static Color GetAverageColor(Sprite sprite, float brightnessAdjustment = 1.5f)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: 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)
			if ((Object)(object)sprite == (Object)null || (Object)(object)sprite.texture == (Object)null)
			{
				return Color.white;
			}
			Texture2D val = MakeReadableCopy(sprite.texture);
			Rect rect = sprite.rect;
			int num = Mathf.FloorToInt(((Rect)(ref rect)).x);
			rect = sprite.rect;
			int num2 = Mathf.FloorToInt(((Rect)(ref rect)).y);
			rect = sprite.rect;
			int num3 = Mathf.FloorToInt(((Rect)(ref rect)).width);
			rect = sprite.rect;
			int num4 = Mathf.FloorToInt(((Rect)(ref rect)).height);
			Color[] array = Il2CppArrayBase<Color>.op_Implicit((Il2CppArrayBase<Color>)(object)val.GetPixels(num, num2, num3, num4));
			float num5 = 0f;
			float num6 = 0f;
			float num7 = 0f;
			int num8 = 0;
			Color[] array2 = array;
			foreach (Color val2 in array2)
			{
				if (!(val2.a < 0.01f))
				{
					num5 += val2.r;
					num6 += val2.g;
					num7 += val2.b;
					num8++;
				}
			}
			if (num8 == 0)
			{
				Logger.Error("No non-transparent pixels found in sprite");
				Object.Destroy((Object)(object)val);
				return Color.white;
			}
			Color color = default(Color);
			((Color)(ref color))..ctor(num5 / (float)num8, num6 / (float)num8, num7 / (float)num8);
			Color result = AdjustBrightness(color, brightnessAdjustment);
			Object.Destroy((Object)(object)val);
			return result;
		}

		private static Color AdjustBrightness(Color color, float factor)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			float num = default(float);
			float num2 = default(float);
			float num3 = default(float);
			Color.RGBToHSV(color, ref num, ref num2, ref num3);
			num3 = Mathf.Clamp01(num3 * factor);
			return Color.HSVToRGB(num, num2, num3);
		}

		private static Texture2D MakeReadableCopy(Texture2D source)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)source).width, ((Texture)source).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1);
			Graphics.Blit((Texture)(object)source, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(((Texture)source).width, ((Texture)source).height);
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		public static void ExportSprite(Sprite sprite, string fileName)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			string path = Path.Combine(directoryName, "ExportedSprites", fileName + ".png");
			try
			{
				if ((Object)(object)sprite == (Object)null)
				{
					Logger.Error("Cannot export null sprite");
					return;
				}
				Texture2D texture = sprite.texture;
				if ((Object)(object)texture == (Object)null)
				{
					Logger.Error("Sprite has no texture");
					return;
				}
				Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height);
				RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height);
				Graphics.Blit((Texture)(object)texture, temporary);
				RenderTexture.active = temporary;
				val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0);
				val.Apply();
				RenderTexture.active = null;
				RenderTexture.ReleaseTemporary(temporary);
				byte[] bytes = Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)ImageConversion.EncodeToPNG(val));
				File.WriteAllBytes(path, bytes);
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to export sprite: " + ex.Message);
			}
		}
	}
}
namespace SimpleLabels.UI
{
	public enum ColorPickerType
	{
		Label,
		Font
	}
	public static class ColorPickerManager
	{
		public static Dictionary<TMP_InputField, GameObject> LabelColorPickers = new Dictionary<TMP_InputField, GameObject>();

		public static Dictionary<TMP_InputField, GameObject> FontColorPickers = new Dictionary<TMP_InputField, GameObject>();

		public static void CreateColorPicker(TMP_InputField inputField, ColorPickerType type)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string text = ((type == ColorPickerType.Label) ? "LabelColorPicker" : "FontColorPicker");
				Dictionary<TMP_InputField, GameObject> dictionary = ((type == ColorPickerType.Label) ? LabelColorPickers : FontColorPickers);
				Dictionary<string, MelonPreferences_Entry<string>> dictionary2 = ((type == ColorPickerType.Label) ? ModSettings.LabelColorOptionsDictionary : ModSettings.FontColorOptionsDictionary);
				GameObject val = new GameObject(text);
				val.transform.SetParent(((Component)inputField).transform, false);
				val.layer = 5;
				RectTransform val2 = val.AddComponent<RectTransform>();
				val2.anchorMin = new Vector2(0.5f, 0.5f);
				val2.anchorMax = new Vector2(0.5f, 0.5f);
				val2.pivot = new Vector2(0.5f, 0.5f);
				val2.anchoredPosition = new Vector2((float)((type == ColorPickerType.Font) ? 245 : (-110)), -80f);
				val2.sizeDelta = new Vector2(300f, 40f);
				float num = 30f;
				float num2 = 3f;
				int count = dictionary2.Values.Count;
				float num3 = (0f - ((float)count * num + (float)(count - 1) * num2)) / 2f;
				Color val6 = default(Color);
				for (int i = 0; i < count; i++)
				{
					GameObject val3 = new GameObject($"ColorButton_{i}");
					val3.transform.SetParent(val.transform, false);
					val3.layer = 5;
					RectTransform val4 = val3.AddComponent<RectTransform>();
					val4.sizeDelta = new Vector2(num, num);
					val4.anchoredPosition = new Vector2(num3 + (float)i * (num + num2), 0f);
					Image val5 = val3.AddComponent<Image>();
					val5.type = (Type)1;
					val5.sprite = SpriteManager.LoadEmbeddedSprite("UISmallSprite.png", new Vector4(5f, 5f, 5f, 5f));
					((Graphic)val5).color = (ColorUtility.TryParseHtmlString(dictionary2.Values.ElementAt(i).Value, ref val6) ? val6 : Color.white);
					Button buttonComponent = val3.AddComponent<Button>();
					((UnityEvent)buttonComponent.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
					{
						OnColorSelected(inputField, buttonComponent, type);
					}));
				}
				dictionary.Add(inputField, val);
				val.SetActive(true);
			}
			catch (Exception ex)
			{
				Logger.Error($"Failed to create {type} color picker: {ex.Message}");
			}
		}

		private static void OnColorSelected(TMP_InputField inputField, Button colorButton, ColorPickerType type)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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)
			Image component = ((Component)colorButton).GetComponent<Image>();
			if (!((Object)(object)component == (Object)null))
			{
				Color color = ((Graphic)component).color;
				string text = "#" + ColorUtility.ToHtmlStringRGB(color);
				string currentlyManagedEntityGuid = LabelTracker.GetCurrentlyManagedEntityGuid();
				if (type == ColorPickerType.Label)
				{
					((Graphic)((Component)inputField).GetComponent<Image>()).color = color;
					Logger.Msg("[ColorPicker] User changed label color: GUID=" + currentlyManagedEntityGuid + ", Color=" + text);
					LabelService.UpdateLabel(currentlyManagedEntityGuid, null, text);
				}
				else
				{
					((Graphic)((Component)inputField).GetComponentInChildren<TextMeshProUGUI>()).color = color;
					Logger.Msg("[ColorPicker] User changed font color: GUID=" + currentlyManagedEntityGuid + ", Color=" + text);
					string newFontColor = text;
					LabelService.UpdateLabel(currentlyManagedEntityGuid, null, null, null, null, newFontColor);
				}
			}
		}

		public static void UpdateAllColorPickers(ColorPickerType type)
		{
			Dictionary<TMP_InputField, GameObject> dictionary = ((type == ColorPickerType.Label) ? LabelColorPickers : FontColorPickers);
			foreach (KeyValuePair<TMP_InputField, GameObject> item in dictionary)
			{
				UpdateColorPickerButtons(item.Value, type);
			}
		}

		private static void UpdateColorPickerButtons(GameObject colorPicker, ColorPickerType type)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, MelonPreferences_Entry<string>> dictionary = ((type == ColorPickerType.Label) ? ModSettings.LabelColorOptionsDictionary : ModSettings.FontColorOptionsDictionary);
			Color val = default(Color);
			for (int i = 0; i < colorPicker.transform.childCount; i++)
			{
				Transform child = colorPicker.transform.GetChild(i);
				Image component = ((Component)child).GetComponent<Image>();
				if (!((Object)(object)component == (Object)null))
				{
					((Graphic)component).color = (ColorUtility.TryParseHtmlString(dictionary.Values.ElementAt(i).Value, ref val) ? val : Color.red);
				}
			}
		}

		public static void SetLabelColorPickerButtonColor(int buttonIndex, Color color)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				foreach (KeyValuePair<TMP_InputField, GameObject> labelColorPicker in LabelColorPickers)
				{
					GameObject value = labelColorPicker.Value;
					if (!((Object)(object)value == (Object)null) && value.transform.childCount > buttonIndex && buttonIndex >= 0)
					{
						Transform child = value.transform.GetChild(buttonIndex);
						Image component = ((Component)child).GetComponent<Image>();
						if ((Object)(object)component != (Object)null)
						{
							((Graphic)component).color = color;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Logger.Error($"Failed to update label color picker button at index {buttonIndex}: {ex.Message}");
			}
		}

		public static void Terminate()
		{
			TerminatePickers(LabelColorPickers);
			TerminatePickers(FontColorPickers);
		}

		private static void TerminatePickers(Dictionary<TMP_InputField, GameObject> pickers)
		{
			foreach (GameObject value in pickers.Values)
			{
				if (!((Object)(object)value == (Object)null))
				{
					Object.Destroy((Object)(object)value);
				}
			}
			pickers.Clear();
		}
	}
	public class GUIManager
	{
		public static Image ToggleButtonBackground;

		public static GameObject InitializeGUI(GameObject parent, Vector2 anchorPosition, string namePrefix)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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)
			namePrefix = ExtractNamePrefix(namePrefix);
			GameObject val = CreateContainer(parent, anchorPosition, namePrefix);
			CreateEntityNameText(val, namePrefix);
			CreateIndicatorText(val, "IndicatorNameText", "Name:", new Vector2(-275f, 45f));
			CreateIndicatorText(val, "IndicatorSizeText", "Size:", new Vector2(288f, 45f));
			CreateIndicatorText(val, "IndicatorFontColorText", "Label Color:", new Vector2(-275f, -35f));
			CreateIndicatorText(val, "IndicatorLabelColorText", "Font Color:", new Vector2(80f, -35f));
			return val;
		}

		private static string ExtractNamePrefix(string namePrefix)
		{
			return namePrefix.Substring(namePrefix.LastIndexOf('/') + 1);
		}

		private static GameObject CreateContainer(GameObject parent, Vector2 anchorPosition, string namePrefix)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: 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)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(namePrefix + "_Container");
			val.layer = 5;
			val.transform.SetParent(parent.transform, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = anchorPosition;
			val2.anchorMax = anchorPosition;
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.sizeDelta = new Vector2(700f, 200f);
			Image val3 = val.AddComponent<Image>();
			val3.type = (Type)1;
			val3.sprite = SpriteManager.LoadEmbeddedSprite("UIBigSprite.png", new Vector4(20f, 20f, 20f, 20f));
			((Graphic)val3).color = new Color(20f / 51f, 20f / 51f, 20f / 51f, 20f / 51f);
			return val;
		}

		private static void CreateEntityNameText(GameObject container, string namePrefix)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("EntityNameText");
			val.layer = 5;
			val.transform.SetParent(container.transform, false);
			TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val2).text = "Entity Name";
			((Graphic)val2).color = Color.white;
			((TMP_Text)val2).fontSize = 22f;
			((TMP_Text)val2).fontStyle = (FontStyles)17;
			((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val2).enableWordWrapping = false;
			((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
			((TMP_Text)val2).margin = new Vector4(15f, 10f, 0f, 0f);
			InputFieldManager.EntityInicatorNames.Add(namePrefix, val2);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = new Vector2(0f, 75f);
			component.sizeDelta = new Vector2(700f, 50f);
		}

		private static void CreateIndicatorText(GameObject container, string objectName, string text, Vector2 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0033: 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_0097: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(objectName);
			val.layer = 5;
			val.transform.SetParent(container.transform, false);
			TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val2).text = text;
			((Graphic)val2).color = Color.white;
			((TMP_Text)val2).fontSize = 16f;
			((TMP_Text)val2).fontStyle = (FontStyles)17;
			((TMP_Text)val2).alignment = (TextAlignmentOptions)513;
			((TMP_Text)val2).enableWordWrapping = false;
			((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = position;
			component.sizeDelta = new Vector2(100f, 25f);
		}

		public static Button CreateOnOffButton(GameObject parent, string namePrefix)
		{
			namePrefix = ExtractNamePrefix(namePrefix);
			GameObject buttonObject = CreateToggleButtonObject(parent, namePrefix);
			return SetupToggleButton(buttonObject, namePrefix);
		}

		private static GameObject CreateToggleButtonObject(GameObject parent, string namePrefix)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(namePrefix + "_ToggleButton");
			val.layer = 5;
			val.transform.SetParent(parent.transform, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0f, 0f);
			val2.anchorMax = new Vector2(0f, 0f);
			val2.pivot = new Vector2(0f, 0f);
			val2.anchoredPosition = new Vector2(10f, 10f);
			val2.sizeDelta = new Vector2(50f, 46.2f);
			ToggleButtonBackground = val.AddComponent<Image>();
			((Graphic)ToggleButtonBackground).color = new Color(1f, 1f, 1f, 0.9f);
			ToggleButtonBackground.sprite = SpriteManager.LoadEmbeddedSprite("On.png", Vector4.zero);
			return val;
		}

		private static Button SetupToggleButton(GameObject buttonObject, string namePrefix)
		{
			Button val = buttonObject.AddComponent<Button>();
			((Selectable)val).image = ToggleButtonBackground;
			bool isOn = true;
			((UnityEvent)val.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
			{
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				isOn = !isOn;
				if (isOn)
				{
					InputFieldManager.ActivateInputField(namePrefix);
					ModSettings.ShowInput.Value = true;
					ToggleButtonBackground.sprite = SpriteManager.LoadEmbeddedSprite("On.png", Vector4.zero);
				}
				else
				{
					InputFieldManager.DeactivateInputField(namePrefix);
					ModSettings.ShowInput.Value = false;
					ToggleButtonBackground.sprite = SpriteManager.LoadEmbeddedSprite("Off.png", Vector4.zero);
				}
			}));
			return val;
		}
	}
	public class InputFieldManager
	{
		public static Dictionary<string, TMP_InputField> InputFields = new Dictionary<string, TMP_InputField>();

		public static Dictionary<string, TMP_InputField> NumericInputFields = new Dictionary<string, TMP_InputField>();

		public static Dictionary<string, GameObject> ContainersGameObjects = new Dictionary<string, GameObject>();

		public static Dictionary<string, Button> ToggleOnOffButtons = new Dictionary<string, Button>();

		public static Dictionary<string, TextMeshProUGUI> EntityInicatorNames = new Dictionary<string, TextMeshProUGUI>();

		public static Dictionary<string, Vector2> SupportedUITypes = new Dictionary<string, Vector2>
		{
			{
				"UI/StorageMenu",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/PackagingStation",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/ChemistryStation",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/LabOven",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/BrickPress",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/Cauldron",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/MixingStation",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/DryingRack",
				new Vector2(0.5f, 0.75f)
			},
			{
				"UI/Stations/MushroomSpawnStation",
				new Vector2(0.5f, 0.75f)
			}
		};

		public static TMP_InputField _currentInputField;

		public static TMP_InputField _currentNumericInputField;

		private static string _pendingItemColor;

		private static string _pendingItemText;

		private static bool _isApplyingItemFeedback;

		public static void Initialize()
		{
			CreateInputFields();
		}

		public static void Terminate()
		{
			foreach (TMP_InputField value in InputFields.Values)
			{
				if (!((Object)(object)value == (Object)null))
				{
					Object.Destroy((Object)(object)((Component)value).gameObject);
				}
			}
			InputFields.Clear();
			foreach (TMP_InputField value2 in NumericInputFields.Values)
			{
				if (!((Object)(object)value2 == (Object)null))
				{
					Object.Destroy((Object)(object)((Component)value2).gameObject);
				}
			}
			NumericInputFields.Clear();
			foreach (GameObject value3 in ContainersGameObjects.Values)
			{
				if (!((Object)(object)value3 == (Object)null))
				{
					Object.Destroy((Object)(object)value3);
				}
			}
			ContainersGameObjects.Clear();
			foreach (Button value4 in ToggleOnOffButtons.Values)
			{
				if (!((Object)(object)value4 == (Object)null))
				{
					Object.Destroy((Object)(object)((Component)value4).gameObject);
				}
			}
			ToggleOnOffButtons.Clear();
			foreach (TextMeshProUGUI value5 in EntityInicatorNames.Values)
			{
				if (!((Object)(object)value5 == (Object)null))
				{
					Object.Destroy((Object)(object)((Component)value5).gameObject);
				}
			}
			EntityInicatorNames.Clear();
			ColorPickerManager.Terminate();
			_currentInputField = null;
			_currentNumericInputField = null;
			_pendingItemColor = null;
			_pendingItemText = null;
			_isApplyingItemFeedback = false;
		}

		public static void ActivateInputField(string gameObjectName)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = FindByKey(ContainersGameObjects, gameObjectName);
			if ((Object)(object)val != (Object)null)
			{
				val.SetActive(true);
			}
			Button val2 = FindByKey(ToggleOnOffButtons, gameObjectName);
			if ((Object)(object)val2 != (Object)null)
			{
				((Component)val2).GetComponent<Image>().sprite = SpriteManager.LoadEmbeddedSprite("On.png", Vector4.zero);
				((Component)val2).gameObject.SetActive(true);
			}
		}

		public static void DeactivateInputField(string gameObjectName)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = FindByKey(ContainersGameObjects, gameObjectName);
			if ((Object)(object)val != (Object)null)
			{
				val.SetActive(false);
			}
			Button val2 = FindByKey(ToggleOnOffButtons, gameObjectName);
			if ((Object)(object)val2 != (Object)null)
			{
				((Component)val2).GetComponent<Image>().sprite = SpriteManager.LoadEmbeddedSprite("Off.png", Vector4.zero);
				((Component)val2).gameObject.SetActive(true);
			}
		}

		public static void DisableToggleOnOffButton(string gameObjectName)
		{
			Button val = FindByKey(ToggleOnOffButtons, gameObjectName);
			if ((Object)(object)val != (Object)null)
			{
				((Component)val).gameObject.SetActive(false);
			}
		}

		public static TMP_InputField GetInputField(string gameObjectName)
		{
			return FindByKey(InputFields, gameObjectName);
		}

		public static TMP_InputField GetNumericInputField(string gameObjectName)
		{
			return FindByKey(NumericInputFields, gameObjectName);
		}

		public static TextMeshProUGUI GetEntityNameIndicator(string gameObjectName)
		{
			return FindByKey(EntityInicatorNames, gameObjectName);
		}

		private static T FindByKey<T>(Dictionary<string, T> dictionary, string key)
		{
			return dictionary.FirstOrDefault((KeyValuePair<string, T> x) => x.Key.Contains(key)).Value;
		}

		private static void CreateInputFields()
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<string, Vector2> supportedUIType in SupportedUITypes)
			{
				GameObject val = GameObject.Find(supportedUIType.Key);
				if ((Object)(object)val == (Object)null)
				{
					Logger.Error($"Couldn't find {supportedUIType} GameObject.");
					continue;
				}
				GameObject val2 = GUIManager.InitializeGUI(val, supportedUIType.Value, supportedUIType.Key);
				ContainersGameObjects.Add(supportedUIType.Key, val2);
				Button value = GUIManager.CreateOnOffButton(val, supportedUIType.Key);
				ToggleOnOffButtons.Add(supportedUIType.Key, value);
				TMP_InputField value2 = CreateInputField(val2, supportedUIType.Key);
				InputFields.Add(supportedUIType.Key, value2);
				TMP_InputField value3 = CreateNumericInputField(val2, supportedUIType.Key);
				NumericInputFields.Add(supportedUIType.Key, value3);
				ColorPickerManager.CreateColorPicker(InputFields[supportedUIType.Key], ColorPickerType.Label);
				ColorPickerManager.CreateColorPicker(InputFields[supportedUIType.Key], ColorPickerType.Font);
			}
		}

		private static TMP_InputField CreateInputField(GameObject parent, string namePrefix)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				namePrefix = ExtractNamePrefix(namePrefix);
				GameObject val = CreateInputFieldObject(parent, namePrefix + "_InputField", new Vector2(550f, 40f), new Vector2(-55f, 10f));
				Image val2 = SetupInputFieldBackground(val, ModSettings.LabelDefaultColor.Value);
				GameObject val3 = CreateTextArea(val.transform);
				GameObject placeholder = CreatePlaceholder(val3.transform);
				TMP_InputField val4 = ConfigureInputField(val, val3, placeholder, 30);
				SetupTextInputListeners(val4);
				val.SetActive(true);
				return val4;
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to create input field: " + ex.Message);
				return null;
			}
		}

		private static TMP_InputField CreateNumericInputField(GameObject parent, string namePrefix)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				namePrefix = ExtractNamePrefix(namePrefix);
				GameObject val = CreateInputFieldObject(parent, namePrefix + "_NumericInputField", new Vector2(90f, 40f), new Vector2(280f, 10f));
				SetupInputFieldBackground(val, "#FFFFFF");
				AddOutline(val);
				GameObject textArea = CreateTextArea(val.transform);
				GameObject placeholder = CreateNumericPlaceholder(val.transform);
				TMP_InputField val2 = ConfigureInputField(val, textArea, placeholder, 2);
				val2.contentType = (ContentType)2;
				SetupNumericInputListeners(val2);
				val.SetActive(true);
				return val2;
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to create numeric input field: " + ex.Message);
				return null;
			}
		}

		private static string ExtractNamePrefix(string namePrefix)
		{
			return namePrefix.Substring(namePrefix.LastIndexOf('/') + 1);
		}

		private static GameObject CreateInputFieldObject(GameObject parent, string objectName, Vector2 sizeDelta, Vector2 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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)
			GameObject val = new GameObject(objectName);
			val.layer = 5;
			val.transform.SetParent(parent.transform, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.sizeDelta = sizeDelta;
			val2.anchoredPosition = position;
			return val;
		}

		private static Image SetupInputFieldBackground(GameObject inputObject, string colorHex)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Image val = inputObject.AddComponent<Image>();
			val.type = (Type)1;
			val.sprite = SpriteManager.LoadEmbeddedSprite("UISmallSprite.png", new Vector4(5f, 5f, 5f, 5f));
			Color val2 = default(Color);
			((Graphic)val).color = (ColorUtility.TryParseHtmlString(colorHex, ref val2) ? val2 : Color.red);
			return val;
		}

		private static void AddOutline(GameObject inputObject)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			Outline val = inputObject.AddComponent<Outline>();
			((Shadow)val).effectColor = new Color(0f, 0f, 0f, 0.15f);
			((Shadow)val).effectDistance = new Vector2(1f, 1f);
		}

		private static TMP_InputField ConfigureInputField(GameObject inputObject, GameObject textArea, GameObject placeholder, int characterLimit)
		{
			TMP_InputField val = inputObject.AddComponent<TMP_InputField>();
			val.textViewport = textArea.GetComponent<RectTransform>();
			val.textComponent = (TMP_Text)(object)textArea.GetComponent<TextMeshProUGUI>();
			val.placeholder = (Graphic)(object)placeholder.GetComponent<TextMeshProUGUI>();
			val.characterLimit = characterLimit;
			return val;
		}

		private static void SetupTextInputListeners(TMP_InputField inputField)
		{
			((UnityEvent<string>)(object)inputField.onValueChanged).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate(string text)
			{
				if (DevUtils.IsStorageOrStationOpen())
				{
					OnInputTextChangeVisualFeedback(text, inputField);
				}
			}));
			((UnityEvent<string>)(object)inputField.onSubmit).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate(string text)
			{
				if (DevUtils.IsStorageOrStationOpen())
				{
					OnInputTextSubmit(text, inputField);
				}
			}));
		}

		private static void SetupNumericInputListeners(TMP_InputField inputField)
		{
			((UnityEvent<string>)(object)inputField.onValueChanged).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate(string text)
			{
				ValidateNumericRange(text, inputField);
			}));
			((UnityEvent<string>)(object)inputField.onSubmit).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate(string text)
			{
				ValidateNumericRange(text, inputField);
				OnNumericInputTextChange(text, inputField);
			}));
		}

		private static void OnInputTextChangeVisualFeedback(string text, TMP_InputField inputField)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			if (_isApplyingItemFeedback)
			{
				return;
			}
			if (!DevUtils.IsStorageOrStationOpen())
			{
				inputField.DeactivateInputField(false);
				_currentInputField = null;
				return;
			}
			string firstTextInCurlyBrackets = GetFirstTextInCurlyBrackets(text);
			if (string.IsNullOrEmpty(firstTextInCurlyBrackets))
			{
				_pendingItemColor = null;
				_pendingItemText = null;
			}
			else if (Registry.ItemExists(firstTextInCurlyBrackets))
			{
				ItemDefinition item = Registry.GetItem(firstTextInCurlyBrackets);
				Color averageColor = SpriteManager.GetAverageColor(item.Icon);
				string text2 = RemoveCurlyBracketsContent(text);
				if (string.IsNullOrEmpty(text2))
				{
					text2 = item.Name;
				}
				_isApplyingItemFeedback = true;
				inputField.text = text2;
				_isApplyingItemFeedback = false;
				((Graphic)((Component)inputField).GetComponent<Image>()).color = averageColor;
				_pendingItemColor = "#" + ColorUtility.ToHtmlStringRGB(averageColor);
				_pendingItemText = text2;
			}
			else
			{
				_pendingItemColor = null;
				_pendingItemText = null;
			}
		}

		private static void OnInputTextSubmit(string text, TMP_InputField inputField)
		{
			//IL_008a: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			if (!DevUtils.IsStorageOrStationOpen())
			{
				inputField.DeactivateInputField(false);
				_currentInputField = null;
				_pendingItemColor = null;
				_pendingItemText = null;
				return;
			}
			string currentlyManagedEntityGuid = LabelTracker.GetCurrentlyManagedEntityGuid();
			if (string.IsNullOrEmpty(currentlyManagedEntityGuid))
			{
				_pendingItemColor = null;
				_pendingItemText = null;
				return;
			}
			string firstTextInCurlyBrackets = GetFirstTextInCurlyBrackets(text);
			string text2 = text;
			string newLabelColor = null;
			if (!string.IsNullOrEmpty(firstTextInCurlyBrackets) && Registry.ItemExists(firstTextInCurlyBrackets))
			{
				ItemDefinition item = Registry.GetItem(firstTextInCurlyBrackets);
				Color averageColor = SpriteManager.GetAverageColor(item.Icon);
				newLabelColor = "#" + ColorUtility.ToHtmlStringRGB(averageColor);
				string text3 = RemoveCurlyBracketsContent(text);
				text2 = (inputField.text = ((!string.IsNullOrEmpty(text3)) ? text3 : item.Name));
				((Graphic)((Component)inputField).GetComponent<Image>()).color = averageColor;
			}
			else if (_pendingItemColor != null && _pendingItemText != null && _pendingItemText == text2)
			{
				newLabelColor = _pendingItemColor;
			}
			_pendingItemColor = null;
			_pendingItemText = null;
			Logger.Msg($"[InputField] User submitted label change: GUID={currentlyManagedEntityGuid}, Text='{text2}'");
			LabelService.UpdateLabel(currentlyManagedEntityGuid, text2, newLabelColor);
		}

		private static void ValidateNumericRange(string text, TMP_InputField inputField)
		{
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			if (int.TryParse(text, out var result))
			{
				int num = Mathf.Clamp(result, 1, 30);
				if (result != num)
				{
					inputField.text = num.ToString();
				}
			}
			else
			{
				inputField.text = "1";
			}
		}

		private static void OnNumericInputTextChange(string text, TMP_InputField inputField)
		{
			inputField.DeactivateInputField(false);
			_currentNumericInputField = null;
			if (!string.IsNullOrEmpty(text) && int.TryParse(text, out var result))
			{
				string currentlyManagedEntityGuid = LabelTracker.GetCurrentlyManagedEntityGuid();
				Logger.Msg($"[InputField] User changed label size: GUID={currentlyManagedEntityGuid}, Size={result}");
				LabelService.UpdateLabel(currentlyManagedEntityGuid, null, null, result);
			}
		}

		private static GameObject CreateTextArea(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("TextArea");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.offsetMin = new Vector2(10f, 0f);
			val2.offsetMax = new Vector2(-10f, 0f);
			TextMeshProUGUI val3 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val3).fontSize = ModSettings.DEFAULT_FONT_SIZE;
			Color val4 = default(Color);
			((Graphic)val3).color = (ColorUtility.TryParseHtmlString(ModSettings.FontDefaultColor.Value, ref val4) ? val4 : Color.red);
			((TMP_Text)val3).alignment = (TextAlignmentOptions)513;
			((TMP_Text)val3).enableWordWrapping = false;
			((TMP_Text)val3).fontStyle = (FontStyles)1;
			return val;
		}

		private static GameObject CreatePlaceholder(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Placeholder");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.offsetMax = new Vector2(0f, 0f);
			val2.offsetMin = new Vector2(-265f, 0f);
			TextMeshProUGUI val3 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val3).text = "Press Enter to confirm changes...";
			((TMP_Text)val3).fontSize = ModSettings.DEFAULT_FONT_SIZE;
			((Graphic)val3).color = new Color(0.5f, 0.5f, 0.5f);
			((TMP_Text)val3).alignment = (TextAlignmentOptions)513;
			((TMP_Text)val3).enableWordWrapping = false;
			return val;
		}

		private static GameObject CreateNumericPlaceholder(Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("NumericPlaceholder");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.offsetMax = new Vector2(75f, 25f);
			val2.offsetMin = new Vector2(-100f, -25f);
			TextMeshProUGUI val3 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val3).text = "Size";
			((TMP_Text)val3).fontSize = ModSettings.DEFAULT_FONT_SIZE;
			((Graphic)val3).color = new Color(0.5f, 0.5f, 0.5f);
			((TMP_Text)val3).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val3).enableWordWrapping = true;
			return val;
		}

		public static string GetFirstTextInCurlyBrackets(string text)
		{
			Match match = Regex.Match(text, "\\{([^}]*)\\}");
			if (match.Success)
			{
				return match.Groups[1].Value;
			}
			return null;
		}

		private static string RemoveCurlyBracketsContent(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return input;
			}
			return Regex.Replace(input, "{[^{}]*}", "").Trim();
		}
	}
	public class LabelApplier
	{
		private static readonly Dictionary<string, List<GameObject>> _entityLabels = new Dictionary<string, List<GameObject>>();

		public static void ApplyOrUpdateLabel(string guid)
		{
			if (string.IsNullOrEmpty(guid))
			{
				return;
			}
			EntityData entityData = LabelTracker.GetEntityData(guid);
			if ((Object)(object)entityData?.GameObject == (Object)null)
			{
				return;
			}
			string text = CleanEntityName(((Object)entityData.GameObject).name);
			if (!LabelPlacementConfigs.LabelPlacementConfigsDictionary.TryGetValue(text, out var value))
			{
				Logger.Msg("[LabelApplier] No placement config for entity type: " + text);
				return;
			}
			if (string.IsNullOrEmpty(entityData.LabelText))
			{
				RemoveLabels(guid);
				return;
			}
			EnsureLabelCount(guid, value.Count);
			for (int i = 0; i < value.Count; i++)
			{
				ConfigureLabel(_entityLabels[guid][i], entityData, value[i]);
			}
		}

		private static void ConfigureLabel(GameObject labelInstance, EntityData entityData, LabelPlacement placement)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)labelInstance == (Object)null)
			{
				labelInstance = LabelPrefabManager.GetLabelInstance();
			}
			if (!labelInstance.activeSelf)
			{
				labelInstance.SetActive(true);
			}
			labelInstance.transform.SetParent(entityData.GameObject.transform, false);
			labelInstance.transform.localPosition = placement.LocalPosition;
			labelInstance.transform.localRotation = placement.Rotation;
			float num = 0.1f;
			float num2 = 1f + (float)(entityData.LabelSize - 1) / 9f;
			float num3 = num * num2;
			labelInstance.transform.localScale = new Vector3(num3, num3, num);
			Transform val = labelInstance.transform.Find("LabelObject/PaperBackground");
			Renderer val2 = default(Renderer);
			if ((Object)(object)val != (Object)null && ((Component)val).TryGetComponent<Renderer>(ref val2))
			{
				Color val3 = default(Color);
				val2.material.color = (ColorUtility.TryParseHtmlString(entityData.LabelColor, ref val3) ? val3 : Color.red);
			}
			Transform obj = labelInstance.transform.Find("LabelObject/LabelText");
			TextMeshPro val4 = ((obj != null) ? ((Component)obj).GetComponent<TextMeshPro>() : null);
			if ((Object)(object)val4 != (Object)null)
			{
				((TMP_Text)val4).text = entityData.LabelText;
				Color val5 = default(Color);
				((Graphic)val4).color = (ColorUtility.TryParseHtmlString(entityData.FontColor, ref val5) ? val5 : Color.red);
			}
		}

		private static void EnsureLabelCount(string guid, int requiredCount)
		{
			if (!_entityLabels.TryGetValue(guid, out var value))
			{
				value = new List<GameObject>();
				_entityLabels.Add(guid, value);
			}
			while (value.Count < requiredCount)
			{
				value.Add(LabelPrefabManager.GetLabelInstance());
			}
			while (value.Count > requiredCount)
			{
				LabelPrefabManager.ReturnToPool(value[value.Count - 1]);
				value.RemoveAt(value.Count - 1);
			}
		}

		private static string CleanEntityName(string originalName)
		{
			return originalName.Replace("(Clone)", "").Replace("_Built", "").Trim();
		}

		public static void RemoveLabels(string guid)
		{
			if (!_entityLabels.TryGetValue(guid, out var value))
			{
				return;
			}
			foreach (GameObject item in value)
			{
				if (!((Object)(object)item == (Object)null))
				{
					LabelPrefabManager.ReturnToPool(item);
				}
			}
			_entityLabels.Remove(guid);
		}

		public static void Terminate()
		{
			foreach (List<GameObject> value in _entityLabels.Values)
			{
				foreach (GameObject item in value)
				{
					if (!((Object)(object)item == (Object)null))
					{
						LabelPrefabManager.ReturnToPool(item);
					}
				}
			}
			_entityLabels.Clear();
		}

		public static void ForceUpdateAllLabels()
		{
			foreach (string allTrackedGuid in LabelTracker.GetAllTrackedGuids())
			{
				ApplyOrUpdateLabel(allTrackedGuid);
			}
		}
	}
	public class LabelInputDataLoader
	{
		public static void LoadLabelData(string entityGuid, GameObject entityGameObject, GameObject inputGameObject, string entityName = "")
		{
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: 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_0155: Unknown result type (might be due to invalid IL or missing references)
			string gameObjectName = ((Object)inputGameObject).name.Replace("(Clone)", "").Replace("_Built", "").Replace("Mk2", "")
				.Replace("_", "")
				.Trim();
			InputFieldManager.DeactivateInputField(gameObjectName);
			try
			{
				if (string.IsNullOrEmpty(entityGuid))
				{
					return;
				}
				Logger.Msg("[InputLoader] Loading label data for entity: GUID=" + entityGuid + ", Name=" + entityName);
				LabelTracker.SetCurrentlyManagedEntity(entityGuid);
				TMP_InputField inputField = InputFieldManager.GetInputField(gameObjectName);
				TMP_InputField numericInputField = InputFieldManager.GetNumericInputField(gameObjectName);
				TextMeshProUGUI entityNameIndicator = InputFieldManager.GetEntityNameIndicator(gameObjectName);
				EntityData entityData = LabelTracker.GetEntityData(entityGuid);
				if (entityData != null && (Object)(object)entityData.GameObject == (Object)null && (Object)(object)entityGameObject != (Object)null)
				{
					LabelService.BindGameObject(entityGuid, entityGameObject);
				}
				inputField.text = entityData?.LabelText ?? string.Empty;
				((TMP_Text)entityNameIndicator).text = entityName;
				Color val = default(Color);
				((Graphic)((Component)inputField).GetComponent<Image>()).color = (ColorUtility.TryParseHtmlString(entityData?.LabelColor ?? ModSettings.LabelDefaultColor.Value, ref val) ? val : Color.red);
				((Graphic)((Component)inputField).GetComponentInChildren<TextMeshProUGUI>()).color = (ColorUtility.TryParseHtmlString(entityData?.FontColor ?? ModSettings.FontDefaultColor.Value, ref val) ? val : Color.red);
				numericInputField.text = entityData?.LabelSize.ToString() ?? ModSettings.LabelDefaultSize.Value.ToString();
				if (LabelTracker.GetEntityData(entityGuid) == null)
				{
					Logger.Msg("[InputLoader] Creating new entity from UI: GUID=" + entityGuid);
					LabelService.CreateLabel(entityGuid, entityGameObject, entityData?.LabelText ?? string.Empty, entityData?.LabelColor ?? ModSettings.LabelDefaultColor.Value, entityData?.LabelSize ?? ModSettings.LabelDefaultSize.Value, entityData?.FontSize ?? ModSettings.DEFAULT_FONT_SIZE, entityData?.FontColor ?? ModSettings.FontDefaultColor.Value);
				}
				if (ModSettings.ShowInput.Value)
				{
					InputFieldManager.ActivateInputField(gameObjectName);
					if (ModSettings.AutoFocusInput.Value)
					{
						inputField.ActivateInputField();
						InputFieldManager._currentInputField = inputField;
						InputFieldManager._currentNumericInputField = numericInputField;
					}
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to handle storage open: " + ex.Message);
			}
		}
	}
	public class LabelPrefabManager
	{
		private static readonly Queue<GameObject> _prefabPool = new Queue<GameObject>();

		private static Transform _poolContainer;

		private static Material _labelMaterial;

		private static GameObject _prefabTemplate;

		private const int MinimumPoolSize = 8;

		private const int BatchSize = 10;

		public static void Initialize()
		{
			CreatePoolContainer();
			CreatePrefabTemplate();
			PrewarmPool(16);
		}

		private static void CreatePoolContainer()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			_poolContainer = new GameObject("LabelPrefabPool").transform;
			((Component)_poolContainer).gameObject.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)((Component)_poolContainer).gameObject);
		}

		private static void CreatePrefabTemplate()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			_prefabTemplate = new GameObject("LabelPrefab");
			_prefabTemplate.SetActive(false);
			_prefabTemplate.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
			GameObject val = new GameObject("LabelObject");
			val.transform.SetParent(_prefabTemplate.transform);
			val.transform.localPosition = Vector3.zero;
			val.transform.localScale = Vector3.one;
			GameObject val2 = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)val2).name = "PaperBackground";
			val2.transform.SetParent(val.transform);
			val2.transform.localPosition = Vector3.zero;
			val2.transform.localScale = new Vector3(2f, 0.6f, 0.1f);
			val2.GetComponent<BoxCollider>().extents = Vector3.zero;
			_labelMaterial = new Material(Shader.Find("Universal Render Pipeline/Simple Lit"));
			if ((Object)(object)_labelMaterial != (Object)null)
			{
				val2.GetComponent<Renderer>().material = _labelMaterial;
			}
			else
			{
				Logger.Error("Couldn't find material to reuse.");
			}
			GameObject val3 = new GameObject("LabelText");
			val3.transform.SetParent(val.transform);
			val3.transform.localPosition = new Vector3(0f, 0f, -0.052f);
			val3.transform.localScale = new Vector3(1.1f, 1.25f, 1f);
			TextMeshPro val4 = val3.AddComponent<TextMeshPro>();
			((TMP_Text)val4).fontSizeMin = 1.4f;
			((TMP_Text)val4).fontSizeMax = 3f;
			((TMP_Text)val4).fontSize = 2f;
			((TMP_Text)val4).fontStyle = (FontStyles)1;
			((TMP_Text)val4).enableAutoSizing = true;
			((TMP_Text)val4).alignment = (TextAlignmentOptions)514;
			((Graphic)val4).color = Color.black;
			((TMP_Text)val4).enableWordWrapping = true;
			((TMP_Text)val4).margin = new Vector4(0.02f, 0.02f, 0.02f, 0.02f);
			TrySetOpenSansFont(val4);
			RectTransform component = val3.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(1.8f, 0.5f);
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
		}

		private static void TrySetOpenSansFont(TextMeshPro textMesh)
		{
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Material[] array = Il2CppArrayBase<Material>.op_Implicit(Resources.FindObjectsOfTypeAll<Material>());
				Material val = null;
				Material[] array2 = array;
				foreach (Material val2 in array2)
				{
					if ((Object)(object)val2.shader != (Object)null && (((Object)val2.shader).name.Contains("TextMeshPro") || ((Object)val2.shader).name.Contains("TMP")) && !((Object)val2.shader).name.Contains("Sprite"))
					{
						val = val2;
						break;
					}
				}
				TMP_FontAsset[] array3 = Il2CppArrayBase<TMP_FontAsset>.op_Implicit(Resources.FindObjectsOfTypeAll<TMP_FontAsset>());
				TMP_FontAsset[] array4 = array3;
				foreach (TMP_FontAsset val3 in array4)
				{
					if (!((Object)val3).name.Contains("OpenSans-Bold"))
					{
						continue;
					}
					((TMP_Text)textMesh).font = val3;
					if ((Object)(object)val != (Object)null)
					{
						Material val4 = new Material(val);
						if (val4.HasProperty("_FaceColor"))
						{
							val4.SetColor("_FaceColor", Color.black);
						}
						((TMP_Text)textMesh).fontSharedMaterial = val4;
						break;
					}
					Material val5 = new Material(((TMP_Asset)val3).material);
					Shader val6 = Shader.Find("TextMeshPro/Distance Field");
					if ((Object)(object)val6 != (Object)null)
					{
						val5.shader = val6;
					}
					((TMP_Text)textMesh).fontSharedMaterial = val5;
					break;
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Error setting font: " + ex.Message);
			}
		}

		private static void PrewarmPool(int count)
		{
			for (int i = 0; i < count; i++)
			{
				ReturnToPool(CreateNewLabelInstance());
			}
		}

		private static GameObject CreateNewLabelInstance()
		{
			GameObject val = Object.Instantiate<GameObject>(_prefabTemplate);
			((Object)val).name = "LabelInstance";
			return val;
		}

		public static GameObject GetLabelInstance()
		{
			if (_prefabPool.Count <= 8)
			{
				ReplenishPool();
			}
			if (_prefabPool.Count > 0)
			{
				GameObject val = _prefabPool.Dequeue();
				if ((Object)(object)val == (Object)null)
				{
					val = CreateNewLabelInstance();
				}
				val.SetActive(true);
				return val;
			}
			Logger.Warning("Pool empty despite replenishment attempt, creating emergency instance");
			return CreateNewLabelInstance();
		}

		private static void ReplenishPool()
		{
			int num = 10;
			for (int i = 0; i < num; i++)
			{
				ReturnToPool(CreateNewLabelInstance());
			}
		}

		public static void ReturnToPool(GameObject labelInstance)
		{
			if (!((Object)(object)labelInstance == (Object)null))
			{
				labelInstance.SetActive(false);
				labelInstance.transform.SetParent(_poolContainer);
				_prefabPool.Enqueue(labelInstance);
			}
		}

		public static void Terminate()
		{
			while (_prefabPool.Count > 0)
			{
				GameObject val = _prefabPool.Dequeue();
				if (!((Object)(object)val == (Object)null))
				{
					Object.Destroy((Object)(object)val);
				}
			}
			if ((Object)(object)_prefabTemplate != (Object)null)
			{
				Object.Destroy((Object)(object)_prefabTemplate);
			}
			if ((Object)(object)_poolContainer != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_poolContainer).gameObject);
			}
			if ((Object)(object)_labelMaterial != (Object)null)
			{
				Object.Destroy((Object)(object)_labelMaterial);
			}
		}
	}
}
namespace SimpleLabels.Settings
{
	public class ColorPickerSettings : MelonMod
	{
		public static string[] colorNames = new string[9] { "Color 1", "Color 2", "Color 3", "Color 4", "Color 5", "Color 6", "Color 7", "Color 8", "Color 9" };

		public static void Initialize()
		{
			ModSettings.LabelColorOptionsDictionary = new Dictionary<string, MelonPreferences_Entry<string>>();
			ModSettings.FontColorOptionsDictionary = new Dictionary<string, MelonPreferences_Entry<string>>();
			CreateDefaultColorOptions();
		}

		private static void CreateDefaultColorOptions()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			Color[] array = (Color[])(object)new Color[9]
			{
				new Color(0.3f, 0.45f, 0.65f),
				new Color(0.4f, 0.6f, 0.35f),
				new Color(0.7f, 0.55f, 0.3f),
				new Color(0.65f, 0.4f, 0.4f),
				new Color(0.4f, 0.35f, 0.6f),
				new Color(0.55f, 0.6f, 0.6f),
				new Color(0.3f, 0.65f, 0.55f),
				new Color(0.8f, 0.7f, 0.5f),
				Color.white
			};
			Color[] array2 = (Color[])(object)new Color[9]
			{
				new Color(0.85f, 0.85f, 0.3f),
				new Color(0.3f, 0.7f, 0.3f),
				new Color(0.8f, 0.4f, 0.2f),
				new Color(0.6f, 0.3f, 0.6f),
				new Color(0.3f, 0.5f, 0.7f),
				new Color(0.75f, 0.75f, 0.75f),
				new Color(0.2f, 0.25f, 0.4f),
				new Color(0.5f, 0.3f, 0.2f),
				Color.black
			};
			for (int i = 0; i < colorNames.Length; i++)
			{
				MelonPreferences_Entry<string> val = ModSettings.LabelColorPickerCategory.CreateEntry<string>(colorNames[i], "#" + ColorUtility.ToHtmlStringRGB(array[i]), (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
				int colorIndex2 = i;
				((MelonEventBase<LemonAction<string, string>>)(object)val.OnEntryValueChanged).Subscribe((LemonAction<string, string>)delegate(string oldVal, string newVal)
				{
					OnColorChanged(colorIndex2, "Label", oldVal, newVal);
				}, 0, false);
				ModSettings.LabelColorOptionsDictionary.Add(colorNames[i], val);
				MelonPreferences_Entry<string> val2 = ModSettings.FontColorPickerCategory.CreateEntry<string>(colorNames[i], "#" + ColorUtility.ToHtmlStringRGB(array2[i]), (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
				int fontColorIndex = i;
				((MelonEventBase<LemonAction<string, string>>)(object)val2.OnEntryValueChanged).Subscribe((LemonAction<string, string>)delegate(string oldVal, string newVal)
				{
					OnColorChanged(fontColorIndex, "Font", oldVal, newVal);
				}, 0, false);
				ModSettings.FontColorOptionsDictionary.Add(colorNames[i], val2);
			}
			static void OnColorChanged(int colorIndex, string pickerType, string oldVal, string newVal)
			{
				if (!Regex.IsMatch(newVal, "^#[0-9A-Fa-f]{6}$"))
				{
					if (pickerType == "Label")
					{
						ModSettings.LabelColorOptionsDictionary[colorNames[colorIndex]].Value = oldVal;
					}
					else if (pickerType == "Font")
					{
						ModSettings.FontColorOptionsDictionary[colorNames[colorIndex]].Value = oldVal;
					}
					Logger.Warning($"Invalid color format for {pickerType} color '{colorNames[colorIndex]}': {newVal}. Reverted to {oldVal}");
				}
				else
				{
					ModManagerIntegration.RequestUIRefresh();
					if (pickerType == "Label")
					{
						ColorPickerManager.UpdateAllColorPickers(ColorPickerType.Label);
					}
					else if (pickerType == "Font")
					{
						ColorPickerManager.UpdateAllColorPickers(ColorPickerType.Font);
					}
				}
			}
		}
	}
	public static class ModManagerIntegration
	{
		private static MethodInfo _requestUIRefreshMethod;

		public static void Initialize()
		{
			try
			{
				Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetType("ModManagerPhoneApp.ModSettingsEvents") != null);
				if (!(assembly == null))
				{
					_requestUIRefreshMethod = assembly.GetType("ModManagerPhoneApp.ModSettingsEvents")?.GetMethod("RequestUIRefresh");
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to initialize Mod Manager integration: " + ex.Message);
			}
		}

		public static void RequestUIRefresh()
		{
			try
			{
				_requestUIRefreshMethod?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to request UI refresh: " + ex.Message);
			}
		}
	}
	public class ModSettings
	{
		public static readonly int DEFAULT_FONT_SIZE = 24;

		public static MelonPreferences_Category GeneralCategory { get; private set; }

		public static MelonPreferences_Category ClipboardCategory { get; private set; }

		public static MelonPreferences_Category LabelColorPickerCategory { get; private set; }

		public static MelonPreferences_Category LabelCategory { get; private set; }

		public static MelonPreferences_Category FontColorPickerCategory { get; private set; }

		public static MelonPreferences_Category FontCategory { get; private set; }

		public static MelonPreferences_Category DebugCategory { get; private set; }

		public static MelonPreferences_Entry<bool> ShowInput { get; private set; }

		public static MelonPreferences_Entry<bool> AutoFocusInput { get; private set; }

		public static MelonPreferences_Entry<bool> ShowClipboardRoutes { get; private set; }

		public static MelonPreferences_Entry<bool> ShowClipboardStations { get; private set; }

		public static MelonPreferences_Entry<bool> ShowClipboardStationsOutput { get; private set; }

		public static Dictionary<string, MelonPreferences_Entry<string>> LabelColorOptionsDictionary { get; set; }

		public static MelonPreferences_Entry<int> LabelDefaultSize { get; private set; }

		public static MelonPreferences_Entry<string> LabelDefaultColor { get; private set; }

		public static MelonPreferences_Entry<bool> AutomaticallySetLabelColorOptions { get; private set; }

		public static Dictionary<string, MelonPreferences_Entry<string>> FontColorOptionsDictionary { get; set; }

		public static MelonPreferences_Entry<string> FontDefaultColor { get; private set; }

		public static MelonPreferences_Entry<bool> ShowDebug { get; private set; }

		public static void Initialize()
		{
			CreateGeneralSettings();
			CreateClipboardSettings();
			CreateLabelColorPickerSettings();
			CreateFontColorPickerSettings();
			ColorPickerSettings.Initialize();
			CreateLabelSettings();
			CreateFontSettings();
			CreateDebugSettings();
		}

		private static void CreateGeneralSettings()
		{
			GeneralCategory = MelonPreferences.CreateCategory("SimpleLabels_01_General", "General");
			ShowInput = GeneralCategory.CreateEntry<bool>("Show input", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)ShowInput.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnShowInputChanged, 0, false);
			AutoFocusInput = GeneralCategory.CreateEntry<bool>("Auto focus input", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)AutoFocusInput.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnAutoFocusInputChanged, 0, false);
		}

		private static void CreateClipboardSettings()
		{
			ClipboardCategory = MelonPreferences.CreateCategory("SimpleLabels_02_Clipboard", "Clipboard");
			ShowClipboardRoutes = ClipboardCategory.CreateEntry<bool>("Show routes", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)ShowClipboardRoutes.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnShowClipboardRoutesChanged, 0, false);
			ShowClipboardStations = ClipboardCategory.CreateEntry<bool>("Show stations", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)ShowClipboardStations.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnShowClipboardStationsChanged, 0, false);
			ShowClipboardStationsOutput = ClipboardCategory.CreateEntry<bool>("Show stations output", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)ShowClipboardStationsOutput.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnShowClipboardStationsOutputChanged, 0, false);
		}

		private static void CreateLabelColorPickerSettings()
		{
			LabelColorPickerCategory = MelonPreferences.CreateCategory("SimpleLabels_03_ColorPicker", "Label Color Picker");
			AutomaticallySetLabelColorOptions = LabelColorPickerCategory.CreateEntry<bool>("Auto-detect Colors from Stored Items", false, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)AutomaticallySetLabelColorOptions.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnAutomaticallySetLabelColorOptionsChanged, 0, false);
		}

		private static void CreateFontColorPickerSettings()
		{
			FontColorPickerCategory = MelonPreferences.CreateCategory("SimpleLabels_04_ColorPicker", "Font Color Picker");
		}

		private static void CreateLabelSettings()
		{
			LabelCategory = MelonPreferences.CreateCategory("SimpleLabels_05_Label", "Labels");
			LabelDefaultSize = LabelCategory.CreateEntry<int>("Default size (1 - 30)", 1, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<int, int>>)(object)LabelDefaultSize.OnEntryValueChanged).Subscribe((LemonAction<int, int>)OnLabelDefaultSizeChanged, 0, false);
			LabelDefaultColor = LabelCategory.CreateEntry<string>("Default color", "#FFFFFF", (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<string, string>>)(object)LabelDefaultColor.OnEntryValueChanged).Subscribe((LemonAction<string, string>)OnLabelDefaultColorChanged, 0, false);
		}

		private static void CreateFontSettings()
		{
			FontCategory = MelonPreferences.CreateCategory("SimpleLabels_06_Font", "Font");
			FontDefaultColor = FontCategory.CreateEntry<string>("Default color", "#000000", (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<string, string>>)(object)FontDefaultColor.OnEntryValueChanged).Subscribe((LemonAction<string, string>)OnFontDefaultColorChanged, 0, false);
		}

		private static void CreateDebugSettings()
		{
			DebugCategory = MelonPreferences.CreateCategory("SimpleLabels_07_Debug", "Debug");
			ShowDebug = DebugCategory.CreateEntry<bool>("Show console debug", false, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<bool, bool>>)(object)ShowDebug.OnEntryValueChanged).Subscribe((LemonAction<bool, bool>)OnShowDebugChanged, 0, false);
		}

		private static void OnShowInputChanged(bool oldValue, bool newValue)
		{
			ShowInput.Value = newValue;
		}

		private static void OnAutoFocusInputChanged(bool oldValue, bool newValue)
		{
			AutoFocusInput.Value = newValue;
		}

		private static void OnShowClipboardRoutesChanged(bool oldValue, bool newValue)
		{
			ShowClipboardRoutes.Value = newValue;
		}

		private static void OnShowClipboardStationsChanged(bool oldValue, bool newValue)
		{
			ShowClipboardStations.Value = newValue;
		}

		private static void OnShowClipboardStationsOutputChanged(bool oldValue, bool newValue)
		{
			ShowClipboardStationsOutput.Value = newValue;
		}

		private static void OnLabelDefaultSizeChanged(int oldValue, int newValue)
		{
			CheckValidSizeAndUpdate(newValue, LabelDefaultSize);
		}

		private static void OnLabelDefaultColorChanged(string oldValue, string newValue)
		{
			CheckCorrectFormatAndUpdate(newValue, LabelDefaultColor);
		}

		private static void OnAutomaticallySetLabelColorOptionsChanged(bool oldValue, bool newValue)
		{
			AutomaticallySetLabelColorOptions.Value = newValue;
		}

		private static void OnFontDefaultColorChanged(string oldValue, string newValue)
		{
			CheckCorrectFormatAndUpdate(newValue, FontDefaultColor);
		}

		private static void OnShowDebugChanged(bool oldValue, bool newValue)
		{
			ShowDebug.Value = newValue;
		}

		private static void CheckCorrectFormatAndUpdate(string newValue, MelonPreferences_Entry<string> entry)
		{
			if (Regex.IsMatch(newValue, "^#[0-9A-Fa-f]{6}$"))
			{
				entry.Value = newValue;
				ColorPickerManager.UpdateAllColorPickers(ColorPickerType.Label);
				ColorPickerManager.UpdateAllColorPickers(ColorPickerType.Font);
			}
			else
			{
				Logger.Warning("Invalid color format: " + newValue + ". Reverted to " + entry.DefaultValue);
				entry.Value = entry.DefaultValue;
				ModManagerIntegration.RequestUIRefresh();
			}
		}

		private static void CheckValidSizeAndUpdate(int newValue, MelonPreferences_Entry<int> entry)
		{
			if (newValue >= 1 && newValue <= 30)
			{
				entry.Value = newValue;
				return;
			}
			Logger.Warning($"Invalid size value: {newValue}. Must be between 1 and 30. Reverted to {entry.DefaultValue}");
			entry.Value = entry.DefaultValue;
			ModManagerIntegration.RequestUIRefresh();
		}
	}
}
namespace SimpleLabels.Services
{
	public static class LabelService
	{
		public static void CreateLabel(string guid, GameObject gameObject, string labelText = "", string labelColor = null, int? labelSize = null, int? fontSize = null, string fontColor = null)
		{
			if (string.IsNullOrEmpty(guid))
			{
				Logger.Error("[LabelService] Cannot create label: GUID is empty");
				return;
			}
			string labelColor2 = labelColor ?? ModSettings.LabelDefaultColor.Value;
			int labelSize2 = labelSize ?? ModSettings.LabelDefaultSize.Value;
			int fontSize2 = fontSize ?? ModSettings.DEFAULT_FONT_SIZE;
			string fontColor2 = fontColor ?? ModSettings.FontDefaultColor.Value;
			LabelTracker.StoreEntity(guid, gameObject, labelText, labelColor2, labelSize2, fontSize2, fontColor2);
			if ((Object)(object)gameObject != (Object)null && !string.IsNullOrEmpty(labelText))
			{
				LabelApplier.ApplyOrUpdateLabel(guid);
			}
			LabelNetworkManager.NotifyLabelChanged(guid);
		}

		public static void UpdateLabel(string guid, string newLabelText = null, string newLabelColor = null, int? newLabelSize = null, int? newFontSize = null, string newFontColor = null, bool fromNetwork = false)
		{
			if (string.IsNullOrEmpty(guid))
			{
				Logger.Error("[LabelService] Cannot update label: GUID is empty");
				return;
			}
			EntityData entityData = LabelTracker.GetEntityData(guid);
			if (entityData == null)
			{
				Logger.Warning("[LabelService] Cannot update label: Entity " + guid + " not found");
				return;
			}
			LabelTracker.UpdateEntityData(guid, newLabelText, newLabelColor, newLabelSize, newFontSize, newFontColor);
			LabelApplier.ApplyOrUpdateLabel(guid);
			if (!fromNetwork)
			{
				LabelNetworkManager.NotifyLabelChanged(guid);
			}
		}

		public static void RemoveLabel(string guid)
		{
			if (!string.IsNullOrEmpty(guid))
			{
				UpdateLabel(guid, "");
			}
		}

		public static void BindGameObject(string guid, GameObject gameObject)
		{
			if (string.IsNullOrEmpty(guid) || (Object)(object)gameObject == (Object)null)
			{
				return;
			}
			EntityData entityData = LabelTracker.GetEntityData(guid);
			if (entityData == null)
			{
				Logger.Warning("[LabelService] Cannot bind GameObject: Entity " + guid + " not found");
				return;
			}
			LabelTracker.UpdateGameObjectReference(guid, gameObject);
			if (!string.IsNullOrEmpty(entityData.LabelText))
			{
				LabelApplier.ApplyOrUpdateLabel(guid);
			}
		}

		public static void UpdateLabelFromNetwork(string guid, string newLabelText = null, string newLabelColor = null, int? newLabelSize = null, int? newFontSize = null, string newFontColor = null)
		{
			UpdateLabel(guid, newLabelText, newLabelColor, newLabelSize, newFontSize, newFontColor, fromNetwork: true);
		}

		public static void ApplyNetworkLabels(Dictionary<string, EntityData> networkedData)
		{
			foreach (KeyValuePair<string, EntityData> networkedDatum in networkedData)
			{
				string key = networkedDatum.Key;
				EntityData value = networkedDatum.Value;
				EntityData entityData = LabelTracker.GetEntityData(key);
				if (entityData != null)
				{
					UpdateLabelFromNetwork(key, value.LabelText, value.LabelColor, value.LabelSize, value.FontSize, value.FontColor);
				}
				else
				{
					CreateLabel(key, null, value.LabelText, value.LabelColor, value.LabelSize, value.FontSize, value.FontColor);
				}
			}
			LabelApplier.ForceUpdateAllLabels();
		}

		public static void BindAllGameObjectsAndApplyLabels()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			Il2CppArrayBase<GridItem> val = Object.FindObjectsOfType<GridItem>();
			Il2CppArrayBase<SurfaceItem> val2 = Object.FindObjectsOfType<SurfaceItem>();
			Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>();
			Guid gUID;
			foreach (GridItem item in val)
			{
				if (!((Object)(object)item == (Object)null))
				{
					gUID = ((BuildableItem)item).GUID;
					string text = ((object)(Guid)(ref gUID)).ToString();
					if (!string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text))
					{
						dictionary.Add(text, ((Component)item).gameObject);
					}
				}
			}
			foreach (SurfaceItem item2 in val2)
			{
				if (!((Object)(object)item2 == (Object)null))
				{
					gUID = ((BuildableItem)item2).GUID;
					string text2 = ((object)(Guid)(ref gUID)).ToString();
					if (!string.IsNullOrEmpty(text2) && !dictionary.ContainsKey(text2))
					{
						dictionary.Add(text2, ((Component)item2).gameObject);
					}
				}
			}
			foreach (string allTrackedGuid in LabelTracker.GetAllTrackedGuids())
			{
				EntityData entityData = LabelTracker.GetEntityData(allTrackedGuid);
				if (entityData != null)
				{
					if ((Object)(object)entityData.GameObject == (Object)null && dictionary.TryGetValue(allTrackedGuid, out var value))
					{
						Logger.Msg("[LabelService] Binding GameObject for synced label: GUID=" + allTrackedGuid);
						BindGameObject(allTrackedGuid, value);
					}
					else if ((Object)(object)entityData.GameObject != (Object)null && !string.IsNullOrEmpty(entityData.LabelText))
					{
						LabelApplier.ApplyOrUpdateLabel(allTrackedGuid);
					}
				}
			}
		}
	}
}
namespace SimpleLabels.Patches
{
	[HarmonyPatch]
	public class ClipboardPatches
	{
		[HarmonyPatch(typeof(RouteListFieldUI), "Refresh")]
		[HarmonyPostfix]
		public static void OnRouteListRefresh(RouteListFieldUI __instance, List<AdvancedTransitRoute> newVal)
		{
			if (!ModSettings.ShowClipboardRoutes.Value)
			{
				return;
			}
			Transform obj = ((Component)__instance).gameObject.transform.Find("Contents");
			object obj2 = ((obj != null) ? ((Component)obj).gameObject : null);
			if (obj2 == null)
			{
				Transform obj3 = ((Component)__instance).gameObject.transform.Find("ScrollArea/Contents");
				obj2 = ((obj3 != null) ? ((Component)obj3).gameObject : null);
			}
			GameObject val = (GameObject)obj2;
			if ((Object)(object)val == (Object)null)
			{
				Logger.Error("[Clipboard] Couldn't find RouteList contents container");
				return;
			}
			IEnumerator enumerator = val.transform.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Object current = enumerator.Current;
					Transform val2 = ((Il2CppObjectBase)current).TryCast<Transform>();
					if (!((Object)(object)val2 == (Object)null) && ((Object)val2).name.Contains("Entry") && ((Component)val2).gameObject.active)
					{
						RouteEntryUI component = ((Component)val2).GetComponent<RouteEntryUI>();
						object obj4;
						if (component == null)
						{
							obj4 = null;
						}
						else
						{
							AdvancedTransitRoute assignedRoute = component.AssignedRoute;
							obj4 = ((assignedRoute != null) ? assignedRoute.GetData() : null);
						}
						if (obj4 == null)
						{
							Logger.Warning("[Clipboard] Missing route data on " + ((Object)val2).name);
							continue;
						}
						AdvancedTransitRouteData data = component.AssignedRoute.GetData();
						UpdateRouteLabel(val2, "Source/Label", data.SourceGUID);
						UpdateRouteLabel(val2, "Destination/Label", data.DestinationGUID);
					}
				}
			}
			finally
			{
				if (enumerator is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}
		}

		private static void UpdateRouteLabel(Transform entryTransform, string labelPath, string guid)
		{
			Transform val = entryTransform.Find(labelPath);
			if ((Object)(object)val == (Object)null)
			{
				Logger.Warning("[Clipboard] Missing label path: " + labelPath);
				return;
			}
			TextMeshProUGUI componentInChildren = ((Component)val).GetComponentInChildren<TextMeshProUGUI>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				Logger.Warning("[Clipboard] Missing TextMeshPro component at " + labelPath);
			}
			else if (!string.IsNullOrEmpty(guid))
			{
				EntityData entityData = LabelTracker.GetEntityData(guid);
				if (entityData != null && !string.IsNullOrEmpty(entityData.LabelText))
				{
					((TMP_Text)componentInChildren).text = entityData.LabelText;
				}
			}
		}

		[HarmonyPatch(typeof(ObjectListFieldUI), "Refresh")]
		[HarmonyPostfix]
		public static void OnObjectListRefresh(ObjectListFieldUI __instance, List<BuildableItem> newVal)
		{
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			if (!ModSettings.ShowClipboardStations.Value)
			{
				return;
			}
			Transform obj = ((Component)__instance).gameObject.transform.Find("Contents");
			GameObject val = ((obj != null) ? ((Component)obj).gameObject : null);
			if ((Object)(object)val == (Object)null)
			{
				Logger.Error("[Clipboard] Couldn't find ObjectList contents container");
				return;
			}
			IEnumerator enumerator = val.transform.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Object current = enumerator.Current;
					Transform val2 = ((Il2CppObjectBase)current).TryCast<Transform>();
					if ((Object)(object)val2 == (Object)null || !((Object)val2).name.Contains("Entry") || !((Component)val2).gameObject.active)
					{
						continue;
					}
					Transform val3 = val2.Find("Title");
					if ((Object)(object)val3 == (Object)null)
					{
						Logger.Warning("[Clipboard] Missing title on " + ((Object)val2).name);
						continue;
					}
					TextMeshProUGUI componentInChildren = ((Component)val3).GetComponentInChildren<TextMeshProUGUI>();
					if ((Object)(object)componentInChildren == (Object)null)
					{
						Logger.Warning("[Clipboard] Missing text component on " + ((Object)val2).name);
						continue;
					}
					int siblingIndex = val2.GetSiblingIndex();
					if (siblingIndex < newVal.Count)
					{
						Guid gUID = newVal._items[siblingIndex].GUID;
						string guid = ((object)(Guid)(ref gUID)).ToString();
						EntityData entityData = LabelTracker.GetEntityData(guid);
						if (entityData != null && !string.IsNullOrEmpty(entityData.LabelText))
						{
							((TMP_Text)componentInChildren).text = entityData.LabelText;
						}
					}
				}
			}
			finally
			{
				if (enumerator is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}
		}

		[HarmonyPatch(typeof(ObjectFieldUI), "Refresh")]
		[HarmonyPostfix]
		public static void OnObjectFieldRefresh(ObjectFieldUI __instance, BuildableItem newVal)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (!ModSettings.ShowClipboardStationsOutput.Value || (Object)(object)newVal == (Object)null)
			{
				return;
			}
			TextMeshProUGUI selectionLabel = __instance.SelectionLabel;
			if (!((Object)(object)selectionLabel == (Object)null))
			{
				Guid gUID = newVal.GUID;
				EntityData entityData = LabelTracker.GetEntityData(((object)(Guid)(ref gUID)).ToString());
				if (entityData != null && !string.IsNullOrEmpty(entityData.LabelText))
				{
					((TMP_Text)selectionLabel).text = entityData.LabelText;
				}
			}
		}
	}
	[HarmonyPatch]
	public class LoaderPatches
	{
		private const string ZeroGuid = "00000000-0000-0000-0000-000000000000";

		[HarmonyPatch(typeof(GridItem), "Awake")]
		[HarmonyPostfix]
		private static void OnGridItemAwake(GridItem __instance)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance == (Object)null))
			{
				Guid gUID = ((BuildableItem)__instance).GUID;
				string guid = ((object)(Guid)(ref gUID)).ToString();
				TryCreateLabelsForEntity(((Component)__instance).gameObject, guid, ((Object)__instance).name);
			}
		}

		[HarmonyPatch(typeof(SurfaceItem), "Awake")]
		[HarmonyPostfix]
		private static void OnSurfaceItemAwake(SurfaceItem __instance)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance == (Object)null))
			{
				Guid gUID = ((BuildableItem)__instance).GUID;
				string guid = ((object)(Guid)(ref gUID)).ToString();
				TryCreateLabelsForEntity(((Component)__instance).gameObject, guid, ((Object)__instance).name);
			}
		}

		[HarmonyPatch(typeof(BuildManager), "CreateGridItem")]
		[HarmonyPostfix]
		private static void OnGridItemCreated(GridItem __result, ItemInstance item, Grid grid, Vector2 originCoordinate, int rotation, string guid)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__result == (Object)null))
			{
				string text;
				if (string.IsNullOrEmpty(guid))
				{
					Guid gUID = ((BuildableItem)__result).GUID;
					text = ((object)(Guid)(ref gUID)).ToString();
				}
				else
				{
					text = guid;
				}
				string guid2 = text;
				TryCreateLabelsForEntity(((Component)__result).gameObject, guid2, ((Object)__result).name);
			}
		}

		[HarmonyPatch(typeof(BuildManager), "CreateSurfaceItem")]
		[HarmonyPostfix]
		private static void OnSurfaceItemCreated(SurfaceItem __result, ItemInstance item, Surface parentSurface, Vector3 relativePosition, Quaternion relativeRotation, string guid)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__result == (Object)null))
			{
				string text;
				if (string.IsNullOrEmpty(guid))
				{
					Guid gUID = ((BuildableItem)__result).GUID;
					text = ((object)(Guid)(ref gUID)).ToString();
				}
				else
				{
					text = guid;
				}
				string guid2 = text;
				TryCreateLabelsForEntity(((Component)__result).gameObject, guid2, ((Object)__result).name);
			}
		}

		[HarmonyPatch(typeof(LoadManager), "Start")]
		[HarmonyPostfix]
		private static void OnLoadManagerStart(LoadManager __instance)
		{
			__instance.onLoadComplete.AddListener(UnityAction.op_Implicit((Action)delegate
			{
				LabelDataManager.LoadLabelsForCurrentSave();
				LabelNetworkManager.RequestLabelSyncFromHost();
				LabelNetworkManager.LoadSyncedLabels();
				LabelNetworkManager.SyncLabelsToNetwork();
			}));
		}

		private static void TryCreateLabelsForEntity(GameObject gameObject, string guid, string originalName)
		{
			if ((Object)(object)gameObject == (Object)null || string.IsNullOrEmpty(guid) || guid == "00000000-0000-0000-0000-000000000000")
			{
				return;
			}
			try
			{
				string text = CleanEntityName(originalName);
				if (!LabelPlacementConfigs.LabelPlacementConfigsDictionary.ContainsKey(text))
				{
					Logger.Msg("[Loader] Entity type '" + text + "' not supported for labels");
					return;
				}
				EntityData entityData = LabelTracker.GetEntityData(guid);
				if (entityData == null)
				{
					Logger.Msg("[Loader] Creating new entity: GUID=" + guid + ", Type=" + text);
					LabelService.CreateLabel(guid, gameObject, string.Empty, ModSettings.LabelDefaultColor.Value, ModSettings.LabelDefaultSize.Value, ModSettings.DEFAULT_FONT_SIZE, ModSettings.FontDefaultColor.Value);
				}
				else
				{
					Logger.Msg("[Loader] Binding GameObject to existing entity: GUID=" + guid);
					LabelService.BindGameObject(guid, gameObject);
				}
			}
			catch (Exception ex)
			{
				Logger.Error("Failed to process " + originalName + ": " + ex.Message);
			}
		}

		public static string CleanEntityName(string originalName)
		{
			return originalName.Replace("(Clone)", "").Replace("_Built", "").Trim();
		}
	}
	public class StationPatches
	{
		[HarmonyPatch(typeof(PackagingStationCanvas), "SetIsOpen")]
		private static class PackagingStationPatch
		{
			[HarmonyPostfix]
			public static void Postfix(PackagingStation station, bool open)
			{
				if (open)
				{
					HandleStationOpen((GridItem)(object)station, "Packaging Station");
				}
			}
		}

		[HarmonyPatch(typeof(DryingRackCanvas