Decompiled source of Custom Structures v1.4.0

Custom Structures.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using CUCoreLib.Data;
using CUCoreLib.Helpers;
using CUCoreLib.Networking;
using CUCoreLib.Registries;
using Custom_Structures;
using HarmonyLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.Tilemaps;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("More Structures")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP")]
[assembly: AssemblyProduct("More Structures")]
[assembly: AssemblyCopyright("Copyright © HP 2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("32f083e1-73e7-4759-b056-e240804dd6f5")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.4.0.0")]
namespace More_Structures
{
	internal class WorldGenerationPatcher : Custom_Structures.WorldGenerationPatcher
	{
	}
}
namespace Custom_Structures
{
	internal sealed class BackgroundObjectIdentity : MonoBehaviour
	{
		public string Id;
	}
	internal sealed class BackgroundInteractionBinding : MonoBehaviour
	{
		public string ObjectId;

		public string SignalId;

		public string ToggleString = "Use";

		public string TooltipName;

		public string TooltipDesc;

		public float RangeMultiplier = 1f;

		public bool ActivateOnce;

		public bool HasSignalId => !string.IsNullOrWhiteSpace(SignalId);

		public bool IsActivatedOnce { get; private set; }

		public string ResolvedTooltipName
		{
			get
			{
				if (!string.IsNullOrWhiteSpace(TooltipName))
				{
					return TooltipName;
				}
				if (string.IsNullOrWhiteSpace(ObjectId))
				{
					return "Object";
				}
				return char.ToUpperInvariant(ObjectId[0]) + ObjectId.Substring(1);
			}
		}

		public bool CanUse()
		{
			if (ActivateOnce)
			{
				return !IsActivatedOnce;
			}
			return true;
		}

		public void MarkUsed()
		{
			if (ActivateOnce)
			{
				IsActivatedOnce = true;
			}
		}
	}
	internal sealed class BackgroundBuildingNameOverride : MonoBehaviour
	{
		public string FullName;

		public string Description;

		private bool applied;

		private void LateUpdate()
		{
			if (applied)
			{
				return;
			}
			BuildingEntity component = ((Component)this).GetComponent<BuildingEntity>();
			if (!((Object)(object)component == (Object)null))
			{
				if (!string.IsNullOrWhiteSpace(FullName))
				{
					component.fullName = FullName;
				}
				if (Description != null)
				{
					component.description = Description;
				}
				applied = true;
				Object.Destroy((Object)(object)this);
			}
		}
	}
	internal sealed class PodButtonDestroyOnZeroHealth : MonoBehaviour
	{
		private BuildingEntity building;

		private void Awake()
		{
			building = ((Component)this).GetComponent<BuildingEntity>();
		}

		private void Update()
		{
			if (!((Object)(object)building == (Object)null) && !(building.health > 0f))
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}
	[DataContract]
	internal sealed class BackgroundObjectRegistryFile
	{
		[DataMember(Name = "objects")]
		public List<BackgroundObjectRegistryEntryDto> Objects { get; set; }
	}
	[DataContract]
	internal sealed class BackgroundObjectRegistryEntryDto
	{
		[DataMember(Name = "id")]
		public string Id { get; set; }

		[DataMember(Name = "spritePath")]
		public string SpritePath { get; set; }

		[DataMember(Name = "pivot")]
		public BackgroundObjectPivotDto Pivot { get; set; }

		[DataMember(Name = "pixelsPerUnit")]
		public float PixelsPerUnit { get; set; }

		[DataMember(Name = "sortingOrder")]
		public int SortingOrder { get; set; }

		[DataMember(Name = "sortingLayer")]
		public string SortingLayer { get; set; }

		[DataMember(Name = "collisionMaskPath")]
		public string CollisionMaskPath { get; set; }

		[DataMember(Name = "trigger")]
		public BackgroundObjectTriggerDto Trigger { get; set; }

		[DataMember(Name = "collider")]
		public BackgroundObjectColliderDto Collider { get; set; }
	}
	[DataContract]
	internal sealed class BackgroundObjectPivotDto
	{
		[DataMember(Name = "x")]
		public float X { get; set; }

		[DataMember(Name = "y")]
		public float Y { get; set; }
	}
	[DataContract]
	internal sealed class BackgroundObjectTriggerDto
	{
		[DataMember(Name = "id")]
		public string Id { get; set; }

		[DataMember(Name = "activateOnce")]
		public bool ActivateOnce { get; set; }

		[DataMember(Name = "addUsable")]
		public bool AddUsable { get; set; } = true;
	}
	[DataContract]
	internal sealed class BackgroundObjectColliderDto
	{
		[DataMember(Name = "minRegionArea")]
		public int MinRegionArea { get; set; }

		[DataMember(Name = "mergePasses")]
		public int MergePasses { get; set; }
	}
	internal sealed class BackgroundObjectDefinition
	{
		public string Id;

		public string SpritePath;

		public float PivotX = 0.5f;

		public float PivotY = 0.5f;

		public float PixelsPerUnit = 16f;

		public int SortingOrder;

		public string SortingLayer;

		public string CollisionMaskPath;

		public BackgroundObjectTriggerDto Trigger;

		public BackgroundObjectColliderDto Collider;
	}
	internal static class BackgroundObjectRegistry
	{
		private const string RegistryRelativePath = "BackgroundObjects/background-objects.json";

		private static readonly Dictionary<string, BackgroundObjectDefinition> Definitions = new Dictionary<string, BackgroundObjectDefinition>(StringComparer.OrdinalIgnoreCase);

		private static readonly BackgroundObjectRegistryEntryDto[] BuiltInEntries = new BackgroundObjectRegistryEntryDto[23]
		{
			new BackgroundObjectRegistryEntryDto
			{
				Id = "amongus",
				SpritePath = "amongus.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "arrowtip",
				SpritePath = "arrowtip.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "beartrapclosed",
				SpritePath = "beartrapclosed.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "brokendoor",
				SpritePath = "brokendoor.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "celldoor",
				SpritePath = "celldoor.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "holidaytree",
				SpritePath = "holidaytree.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "jackolantern",
				SpritePath = "jackolantern.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "mattress",
				SpritePath = "mattress.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "podbutton",
				SpritePath = "podbutton.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "sleepingbagopen",
				SpritePath = "sleepingbagopen.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "table",
				SpritePath = "table.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "thirdlawdoodle",
				SpritePath = "thirdlawdoodle.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipcontainer",
				SpritePath = "tipcontainer.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipknowledge",
				SpritePath = "tipknowledge.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipmedical",
				SpritePath = "tipmedical.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipmine",
				SpritePath = "tipmine.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipsleep",
				SpritePath = "tipsleep.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tipwait",
				SpritePath = "tipwait.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "turretrailing",
				SpritePath = "turretrailing.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tutorialcamera",
				SpritePath = "tutorialcamera.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tutorialdoor",
				SpritePath = "tutorialdoor.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tutorialdoorframe",
				SpritePath = "tutorialDoorFrame.png",
				PixelsPerUnit = 8f
			},
			new BackgroundObjectRegistryEntryDto
			{
				Id = "tutorialspeaker",
				SpritePath = "tutorialspeaker.png",
				PixelsPerUnit = 8f
			}
		};

		private static string structureRootPath;

		private static string backgroundRootPath;

		public static string BackgroundRootPath => backgroundRootPath;

		public static void Reload(string structuresRootPath)
		{
			Definitions.Clear();
			structureRootPath = structuresRootPath;
			backgroundRootPath = Path.Combine(structuresRootPath ?? string.Empty, "BackgroundObjects");
			LoadBuiltInDefinitions();
			if (string.IsNullOrWhiteSpace(structureRootPath))
			{
				return;
			}
			string text = Path.Combine(structureRootPath, "BackgroundObjects/background-objects.json");
			if (!File.Exists(text))
			{
				return;
			}
			try
			{
				List<BackgroundObjectRegistryEntryDto> list = DeserializeEntries(File.ReadAllText(text));
				if (list != null && list.Count != 0)
				{
					for (int i = 0; i < list.Count; i++)
					{
						TryApplyEntry(list[i], "registry '" + text + "'", i);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static bool TryGet(string id, out BackgroundObjectDefinition definition)
		{
			definition = null;
			string text = NormalizeId(id);
			if (string.IsNullOrWhiteSpace(text))
			{
				return false;
			}
			return Definitions.TryGetValue(text, out definition);
		}

		public static bool IsRegistered(string id)
		{
			BackgroundObjectDefinition definition;
			return TryGet(id, out definition);
		}

		private static List<BackgroundObjectRegistryEntryDto> DeserializeEntries(string json)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			if (string.IsNullOrWhiteSpace(json))
			{
				return null;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(json);
			try
			{
				DataContractJsonSerializer val = new DataContractJsonSerializer(typeof(BackgroundObjectRegistryFile));
				using MemoryStream memoryStream = new MemoryStream(bytes);
				BackgroundObjectRegistryFile backgroundObjectRegistryFile = ((XmlObjectSerializer)val).ReadObject((Stream)memoryStream) as BackgroundObjectRegistryFile;
				if (backgroundObjectRegistryFile?.Objects != null)
				{
					return backgroundObjectRegistryFile.Objects;
				}
			}
			catch
			{
			}
			try
			{
				DataContractJsonSerializer val2 = new DataContractJsonSerializer(typeof(List<BackgroundObjectRegistryEntryDto>));
				using MemoryStream memoryStream2 = new MemoryStream(bytes);
				return ((XmlObjectSerializer)val2).ReadObject((Stream)memoryStream2) as List<BackgroundObjectRegistryEntryDto>;
			}
			catch
			{
				return null;
			}
		}

		private static string NormalizeId(string raw)
		{
			if (!string.IsNullOrWhiteSpace(raw))
			{
				return raw.Trim().ToLowerInvariant();
			}
			return string.Empty;
		}

		private static string NormalizeRelativePath(string raw)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				return string.Empty;
			}
			return raw.Trim().Replace('\\', '/');
		}

		private static float Clamp01OrDefault(float value, float fallback)
		{
			if (float.IsNaN(value) || float.IsInfinity(value))
			{
				return fallback;
			}
			return Mathf.Clamp01(value);
		}

		private static void LoadBuiltInDefinitions()
		{
			for (int i = 0; i < BuiltInEntries.Length; i++)
			{
				TryApplyEntry(BuiltInEntries[i], "built-in", i);
			}
		}

		private static void TryApplyEntry(BackgroundObjectRegistryEntryDto entry, string sourceLabel, int index)
		{
			if (entry != null)
			{
				string text = NormalizeId(entry.Id);
				if (!string.IsNullOrWhiteSpace(text) && !string.IsNullOrWhiteSpace(entry.SpritePath))
				{
					Definitions[text] = new BackgroundObjectDefinition
					{
						Id = text,
						SpritePath = NormalizeRelativePath(entry.SpritePath),
						PivotX = Clamp01OrDefault((entry.Pivot != null) ? entry.Pivot.X : float.NaN, 0.5f),
						PivotY = Clamp01OrDefault((entry.Pivot != null) ? entry.Pivot.Y : float.NaN, 0.5f),
						PixelsPerUnit = ((entry.PixelsPerUnit > 0f) ? entry.PixelsPerUnit : 16f),
						SortingOrder = entry.SortingOrder,
						SortingLayer = entry.SortingLayer?.Trim(),
						CollisionMaskPath = NormalizeRelativePath(entry.CollisionMaskPath),
						Trigger = entry.Trigger,
						Collider = entry.Collider
					};
				}
			}
		}
	}
	internal static class BackgroundObjectSpawner
	{
		private sealed class InteractionTemplate
		{
			public bool Initialized;

			public Vector2 ColliderSize = Vector2.one;

			public Vector2 ColliderOffset = Vector2.zero;

			public bool ColliderIsTrigger;

			public float RangeMultiplier = 1f;

			public string ToggleString = "Use";
		}

		private sealed class BackgroundObjectUseRelay : MonoBehaviour
		{
			private BackgroundInteractionBinding binding;

			private void Awake()
			{
				binding = ((Component)this).GetComponent<BackgroundInteractionBinding>() ?? ((Component)this).GetComponentInParent<BackgroundInteractionBinding>();
			}

			public void OnUse()
			{
				if (!((Object)(object)binding != (Object)null) || binding.CanUse())
				{
					StructureSignalRuntime.EmitUseSignals(((Component)this).gameObject);
					binding?.MarkUsed();
				}
			}
		}

		private struct IntRect
		{
			public int X;

			public int Y;

			public int W;

			public int H;
		}

		private static GameObject cachedSpawnTemplate;

		private static readonly Dictionary<string, Sprite> SpriteCache = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> MissingSpriteWarnings = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly Type BoxCollider2DType = Type.GetType("UnityEngine.BoxCollider2D, UnityEngine.Physics2DModule");

		private static readonly InteractionTemplate ScrapeaterTemplate = new InteractionTemplate();

		public static GameObject TrySpawn(StructureEntityDef def, Vector2 pos, BackgroundObjectDefinition definition)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//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 (def == null || definition == null)
			{
				return null;
			}
			if (!TryGetSprite(definition, out var sprite))
			{
				MissingSpriteWarnings.Add(definition.Id);
				return null;
			}
			GameObject spawnTemplate = GetSpawnTemplate();
			if ((Object)(object)spawnTemplate == (Object)null)
			{
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(spawnTemplate, Vector2.op_Implicit(pos), Quaternion.identity);
			MoreStructuresMpCompat.MarkLocalObject(val);
			((Object)val).name = "bgobj_" + definition.Id;
			val.AddComponent<BackgroundObjectIdentity>().Id = definition.Id;
			if ((Object)(object)WorldGeneration.world?.worldGrid != (Object)null)
			{
				val.transform.SetParent(((Component)WorldGeneration.world.worldGrid).transform, true);
			}
			SpriteRenderer val2 = val.GetComponent<SpriteRenderer>();
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = val.AddComponent<SpriteRenderer>();
			}
			val2.sprite = sprite;
			((Renderer)val2).sortingOrder = definition.SortingOrder;
			if (!string.IsNullOrWhiteSpace(definition.SortingLayer))
			{
				((Renderer)val2).sortingLayerName = definition.SortingLayer;
			}
			ApplyTransform(def, val);
			TryAttachSignalTrigger(definition, def, val);
			TryAddMaskColliders(definition, val, sprite);
			val.SetActive(true);
			return val;
		}

		private static GameObject GetSpawnTemplate()
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)cachedSpawnTemplate != (Object)null)
			{
				return cachedSpawnTemplate;
			}
			cachedSpawnTemplate = Object.Instantiate<GameObject>(Resources.Load<GameObject>("stoneplant"));
			Object.DontDestroyOnLoad((Object)(object)cachedSpawnTemplate);
			((Object)cachedSpawnTemplate).name = "MoreStructures_BGObject_Template";
			cachedSpawnTemplate.SetActive(false);
			Component[] components = cachedSpawnTemplate.GetComponents<Component>();
			foreach (Component val in components)
			{
				if (!(val is Transform) && !(val is SpriteRenderer))
				{
					Object.DestroyImmediate((Object)(object)val);
				}
			}
			foreach (Transform item in cachedSpawnTemplate.transform)
			{
				Object.DestroyImmediate((Object)(object)((Component)item).gameObject);
			}
			return cachedSpawnTemplate;
		}

		private static void ApplyTransform(StructureEntityDef def, GameObject obj)
		{
			//IL_0036: 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)
			if (def != null && !((Object)(object)obj == (Object)null))
			{
				if (def.Rotation != 0f)
				{
					obj.transform.rotation = Quaternion.Euler(0f, 0f, -1f * def.Rotation);
				}
				float num = (def.FlipX ? (0f - def.Scale) : def.Scale);
				float num2 = (def.FlipY ? (0f - def.Scale) : def.Scale);
				if (!Mathf.Approximately(num, 1f) || !Mathf.Approximately(num2, 1f))
				{
					obj.transform.localScale = new Vector3(num, num2, 1f);
				}
			}
		}

		private static void TryAttachSignalTrigger(BackgroundObjectDefinition definition, StructureEntityDef entityDef, GameObject obj)
		{
			if (definition == null || (Object)(object)obj == (Object)null)
			{
				return;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			if (entityDef?.CustomProperties != null)
			{
				foreach (KeyValuePair<string, string> customProperty in entityDef.CustomProperties)
				{
					if (!string.IsNullOrWhiteSpace(customProperty.Key) && !string.IsNullOrWhiteSpace(customProperty.Value))
					{
						dictionary[customProperty.Key.Trim()] = customProperty.Value.Trim();
					}
				}
			}
			BackgroundObjectTriggerDto trigger = definition.Trigger;
			if (trigger != null)
			{
				ApplyTriggerDefaults(dictionary, trigger);
			}
			bool num = HasInteractionProperties(dictionary);
			bool flag = trigger?.AddUsable ?? true;
			if (num && flag)
			{
				BindInteraction(definition, dictionary, obj);
			}
			if (dictionary.Count != 0)
			{
				StructureSignalRuntime.TryAttachNode(obj, dictionary, definition.Id);
			}
		}

		private static bool HasInteractionProperties(Dictionary<string, string> mergedProperties)
		{
			if (mergedProperties == null || mergedProperties.Count == 0)
			{
				return false;
			}
			if (!mergedProperties.ContainsKey("id") && !mergedProperties.ContainsKey("toggleString") && !mergedProperties.ContainsKey("tooltipName") && !mergedProperties.ContainsKey("tooltipDesc") && !mergedProperties.ContainsKey("rangeMultiplier"))
			{
				return mergedProperties.ContainsKey("activateOnce");
			}
			return true;
		}

		private static void BindInteraction(BackgroundObjectDefinition definition, Dictionary<string, string> mergedProperties, GameObject obj)
		{
			if (definition != null && mergedProperties != null && !((Object)(object)obj == (Object)null))
			{
				BackgroundInteractionBinding backgroundInteractionBinding = obj.GetComponent<BackgroundInteractionBinding>();
				if ((Object)(object)backgroundInteractionBinding == (Object)null)
				{
					backgroundInteractionBinding = obj.AddComponent<BackgroundInteractionBinding>();
				}
				backgroundInteractionBinding.ObjectId = definition.Id;
				backgroundInteractionBinding.SignalId = ReadStringProperty(mergedProperties, "id", string.Empty).ToLowerInvariant();
				backgroundInteractionBinding.ToggleString = ReadStringProperty(mergedProperties, "toggleString", "Use");
				backgroundInteractionBinding.TooltipName = ReadStringProperty(mergedProperties, "tooltipName", string.Empty);
				backgroundInteractionBinding.TooltipDesc = ReadStringProperty(mergedProperties, "tooltipDesc", string.Empty);
				backgroundInteractionBinding.RangeMultiplier = ReadFloatProperty(mergedProperties, "rangeMultiplier", 1f, 0.05f, 100f);
				backgroundInteractionBinding.ActivateOnce = ReadBoolProperty(mergedProperties, false, "activateOnce");
				UsableObject val = obj.GetComponent<UsableObject>();
				if ((Object)(object)val == (Object)null)
				{
					val = obj.AddComponent<UsableObject>();
				}
				ApplyScrapeaterInteractionTemplate(obj, val);
				val.didLangString = true;
				val.toggleString = (string.IsNullOrWhiteSpace(backgroundInteractionBinding.ToggleString) ? "Use" : backgroundInteractionBinding.ToggleString);
				val.rangeMultiplier = backgroundInteractionBinding.RangeMultiplier;
				EnsureBuildingEntity(obj, definition, backgroundInteractionBinding);
				if ((Object)(object)obj.GetComponent<BackgroundObjectUseRelay>() == (Object)null)
				{
					obj.AddComponent<BackgroundObjectUseRelay>();
				}
				EnsureInteractionCollider(obj);
				EnsureInteractionLayer(obj);
			}
		}

		private static void EnsureInteractionCollider(GameObject obj)
		{
			//IL_0048: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)obj == (Object)null || BoxCollider2DType == null || (Object)(object)obj.GetComponent(BoxCollider2DType) != (Object)null)
			{
				return;
			}
			Component val = obj.AddComponent(BoxCollider2DType);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			SpriteRenderer component = obj.GetComponent<SpriteRenderer>();
			Vector2 val2 = Vector2.one;
			if ((Object)(object)component != (Object)null && (Object)(object)component.sprite != (Object)null)
			{
				Bounds bounds = component.sprite.bounds;
				Vector2 val3 = Vector2.op_Implicit(((Bounds)(ref bounds)).size);
				if (val3.x > 0f && val3.y > 0f)
				{
					val2 = val3;
				}
			}
			PropertyInfo property = BoxCollider2DType.GetProperty("size", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null && property.CanWrite && property.PropertyType == typeof(Vector2))
			{
				property.SetValue(val, val2, null);
			}
			PropertyInfo property2 = BoxCollider2DType.GetProperty("isTrigger", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property2 != null && property2.CanWrite && property2.PropertyType == typeof(bool))
			{
				property2.SetValue(val, false, null);
			}
		}

		private static void EnsureInteractionLayer(GameObject obj)
		{
			if (!((Object)(object)obj == (Object)null))
			{
				int num = LayerMask.NameToLayer("Descriptor");
				if (num >= 0)
				{
					obj.layer = num;
				}
			}
		}

		private static void EnsureBuildingEntity(GameObject obj, BackgroundObjectDefinition definition, BackgroundInteractionBinding binding)
		{
			//IL_00f3: 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_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)obj == (Object)null || definition == null || (Object)(object)binding == (Object)null)
			{
				return;
			}
			BuildingEntity val = obj.GetComponent<BuildingEntity>();
			if ((Object)(object)val == (Object)null)
			{
				val = obj.AddComponent<BuildingEntity>();
			}
			val.id = (string.Equals(definition.Id, "podbutton", StringComparison.OrdinalIgnoreCase) ? "lifepodbuttonheat" : definition.Id);
			val.fullName = binding.ResolvedTooltipName;
			val.description = binding.TooltipDesc ?? string.Empty;
			val.skipDescriptionSet = true;
			val.requireGround = false;
			NormalizeBackgroundBuildingDrops(val);
			if (val.health < 1f)
			{
				val.health = 100f;
			}
			if (string.Equals(definition.Id, "podbutton", StringComparison.OrdinalIgnoreCase))
			{
				val.cantHit = true;
				val.health = 100f;
				if ((Object)(object)obj.GetComponent<PodButtonDestroyOnZeroHealth>() == (Object)null)
				{
					obj.AddComponent<PodButtonDestroyOnZeroHealth>();
				}
			}
			if ((Object)(object)WorldGeneration.world != (Object)null)
			{
				val.blockPlacedOn = WorldGeneration.world.WorldToBlockPos(Vector2.op_Implicit(obj.transform.position + Vector3.down * 0.5f));
			}
			BackgroundBuildingNameOverride backgroundBuildingNameOverride = obj.GetComponent<BackgroundBuildingNameOverride>();
			if ((Object)(object)backgroundBuildingNameOverride == (Object)null)
			{
				backgroundBuildingNameOverride = obj.AddComponent<BackgroundBuildingNameOverride>();
			}
			backgroundBuildingNameOverride.FullName = binding.ResolvedTooltipName;
			backgroundBuildingNameOverride.Description = binding.TooltipDesc ?? string.Empty;
		}

		private static void NormalizeBackgroundBuildingDrops(BuildingEntity building)
		{
			if (!((Object)(object)building == (Object)null))
			{
				building.itemsDropOnDestroy = (ItemDrop[])(((object)building.itemsDropOnDestroy) ?? ((object)new ItemDrop[0]));
				building.alwaysDrop = (ItemDrop[])(((object)building.alwaysDrop) ?? ((object)new ItemDrop[0]));
				building.itemCategoriesToAdd = building.itemCategoriesToAdd ?? new string[0];
				if (building.itemCategoriesToAdd.Length == 0)
				{
					building.guaranteedDropAmount = 0;
				}
			}
		}

		private static void ApplyScrapeaterInteractionTemplate(GameObject obj, UsableObject usable)
		{
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)obj == (Object)null || (Object)(object)usable == (Object)null)
			{
				return;
			}
			EnsureScrapeaterTemplateLoaded();
			usable.rangeMultiplier = ((ScrapeaterTemplate.RangeMultiplier > 0f) ? ScrapeaterTemplate.RangeMultiplier : 1f);
			if (!string.IsNullOrWhiteSpace(ScrapeaterTemplate.ToggleString))
			{
				usable.toggleString = ScrapeaterTemplate.ToggleString;
			}
			if ((Object)(object)obj == (Object)null || BoxCollider2DType == null)
			{
				return;
			}
			Component val = obj.GetComponent(BoxCollider2DType);
			if ((Object)(object)val == (Object)null)
			{
				val = obj.AddComponent(BoxCollider2DType);
			}
			if (!((Object)(object)val == (Object)null))
			{
				PropertyInfo property = BoxCollider2DType.GetProperty("size", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.CanWrite && property.PropertyType == typeof(Vector2))
				{
					property.SetValue(val, ScrapeaterTemplate.ColliderSize, null);
				}
				PropertyInfo property2 = BoxCollider2DType.GetProperty("offset", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property2 != null && property2.CanWrite && property2.PropertyType == typeof(Vector2))
				{
					property2.SetValue(val, ScrapeaterTemplate.ColliderOffset, null);
				}
				PropertyInfo property3 = BoxCollider2DType.GetProperty("isTrigger", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property3 != null && property3.CanWrite && property3.PropertyType == typeof(bool))
				{
					property3.SetValue(val, ScrapeaterTemplate.ColliderIsTrigger, null);
				}
			}
		}

		private static void EnsureScrapeaterTemplateLoaded()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: 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_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			if (ScrapeaterTemplate.Initialized)
			{
				return;
			}
			ScrapeaterTemplate.Initialized = true;
			GameObject val = null;
			try
			{
				val = Utils.Create("scrapeater", Vector2.zero, 0f);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				UsableObject val2 = val.GetComponent<UsableObject>() ?? val.GetComponentInChildren<UsableObject>(true);
				if ((Object)(object)val2 != (Object)null)
				{
					if (!string.IsNullOrWhiteSpace(val2.toggleString))
					{
						ScrapeaterTemplate.ToggleString = val2.toggleString;
					}
					if (val2.rangeMultiplier > 0f)
					{
						ScrapeaterTemplate.RangeMultiplier = val2.rangeMultiplier;
					}
				}
				if (!(BoxCollider2DType != null))
				{
					return;
				}
				Component val3 = val.GetComponent(BoxCollider2DType) ?? val.GetComponentInChildren(BoxCollider2DType, true);
				if ((Object)(object)val3 != (Object)null)
				{
					PropertyInfo property = BoxCollider2DType.GetProperty("size", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.CanRead && property.PropertyType == typeof(Vector2) && property.GetValue(val3, null) is Vector2 val4 && val4.x > 0f && val4.y > 0f)
					{
						ScrapeaterTemplate.ColliderSize = val4;
					}
					PropertyInfo property2 = BoxCollider2DType.GetProperty("offset", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property2 != null && property2.CanRead && property2.PropertyType == typeof(Vector2) && property2.GetValue(val3, null) is Vector2 colliderOffset)
					{
						ScrapeaterTemplate.ColliderOffset = colliderOffset;
					}
					PropertyInfo property3 = BoxCollider2DType.GetProperty("isTrigger", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property3 != null && property3.CanRead && property3.PropertyType == typeof(bool) && property3.GetValue(val3, null) is bool colliderIsTrigger)
					{
						ScrapeaterTemplate.ColliderIsTrigger = colliderIsTrigger;
					}
				}
			}
			catch
			{
			}
			finally
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		private static void ApplyTriggerDefaults(Dictionary<string, string> merged, BackgroundObjectTriggerDto trigger)
		{
			if (merged != null && trigger != null)
			{
				if (!string.IsNullOrWhiteSpace(trigger.Id))
				{
					AddIfMissing(merged, "id", trigger.Id);
				}
				AddIfMissing(merged, "activateOnce", trigger.ActivateOnce ? "true" : "false");
			}
		}

		private static void AddIfMissing(Dictionary<string, string> map, string key, string value)
		{
			if (map != null && !string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(value) && !map.ContainsKey(key))
			{
				map[key] = value.Trim();
			}
		}

		private static string ReadStringProperty(Dictionary<string, string> map, string key, string fallback)
		{
			if (map != null && map.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value))
			{
				return value.Trim();
			}
			return fallback;
		}

		private static bool ReadBoolProperty(Dictionary<string, string> map, bool fallback, params string[] keys)
		{
			if (map == null || keys == null || keys.Length == 0)
			{
				return fallback;
			}
			for (int i = 0; i < keys.Length; i++)
			{
				if (map.TryGetValue(keys[i], out var value) && !string.IsNullOrWhiteSpace(value))
				{
					switch (value.Trim().ToLowerInvariant())
					{
					case "1":
					case "true":
					case "yes":
					case "on":
						return true;
					case "0":
					case "false":
					case "no":
					case "off":
						return false;
					}
				}
			}
			return fallback;
		}

		private static float ReadFloatProperty(Dictionary<string, string> map, string key, float fallback, float min, float max)
		{
			if (map != null && map.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) && float.TryParse(value.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return Mathf.Clamp(result, min, max);
			}
			return Mathf.Clamp(fallback, min, max);
		}

		private static bool TryGetSprite(BackgroundObjectDefinition definition, out Sprite sprite)
		{
			sprite = null;
			if (definition == null || string.IsNullOrWhiteSpace(definition.Id))
			{
				return false;
			}
			if (SpriteCache.TryGetValue(definition.Id, out var value) && (Object)(object)value != (Object)null)
			{
				sprite = value;
				return true;
			}
			if (TryLoadSpriteFromDisk(definition, out sprite) || TryLoadSpriteFromEmbedded(definition, out sprite))
			{
				SpriteCache[definition.Id] = sprite;
				return true;
			}
			return false;
		}

		private static bool TryLoadSpriteFromDisk(BackgroundObjectDefinition definition, out Sprite sprite)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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)
			sprite = null;
			string text = ResolveAssetPath(definition.SpritePath);
			if (string.IsNullOrWhiteSpace(text) || !File.Exists(text))
			{
				return false;
			}
			byte[] array = File.ReadAllBytes(text);
			if (array == null || array.Length == 0)
			{
				return false;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)5, false)
			{
				filterMode = (FilterMode)0,
				name = "bgobj_tex_" + definition.Id
			};
			if (!TryLoadImageIntoTexture(val, array))
			{
				Object.Destroy((Object)(object)val);
				return false;
			}
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor((float)((Texture)val).width * definition.PivotX, (float)((Texture)val).height * definition.PivotY);
			sprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2((((Texture)val).width <= 0) ? 0.5f : (val2.x / (float)((Texture)val).width), (((Texture)val).height <= 0) ? 0.5f : (val2.y / (float)((Texture)val).height)), Mathf.Max(1f, definition.PixelsPerUnit));
			((Object)sprite).name = "bgobj_sprite_" + definition.Id;
			return true;
		}

		private static bool TryLoadSpriteFromEmbedded(BackgroundObjectDefinition definition, out Sprite sprite)
		{
			//IL_0092: 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)
			sprite = null;
			if (definition == null)
			{
				return false;
			}
			foreach (string item in BuildEmbeddedCandidateNames(definition.SpritePath, definition.Id))
			{
				Sprite val = EmbeddedSpriteLoader.TryLoadEmbeddedSprite(item, Mathf.Max(1f, definition.PixelsPerUnit), (FilterMode)0);
				if (!((Object)(object)val == (Object)null))
				{
					if (!Mathf.Approximately(definition.PivotX, 0.5f) || !Mathf.Approximately(definition.PivotY, 0.5f))
					{
						Texture2D texture = val.texture;
						sprite = Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(definition.PivotX, definition.PivotY), Mathf.Max(1f, definition.PixelsPerUnit));
						Object.Destroy((Object)(object)val);
					}
					else
					{
						sprite = val;
					}
					((Object)sprite).name = "bgobj_sprite_" + definition.Id;
					return true;
				}
			}
			return false;
		}

		private static IEnumerable<string> BuildEmbeddedCandidateNames(string spritePath, string fallbackId)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			if (!string.IsNullOrWhiteSpace(spritePath))
			{
				string fileName = Path.GetFileName(spritePath.Trim().Replace('\\', '/'));
				if (!string.IsNullOrWhiteSpace(fileName))
				{
					hashSet.Add(fileName);
					if (!Path.HasExtension(fileName))
					{
						hashSet.Add(fileName + ".png");
					}
				}
			}
			if (!string.IsNullOrWhiteSpace(fallbackId))
			{
				hashSet.Add(fallbackId + ".png");
				hashSet.Add(fallbackId);
			}
			return hashSet;
		}

		private static void TryAddMaskColliders(BackgroundObjectDefinition definition, GameObject obj, Sprite sprite)
		{
			//IL_00d2: 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)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			if (definition == null || (Object)(object)obj == (Object)null || (Object)(object)sprite == (Object)null || string.IsNullOrWhiteSpace(definition.CollisionMaskPath) || BoxCollider2DType == null)
			{
				return;
			}
			string text = ResolveAssetPath(definition.CollisionMaskPath);
			if (string.IsNullOrWhiteSpace(text) || !File.Exists(text))
			{
				return;
			}
			Texture2D val = LoadMaskTexture(text, definition.Id);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				int minArea = Mathf.Max(1, definition.Collider?.MinRegionArea ?? 1);
				int num = Mathf.Max(0, definition.Collider?.MergePasses ?? 1);
				List<IntRect> list = BuildSolidRects(val, minArea);
				if (num > 0)
				{
					for (int i = 0; i < num; i++)
					{
						if (!MergeAdjacentRects(list))
						{
							break;
						}
					}
				}
				float ppu = Mathf.Max(1f, definition.PixelsPerUnit);
				Vector2 pivot = sprite.pivot;
				for (int j = 0; j < list.Count; j++)
				{
					IntRect rect = list[j];
					AddBoxCollider(obj, rect, pivot, ppu);
				}
			}
			finally
			{
				Object.Destroy((Object)(object)val);
			}
		}

		private static Texture2D LoadMaskTexture(string fullPath, string id)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0032: Expected O, but got Unknown
			byte[] array = File.ReadAllBytes(fullPath);
			if (array == null || array.Length == 0)
			{
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)5, false)
			{
				filterMode = (FilterMode)0,
				name = "bgobj_mask_" + id
			};
			if (!TryLoadImageIntoTexture(val, array))
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			return val;
		}

		private static List<IntRect> BuildSolidRects(Texture2D maskTexture, int minArea)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_005f: 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)
			int width = ((Texture)maskTexture).width;
			int height = ((Texture)maskTexture).height;
			bool[,] array = new bool[width, height];
			bool[,] array2 = new bool[width, height];
			Color32[] pixels = maskTexture.GetPixels32();
			for (int i = 0; i < height; i++)
			{
				int num = i * width;
				for (int j = 0; j < width; j++)
				{
					Color32 val = pixels[num + j];
					array[j, i] = val.a > 32 && (val.r > 32 || val.g > 32 || val.b > 32);
				}
			}
			List<IntRect> list = new List<IntRect>();
			for (int k = 0; k < height; k++)
			{
				for (int l = 0; l < width; l++)
				{
					if (!array[l, k] || array2[l, k])
					{
						continue;
					}
					int m;
					for (m = 0; l + m < width && array[l + m, k] && !array2[l + m, k]; m++)
					{
					}
					int num2 = 1;
					bool flag = true;
					while (flag && k + num2 < height)
					{
						for (int n = l; n < l + m; n++)
						{
							if (!array[n, k + num2] || array2[n, k + num2])
							{
								flag = false;
								break;
							}
						}
						if (flag)
						{
							num2++;
						}
					}
					for (int num3 = k; num3 < k + num2; num3++)
					{
						for (int num4 = l; num4 < l + m; num4++)
						{
							array2[num4, num3] = true;
						}
					}
					if (m * num2 >= minArea)
					{
						list.Add(new IntRect
						{
							X = l,
							Y = k,
							W = m,
							H = num2
						});
					}
				}
			}
			return list;
		}

		private static bool MergeAdjacentRects(List<IntRect> rects)
		{
			if (rects == null || rects.Count < 2)
			{
				return false;
			}
			for (int i = 0; i < rects.Count; i++)
			{
				IntRect intRect = rects[i];
				for (int j = i + 1; j < rects.Count; j++)
				{
					IntRect intRect2 = rects[j];
					if (intRect.Y == intRect2.Y && intRect.H == intRect2.H && intRect.X + intRect.W == intRect2.X)
					{
						rects[i] = new IntRect
						{
							X = intRect.X,
							Y = intRect.Y,
							W = intRect.W + intRect2.W,
							H = intRect.H
						};
						rects.RemoveAt(j);
						return true;
					}
					if (intRect.X == intRect2.X && intRect.W == intRect2.W && intRect.Y + intRect.H == intRect2.Y)
					{
						rects[i] = new IntRect
						{
							X = intRect.X,
							Y = intRect.Y,
							W = intRect.W,
							H = intRect.H + intRect2.H
						};
						rects.RemoveAt(j);
						return true;
					}
					if (intRect2.Y == intRect.Y && intRect2.H == intRect.H && intRect2.X + intRect2.W == intRect.X)
					{
						rects[i] = new IntRect
						{
							X = intRect2.X,
							Y = intRect2.Y,
							W = intRect2.W + intRect.W,
							H = intRect2.H
						};
						rects.RemoveAt(j);
						return true;
					}
					if (intRect2.X == intRect.X && intRect2.W == intRect.W && intRect2.Y + intRect2.H == intRect.Y)
					{
						rects[i] = new IntRect
						{
							X = intRect2.X,
							Y = intRect2.Y,
							W = intRect2.W,
							H = intRect2.H + intRect.H
						};
						rects.RemoveAt(j);
						return true;
					}
				}
			}
			return false;
		}

		private static void AddBoxCollider(GameObject obj, IntRect rect, Vector2 pivotPx, float ppu)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)obj == (Object)null || BoxCollider2DType == null || rect.W <= 0 || rect.H <= 0)
			{
				return;
			}
			Component val = obj.AddComponent(BoxCollider2DType);
			if (!((Object)(object)val == (Object)null))
			{
				float num = (float)rect.X + (float)rect.W * 0.5f;
				float num2 = (float)rect.Y + (float)rect.H * 0.5f;
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor((float)rect.W / ppu, (float)rect.H / ppu);
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor((num - pivotPx.x) / ppu, (num2 - pivotPx.y) / ppu);
				PropertyInfo property = BoxCollider2DType.GetProperty("size", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				PropertyInfo property2 = BoxCollider2DType.GetProperty("offset", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null && property.CanWrite && property.PropertyType == typeof(Vector2))
				{
					property.SetValue(val, val2, null);
				}
				if (property2 != null && property2.CanWrite && property2.PropertyType == typeof(Vector2))
				{
					property2.SetValue(val, val3, null);
				}
			}
		}

		private static string ResolveAssetPath(string relativePath)
		{
			if (string.IsNullOrWhiteSpace(relativePath))
			{
				return string.Empty;
			}
			string backgroundRootPath = BackgroundObjectRegistry.BackgroundRootPath;
			if (string.IsNullOrWhiteSpace(backgroundRootPath))
			{
				return string.Empty;
			}
			string text = relativePath.Trim().Replace('\\', '/');
			string text2 = Path.Combine(backgroundRootPath, text.Replace('/', Path.DirectorySeparatorChar));
			if (File.Exists(text2))
			{
				return text2;
			}
			if (!Path.HasExtension(text2))
			{
				string text3 = text2 + ".png";
				if (File.Exists(text3))
				{
					return text3;
				}
			}
			return text2;
		}

		private static bool TryLoadImageIntoTexture(Texture2D texture, byte[] bytes)
		{
			if ((Object)(object)texture == (Object)null || bytes == null || bytes.Length == 0)
			{
				return false;
			}
			try
			{
				Type type = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule");
				if (type == null)
				{
					return false;
				}
				MethodInfo method = type.GetMethod("LoadImage", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
				{
					typeof(Texture2D),
					typeof(byte[]),
					typeof(bool)
				}, null);
				if (method != null)
				{
					object obj = method.Invoke(null, new object[3] { texture, bytes, false });
					bool flag = default(bool);
					int num;
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
					return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				}
				method = type.GetMethod("LoadImage", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
				{
					typeof(Texture2D),
					typeof(byte[])
				}, null);
				if (method != null)
				{
					object obj2 = method.Invoke(null, new object[2] { texture, bytes });
					bool flag2 = default(bool);
					int num2;
					if (obj2 is bool)
					{
						flag2 = (bool)obj2;
						num2 = 1;
					}
					else
					{
						num2 = 0;
					}
					return (byte)((uint)num2 & (flag2 ? 1u : 0u)) != 0;
				}
			}
			catch
			{
				return false;
			}
			return false;
		}
	}
	internal class CommunityStructureEntry
	{
		public string Id;

		public string Name;

		public string Author;

		public string Code;

		public DateTime? CreatedAtUtc;

		public DateTime? UpdatedAtUtc;

		public int Score;
	}
	[DataContract]
	internal class CommunityStructureCatalogCache
	{
		[DataMember]
		public string catalogUrl { get; set; }

		[DataMember]
		public string nextPageToken { get; set; }

		[DataMember]
		public string savedAtUtc { get; set; }

		[DataMember]
		public List<CommunityStructureCatalogCacheEntry> entries { get; set; }
	}
	[DataContract]
	internal class CommunityStructureCatalogCacheEntry
	{
		[DataMember]
		public string id { get; set; }

		[DataMember]
		public string name { get; set; }

		[DataMember]
		public string author { get; set; }

		[DataMember]
		public string code { get; set; }

		[DataMember]
		public string createdAtUtc { get; set; }

		[DataMember]
		public string updatedAtUtc { get; set; }

		[DataMember]
		public int score { get; set; }
	}
	[DataContract]
	internal class FirestoreApiResponse
	{
		[DataMember]
		public FirestoreApiError error { get; set; }

		[DataMember]
		public List<FirestoreDocument> documents { get; set; }

		[DataMember]
		public FirestoreDocument document { get; set; }

		[DataMember]
		public string name { get; set; }

		[DataMember]
		public string createTime { get; set; }

		[DataMember]
		public Dictionary<string, FirestoreFieldValue> fields { get; set; }

		[DataMember]
		public string nextPageToken { get; set; }
	}
	[DataContract]
	internal class FirestoreApiError
	{
		[DataMember]
		public string message { get; set; }
	}
	[DataContract]
	internal class FirestoreDocument
	{
		[DataMember]
		public string name { get; set; }

		[DataMember]
		public string createTime { get; set; }

		[DataMember]
		public Dictionary<string, FirestoreFieldValue> fields { get; set; }
	}
	[DataContract]
	internal class FirestoreFieldValue
	{
		[DataMember]
		public string stringValue { get; set; }

		[DataMember]
		public string timestampValue { get; set; }

		[DataMember]
		public string integerValue { get; set; }
	}
	internal static class CommunityStructureBrowser
	{
		private class RemoteSearchAttempt
		{
			public string Field;

			public string Prefix;
		}

		private class BrowserRunner : MonoBehaviour
		{
		}

		private const int CatalogPageSize = 30;

		private const int MaxCachedCatalogEntries = 600;

		private const int RemoteSearchMaxDocuments = 10;

		private const int RemoteSearchMaxAttempts = 3;

		private const double CatalogDiskCacheMaxAgeHours = 24.0;

		private const string CatalogUrlPlayerPrefKey = "MoreStructures_RemoteCatalogUrl";

		private const string DefaultCatalogUrl = "https://firestore.googleapis.com/v1/projects/cu-structure-editor/databases/(default)/documents/published_levels?pageSize=30&orderBy=score%20desc&key=AIzaSyBPuYD1WX-h5naDAfoiUnScowieUJhHHUM";

		private const string DocumentUrlPrefix = "https://firestore.googleapis.com/v1/projects/cu-structure-editor/databases/(default)/documents/published_levels/";

		private const string ApiKeyQuery = "?key=AIzaSyBPuYD1WX-h5naDAfoiUnScowieUJhHHUM";

		private static ManualLogSource Logger;

		private static BrowserRunner Runner;

		private static bool IsCatalogRequestInFlight;

		private static bool IsDownloadRequestInFlight;

		private static bool IsDisableRequestInFlight;

		private static bool IsRemoteSearchRequestInFlight;

		private static int CatalogRequestGeneration;

		private static int DownloadRequestGeneration;

		private static int RemoteSearchRequestGeneration;

		private static UnityWebRequest ActiveCatalogRequest;

		private static UnityWebRequest ActiveDownloadRequest;

		private static UnityWebRequest ActiveRemoteSearchRequest;

		private static string LastCatalogStatus = "Catalog has not been loaded yet.";

		private static string NextCatalogPageToken = string.Empty;

		private static readonly List<CommunityStructureEntry> CachedEntriesInternal = new List<CommunityStructureEntry>();

		private static readonly List<CommunityStructureEntry> InstalledEntriesInternal = new List<CommunityStructureEntry>();

		private static readonly HashSet<string> InstalledRemoteIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> InstalledDefinitionNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static bool InstalledEntriesDirty = true;

		public static bool IsRefreshingCatalog => IsCatalogRequestInFlight;

		public static bool IsDownloadingStructure => IsDownloadRequestInFlight;

		public static bool IsDisablingStructure => IsDisableRequestInFlight;

		public static bool IsSearchingRemoteCatalog => IsRemoteSearchRequestInFlight;

		public static bool IsMutatingStructure
		{
			get
			{
				if (!IsDownloadRequestInFlight)
				{
					return IsDisableRequestInFlight;
				}
				return true;
			}
		}

		public static bool HasMoreCatalogEntries => !string.IsNullOrWhiteSpace(NextCatalogPageToken);

		public static int CachedCount => CachedEntriesInternal.Count;

		public static string CatalogStatus => LastCatalogStatus;

		public static void Initialize(ManualLogSource logger)
		{
			Logger = logger;
			TryLoadCatalogCache();
		}

		public static void SuspendRequests()
		{
			CatalogRequestGeneration++;
			IsCatalogRequestInFlight = false;
			if (ActiveCatalogRequest != null)
			{
				ActiveCatalogRequest.Abort();
				ActiveCatalogRequest = null;
			}
			DownloadRequestGeneration++;
			IsDownloadRequestInFlight = false;
			RemoteSearchRequestGeneration++;
			IsRemoteSearchRequestInFlight = false;
			if (ActiveRemoteSearchRequest != null)
			{
				ActiveRemoteSearchRequest.Abort();
				ActiveRemoteSearchRequest = null;
			}
			if (ActiveDownloadRequest != null)
			{
				ActiveDownloadRequest.Abort();
				ActiveDownloadRequest = null;
			}
			if ((Object)(object)Runner != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)Runner).gameObject);
				Runner = null;
			}
		}

		public static void InvalidateInstalledEntries()
		{
			InstalledEntriesDirty = true;
		}

		public static string GetCatalogUrl()
		{
			string text = PlayerPrefs.GetString("MoreStructures_RemoteCatalogUrl", string.Empty);
			if (!string.IsNullOrWhiteSpace(text))
			{
				return text.Trim();
			}
			return "https://firestore.googleapis.com/v1/projects/cu-structure-editor/databases/(default)/documents/published_levels?pageSize=30&orderBy=score%20desc&key=AIzaSyBPuYD1WX-h5naDAfoiUnScowieUJhHHUM";
		}

		public static bool TrySetCatalogUrl(string url, out string message)
		{
			if (string.IsNullOrWhiteSpace(url))
			{
				PlayerPrefs.DeleteKey("MoreStructures_RemoteCatalogUrl");
				PlayerPrefs.Save();
				CachedEntriesInternal.Clear();
				NextCatalogPageToken = string.Empty;
				message = "Remote catalog source reset to default (Firebase).";
				return true;
			}
			string text = url.Trim();
			if (!Uri.TryCreate(text, UriKind.Absolute, out Uri result) || (result.Scheme != Uri.UriSchemeHttp && result.Scheme != Uri.UriSchemeHttps))
			{
				message = "Invalid URL. Use a full http/https URL.";
				return false;
			}
			PlayerPrefs.SetString("MoreStructures_RemoteCatalogUrl", text);
			PlayerPrefs.Save();
			CachedEntriesInternal.Clear();
			NextCatalogPageToken = string.Empty;
			message = "Remote catalog source updated to: " + text;
			return true;
		}

		public static void RefreshCatalog(Action<bool, string> onComplete)
		{
			EnsureRunner();
			if (IsCatalogRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "A catalog refresh is already running.");
			}
			else
			{
				((MonoBehaviour)Runner).StartCoroutine(RefreshCatalogCoroutine(onComplete));
			}
		}

		public static void LoadNextCatalogPage(Action<bool, string> onComplete)
		{
			EnsureRunner();
			if (IsCatalogRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "A catalog request is already running.");
			}
			else if (!HasMoreCatalogEntries)
			{
				onComplete?.Invoke(arg1: false, "All loaded catalog entries are already shown.");
			}
			else
			{
				((MonoBehaviour)Runner).StartCoroutine(LoadCatalogPageCoroutine(resetCatalog: false, onComplete));
			}
		}

		public static void SearchRemoteCatalog(string query, Action<bool, string> onComplete)
		{
			EnsureRunner();
			if (IsRemoteSearchRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "A catalog search is already running.");
				return;
			}
			if (!TryBuildRunQueryRequest(GetCatalogUrl(), out var endpoint, out var collectionId))
			{
				onComplete?.Invoke(arg1: false, "Catalog search needs the default Firebase source.");
				return;
			}
			List<RemoteSearchAttempt> list = BuildRemoteSearchAttempts(query);
			if (list.Count == 0)
			{
				onComplete?.Invoke(arg1: false, "Nothing to search the catalog for.");
				return;
			}
			int requestGeneration = ++RemoteSearchRequestGeneration;
			((MonoBehaviour)Runner).StartCoroutine(RemoteSearchCoroutine(list, endpoint, collectionId, requestGeneration, onComplete));
		}

		public static List<CommunityStructureEntry> BrowseCached(int count)
		{
			EnsureInstalledEntriesCurrent();
			List<CommunityStructureEntry> list = MergeInstalledEntriesFirst();
			int count2 = Math.Max(1, Math.Min(list.Count, count));
			return list.Take(count2).ToList();
		}

		public static List<CommunityStructureEntry> SearchCached(string query, int count)
		{
			string text = (query ?? string.Empty).Trim();
			if (text.Length == 0)
			{
				return new List<CommunityStructureEntry>();
			}
			EnsureInstalledEntriesCurrent();
			List<CommunityStructureEntry> list = MergeInstalledEntriesFirst();
			int count2 = list.Count;
			return Enumerable.Take(count: Math.Max(1, Math.Min(count2, count)), source: CommunityStructureCatalogFilter.Apply(list, text, (CommunityStructureEntry entry) => IsEnabled(entry.Id))).ToList();
		}

		public static List<string> GetCachedIds(int count)
		{
			int count2 = Math.Max(1, Math.Min(200, count));
			return (from entry in CachedEntriesInternal
				select entry.Id into id
				where !string.IsNullOrWhiteSpace(id)
				select id).Take(count2).ToList();
		}

		public static void DownloadAndInstall(string structureId, Action<bool, string> onComplete)
		{
			EnsureRunner();
			string text = (structureId ?? string.Empty).Trim();
			if (text.Length == 0)
			{
				onComplete?.Invoke(arg1: false, "Structure ID cannot be empty.");
			}
			else if (IsDownloadRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "Another structure download/install is already running.");
			}
			else if (IsDisableRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "A structure disable operation is already running.");
			}
			else
			{
				((MonoBehaviour)Runner).StartCoroutine(DownloadAndInstallCoroutine(text, onComplete));
			}
		}

		public static bool IsInstalled(string structureId)
		{
			string text = (structureId ?? string.Empty).Trim();
			if (text.Length == 0)
			{
				return false;
			}
			EnsureInstalledEntriesCurrent();
			return InstalledRemoteIds.Contains(text);
		}

		public static bool IsEnabled(string structureId, string structureDefinitionName = null)
		{
			if (IsInstalled(structureId))
			{
				return true;
			}
			string text = (structureDefinitionName ?? string.Empty).Trim();
			if (text.Length > 0 && (InstalledDefinitionNames.Contains(text) || WorldGenerationPatcher.StructureDefinitions.ContainsKey(text)))
			{
				return true;
			}
			return false;
		}

		public static void DisableInstalled(string structureId, Action<bool, string> onComplete)
		{
			DisableInstalled(structureId, null, onComplete);
		}

		public static void DisableInstalled(string structureId, string structureDefinitionName, Action<bool, string> onComplete)
		{
			string text = (structureId ?? string.Empty).Trim();
			if (text.Length == 0)
			{
				onComplete?.Invoke(arg1: false, "Structure ID cannot be empty.");
				return;
			}
			if (IsDownloadRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "A structure download/install is already running.");
				return;
			}
			if (IsDisableRequestInFlight)
			{
				onComplete?.Invoke(arg1: false, "Another structure disable operation is already running.");
				return;
			}
			IsDisableRequestInFlight = true;
			try
			{
				HashSet<string> hashSet = new HashSet<string>(FindInstalledStructureFiles(text), StringComparer.OrdinalIgnoreCase);
				if (!string.IsNullOrWhiteSpace(structureDefinitionName))
				{
					foreach (string item in FindFilesByDefinitionName(structureDefinitionName.Trim()))
					{
						hashSet.Add(item);
					}
				}
				if (hashSet.Count == 0)
				{
					IsDisableRequestInFlight = false;
					onComplete?.Invoke(arg1: false, "No local downloaded files were found for '" + text + "'.");
					return;
				}
				foreach (string item2 in hashSet)
				{
					if (File.Exists(item2))
					{
						File.Delete(item2);
					}
				}
				int num = ConsoleScriptPatcher.ReloadStructuresAndRefreshCommands();
				InstalledEntriesDirty = true;
				RefreshInstalledEntries();
				IsDisableRequestInFlight = false;
				onComplete?.Invoke(arg1: true, $"Disabled '{text}' by removing {hashSet.Count} file(s). Loaded structures: {num}.");
			}
			catch (Exception ex)
			{
				IsDisableRequestInFlight = false;
				onComplete?.Invoke(arg1: false, "Failed disabling '" + text + "': " + ex.Message);
			}
		}

		private static List<string> FindFilesByDefinitionName(string definitionName)
		{
			string path = ResolveStructureOutputDirectory();
			if (!Directory.Exists(path) || string.IsNullOrWhiteSpace(definitionName))
			{
				return new List<string>();
			}
			return (from filePath in Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)
				where filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || filePath.EndsWith(".ms2.json", StringComparison.OrdinalIgnoreCase)
				where FileDeclaresDefinitionName(filePath, definitionName)
				select filePath).ToList();
		}

		private static bool FileDeclaresDefinitionName(string filePath, string definitionName)
		{
			try
			{
				string code = File.ReadAllText(filePath);
				return string.Equals(CommunityStructureMetadataParser.Parse(new CommunityStructureEntry
				{
					Id = ResolveRemoteIdFromInstalledFileName(filePath),
					Name = ResolveInstalledDisplayName(filePath),
					Author = "Installed",
					Code = code,
					CreatedAtUtc = File.GetLastWriteTimeUtc(filePath),
					Score = 0
				})?.DefinitionName?.Trim(), definitionName, StringComparison.OrdinalIgnoreCase);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("Failed reading structure file '" + Path.GetFileName(filePath) + "'. Oop. " + ex.Message));
				}
			}
			return false;
		}

		private static IEnumerator RefreshCatalogCoroutine(Action<bool, string> onComplete)
		{
			yield return LoadCatalogPageCoroutine(resetCatalog: true, onComplete);
		}

		private static IEnumerator LoadCatalogPageCoroutine(bool resetCatalog, Action<bool, string> onComplete)
		{
			int requestGeneration = ++CatalogRequestGeneration;
			IsCatalogRequestInFlight = true;
			if (resetCatalog)
			{
				NextCatalogPageToken = string.Empty;
			}
			string text = BuildCatalogPageUrl(resetCatalog ? null : NextCatalogPageToken);
			UnityWebRequest request = UnityWebRequest.Get(text);
			try
			{
				ActiveCatalogRequest = request;
				request.timeout = 20;
				request.SetRequestHeader("User-Agent", "MoreStructuresMod");
				yield return request.SendWebRequest();
				if (requestGeneration != CatalogRequestGeneration)
				{
					yield break;
				}
				if ((int)request.result != 1)
				{
					LastCatalogStatus = "Catalog refresh failed: " + request.error;
					ActiveCatalogRequest = null;
					IsCatalogRequestInFlight = false;
					onComplete?.Invoke(arg1: false, LastCatalogStatus);
					yield break;
				}
				if (!TryParseCatalogResponse(request.downloadHandler.text, out var entries, out var nextPageToken, out var error))
				{
					LastCatalogStatus = "Catalog parse failed: " + error;
					ActiveCatalogRequest = null;
					IsCatalogRequestInFlight = false;
					onComplete?.Invoke(arg1: false, LastCatalogStatus);
					yield break;
				}
				if (resetCatalog)
				{
					CachedEntriesInternal.Clear();
				}
				AddUniqueCachedEntries(entries);
				NextCatalogPageToken = nextPageToken ?? string.Empty;
				LastCatalogStatus = (HasMoreCatalogEntries ? $"Catalog loaded: {CachedEntriesInternal.Count} entries. Scroll down or search to load more." : $"Catalog loaded: {CachedEntriesInternal.Count} entries.");
				SaveCatalogCache();
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
			ActiveCatalogRequest = null;
			IsCatalogRequestInFlight = false;
			onComplete?.Invoke(arg1: true, LastCatalogStatus);
		}

		private static IEnumerator RemoteSearchCoroutine(List<RemoteSearchAttempt> attempts, string endpoint, string collectionId, int requestGeneration, Action<bool, string> onComplete)
		{
			IsRemoteSearchRequestInFlight = true;
			int i = 0;
			while (true)
			{
				if (i < attempts.Count)
				{
					if (requestGeneration != RemoteSearchRequestGeneration)
					{
						break;
					}
					string text = BuildPrefixSearchBody(collectionId, attempts[i].Field, attempts[i].Prefix);
					if (text != null)
					{
						byte[] bytes = Encoding.UTF8.GetBytes(text);
						UnityWebRequest request = new UnityWebRequest(endpoint, "POST");
						try
						{
							ActiveRemoteSearchRequest = request;
							request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes);
							request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
							request.SetRequestHeader("Content-Type", "application/json");
							request.timeout = 20;
							request.SetRequestHeader("User-Agent", "MoreStructuresMod");
							yield return request.SendWebRequest();
							if (requestGeneration != RemoteSearchRequestGeneration)
							{
								break;
							}
							if ((int)request.result != 1)
							{
								FinishRemoteSearch();
								onComplete?.Invoke(arg1: false, "Catalog search failed: " + request.error);
								break;
							}
							if (!TryParseRunQueryResponse(request.downloadHandler.text, out var entries, out var error))
							{
								FinishRemoteSearch();
								onComplete?.Invoke(arg1: false, "Catalog search parse failed: " + error);
								break;
							}
							if (entries.Count > 0)
							{
								AddUniqueCachedEntries(entries);
								SaveCatalogCache();
								FinishRemoteSearch();
								onComplete?.Invoke(arg1: true, $"Catalog search matched {entries.Count} structure(s).");
								break;
							}
						}
						finally
						{
							((IDisposable)request)?.Dispose();
						}
						ActiveRemoteSearchRequest = null;
					}
					i++;
					continue;
				}
				FinishRemoteSearch();
				onComplete?.Invoke(arg1: true, "Catalog search found no additional matches.");
				break;
			}
		}

		private static void FinishRemoteSearch()
		{
			ActiveRemoteSearchRequest = null;
			IsRemoteSearchRequestInFlight = false;
		}

		private static List<RemoteSearchAttempt> BuildRemoteSearchAttempts(string query)
		{
			List<RemoteSearchAttempt> list = new List<RemoteSearchAttempt>();
			if (!CommunityStructureCatalogFilter.TryGetRemoteSearchTerm(query, out var field, out var term, out var fieldWasExplicit))
			{
				return list;
			}
			list.Add(new RemoteSearchAttempt
			{
				Field = field,
				Prefix = term
			});
			if (!fieldWasExplicit && list.Count < 3)
			{
				list.Add(new RemoteSearchAttempt
				{
					Field = "author",
					Prefix = term
				});
			}
			string text = SwapLeadingLetterCase(term);
			if (!string.IsNullOrEmpty(text) && list.Count < 3)
			{
				list.Add(new RemoteSearchAttempt
				{
					Field = field,
					Prefix = text
				});
			}
			return list;
		}

		private static string SwapLeadingLetterCase(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return null;
			}
			for (int i = 0; i < value.Length; i++)
			{
				char c = value[i];
				if (char.IsLetter(c) && !char.IsSurrogate(c))
				{
					char c2 = (char.IsUpper(c) ? char.ToLowerInvariant(c) : char.ToUpperInvariant(c));
					if (c2 == c)
					{
						return null;
					}
					return value.Substring(0, i) + c2 + value.Substring(i + 1);
				}
			}
			return null;
		}

		private static bool TryParseRunQueryResponse(string text, out List<CommunityStructureEntry> entries, out string error)
		{
			entries = new List<CommunityStructureEntry>();
			error = null;
			try
			{
				foreach (string item in EnumerateJsonRootObjects(text))
				{
					FirestoreApiResponse firestoreApiResponse = DeserializeJson<FirestoreApiResponse>(item);
					if (firestoreApiResponse != null)
					{
						if (TryReadFirestoreError(firestoreApiResponse, out error))
						{
							entries.Clear();
							return false;
						}
						FirestoreDocument document = firestoreApiResponse.document;
						if (document != null && TryBuildEntryFromDocument(document, out var entry))
						{
							entries.Add(entry);
						}
					}
				}
				entries = (from communityStructureEntry in entries
					orderby communityStructureEntry.Score descending, communityStructureEntry.CreatedAtUtc ?? DateTime.MinValue descending
					select communityStructureEntry).ThenBy<CommunityStructureEntry, string>((CommunityStructureEntry communityStructureEntry) => communityStructureEntry.Name ?? string.Empty, StringComparer.OrdinalIgnoreCase).ToList();
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				return false;
			}
		}

		private static IEnumerable<string> EnumerateJsonRootObjects(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				yield break;
			}
			int depth = 0;
			int num = -1;
			bool inString = false;
			bool escaped = false;
			for (int i = 0; i < text.Length; i++)
			{
				char c = text[i];
				if (inString)
				{
					if (escaped)
					{
						escaped = false;
						continue;
					}
					switch (c)
					{
					case '\\':
						escaped = true;
						break;
					case '"':
						inString = false;
						break;
					}
					continue;
				}
				switch (c)
				{
				case '"':
					inString = true;
					break;
				case '{':
					if (depth == 0)
					{
						num = i;
					}
					depth++;
					break;
				case '}':
					depth--;
					if (depth == 0 && num >= 0)
					{
						yield return text.Substring(num, i - num + 1);
						num = -1;
					}
					else if (depth < 0)
					{
						yield break;
					}
					break;
				}
			}
		}

		private static string BuildPrefixSearchBody(string collectionId, string field, string prefix)
		{
			if (string.IsNullOrEmpty(prefix) || string.IsNullOrEmpty(collectionId) || (field != "name" && field != "author"))
			{
				return null;
			}
			string upperBound;
			string text = ((!TryGetPrefixUpperBound(prefix, out upperBound)) ? BuildFieldFilter(field, "EQUAL", prefix) : ("{\"compositeFilter\":{\"op\":\"AND\",\"filters\":[" + BuildFieldFilter(field, "GREATER_THAN_OR_EQUAL", prefix) + "," + BuildFieldFilter(field, "LESS_THAN", upperBound) + "]}}"));
			return "{\"structuredQuery\":{\"from\":{\"collectionId\":\"" + EscapeJsonString(collectionId) + "\"},\"where\":" + text + ",\"orderBy\":[{\"field\":{\"fieldPath\":\"" + field + "\"},\"direction\":\"ASCENDING\"}],\"limit\":" + 10.ToString(CultureInfo.InvariantCulture) + "}}";
		}

		private static string BuildFieldFilter(string field, string op, string value)
		{
			return "{\"fieldFilter\":{\"field\":{\"fieldPath\":\"" + field + "\"},\"op\":\"" + op + "\",\"value\":{\"stringValue\":\"" + EscapeJsonString(value) + "\"}}}";
		}

		private static bool TryGetPrefixUpperBound(string prefix, out string upperBound)
		{
			upperBound = null;
			if (string.IsNullOrEmpty(prefix))
			{
				return false;
			}
			char[] array = prefix.ToCharArray();
			int num = array.Length - 1;
			char c = array[num];
			if (char.IsSurrogate(c) || c == '\uffff')
			{
				return false;
			}
			char c2 = (char)(c + 1);
			if (char.IsSurrogate(c2))
			{
				return false;
			}
			array[num] = c2;
			upperBound = new string(array);
			return true;
		}

		private static string EscapeJsonString(string value)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = value ?? string.Empty;
			foreach (char c in text)
			{
				switch (c)
				{
				case '"':
					stringBuilder.Append("\\\"");
					continue;
				case '\\':
					stringBuilder.Append("\\\\");
					continue;
				case '\b':
					stringBuilder.Append("\\b");
					continue;
				case '\f':
					stringBuilder.Append("\\f");
					continue;
				case '\n':
					stringBuilder.Append("\\n");
					continue;
				case '\r':
					stringBuilder.Append("\\r");
					continue;
				case '\t':
					stringBuilder.Append("\\t");
					continue;
				}
				if (c < ' ')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4", CultureInfo.InvariantCulture));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		private static bool TryBuildRunQueryRequest(string catalogUrl, out string endpoint, out string collectionId)
		{
			endpoint = null;
			collectionId = null;
			catalogUrl = catalogUrl ?? string.Empty;
			int num = catalogUrl.IndexOf("/documents/", StringComparison.OrdinalIgnoreCase);
			if (num < 0)
			{
				return false;
			}
			int num2 = num + "/documents/".Length;
			int i;
			for (i = num2; i < catalogUrl.Length && catalogUrl[i] != '?' && catalogUrl[i] != '#'; i++)
			{
			}
			string text = catalogUrl.Substring(num2, i - num2).Trim(new char[1] { '/' });
			if (text.Length == 0 || text.IndexOf('/') >= 0)
			{
				return false;
			}
			string text2 = ReadQueryParameterValue(catalogUrl.Substring(i), "key");
			if (string.IsNullOrWhiteSpace(text2))
			{
				return false;
			}
			collectionId = text;
			endpoint = catalogUrl.Substring(0, num) + "/documents:runQuery?key=" + UnityWebRequest.EscapeURL(text2);
			return true;
		}

		private static string ReadQueryParameterValue(string query, string name)
		{
			if (string.IsNullOrWhiteSpace(query))
			{
				return string.Empty;
			}
			string[] array = query.TrimStart(new char[1] { '?' }).Split(new char[1] { '&' });
			foreach (string text in array)
			{
				int num = text.IndexOf('=');
				if (num > 0 && string.Equals(text.Substring(0, num), name, StringComparison.OrdinalIgnoreCase))
				{
					try
					{
						return Uri.UnescapeDataString(text.Substring(num + 1));
					}
					catch (Exception)
					{
						return text.Substring(num + 1);
					}
				}
			}
			return string.Empty;
		}

		public static void DownloadFromConsoleInput(string input, Action<bool, string> onComplete)
		{
			string trimmed = (input ?? string.Empty).Trim().Trim(new char[1] { '"' });
			if (trimmed.Length == 0)
			{
				onComplete?.Invoke(arg1: false, "Give a share link, structure ID, or structure name.");
				return;
			}
			if (TryExtractIdFromLink(trimmed, out var id))
			{
				DownloadAndInstall(id, onComplete);
				return;
			}
			if (TryFindCachedByName(trimmed, out var entry, out var ambiguity))
			{
				DownloadAndInstall(entry.Id, onComplete);
				return;
			}
			if (ambiguity != null)
			{
				onComplete?.Invoke(arg1: false, ambiguity);
				return;
			}
			DownloadAndInstall(trimmed, delegate(bool installed, string message)
			{
				if (installed)
				{
					onComplete?.Invoke(arg1: true, message);
				}
				else
				{
					SearchRemoteCatalog(trimmed, delegate(bool searched, string searchMessage)
					{
						if (TryFindCachedByName(trimmed, out var entry2, out var ambiguity2))
						{
							DownloadAndInstall(entry2.Id, onComplete);
						}
						else
						{
							onComplete?.Invoke(arg1: false, ambiguity2 ?? (searched ? ("No structure found with the ID or name '" + trimmed + "'.") : searchMessage));
						}
					});
				}
			});
		}

		private static bool TryExtractIdFromLink(string input, out string id)
		{
			id = null;
			if (!Uri.TryCreate(input, UriKind.Absolute, out Uri result) || (result.Scheme != Uri.UriSchemeHttp && result.Scheme != Uri.UriSchemeHttps))
			{
				return false;
			}
			string text = ReadQueryParameterValue(result.Query, "id");
			if (!string.IsNullOrWhiteSpace(text))
			{
				id = text.Trim();
				return true;
			}
			string[] array = result.AbsolutePath.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length - 1; i++)
			{
				if (array[i] == "s" || array[i] == "published_levels")
				{
					id = Uri.UnescapeDataString(array[i + 1]).Trim();
					return id.Length > 0;
				}
			}
			return false;
		}

		private static bool TryFindCachedByName(string name, out CommunityStructureEntry entry, out string ambiguity)
		{
			entry = null;
			ambiguity = null;
			List<CommunityStructureEntry> source = CachedEntriesInternal.Where((CommunityStructureEntry e) => e != null && !string.IsNullOrWhiteSpace(e.Id) && !string.IsNullOrWhiteSpace(e.Name)).ToList();
			List<CommunityStructureEntry> matches = source.Where((CommunityStructureEntry e) => string.Equals(e.Name.Trim(), name, StringComparison.OrdinalIgnoreCase)).ToList();
			if (matches.Count == 0)
			{
				matches = source.Where((CommunityStructureEntry e) => e.Name.Trim().StartsWith(name, StringComparison.OrdinalIgnoreCase)).ToList();
			}
			if (matches.Count == 1)
			{
				entry = matches[0];
				return true;
			}
			if (matches.Count > 1)
			{
				if (matches.All((CommunityStructureEntry e) => string.Equals(e.Name.Trim(), matches[0].Name.Trim(), StringComparison.OrdinalIgnoreCase)))
				{
					entry = matches.OrderByDescending((CommunityStructureEntry e) => e.Score).First();
					return true;
				}
				ambiguity = "'" + name + "' matches several structures: " + string.Join(", ", from e in matches.Take(6)
					select e.Name.Trim() + " (" + e.Id + ")") + ". Use the full name or ID.";
			}
			return false;
		}

		private static IEnumerator DownloadAndInstallCoroutine(string structureId, Action<bool, string> onComplete)
		{
			int requestGeneration = ++DownloadRequestGeneration;
			IsDownloadRequestInFlight = true;
			string text = BuildDocumentUrl(structureId);
			UnityWebRequest request = UnityWebRequest.Get(text);
			CommunityStructureEntry entry;
			try
			{
				ActiveDownloadRequest = request;
				request.timeout = 20;
				request.SetRequestHeader("User-Agent", "MoreStructuresMod");
				yield return request.SendWebRequest();
				if (requestGeneration != DownloadRequestGeneration)
				{
					yield break;
				}
				if ((int)request.result != 1)
				{
					ActiveDownloadRequest = null;
					IsDownloadRequestInFlight = false;
					onComplete?.Invoke(arg1: false, "Download failed for '" + structureId + "': " + request.error);
					yield break;
				}
				if (!TryParseSingleDocument(request.downloadHandler.text, out entry, out var error))
				{
					ActiveDownloadRequest = null;
					IsDownloadRequestInFlight = false;
					onComplete?.Invoke(arg1: false, "Could not parse structure '" + structureId + "': " + error);
					yield break;
				}
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
			ActiveDownloadRequest = null;
			if (entry == null || string.IsNullOrWhiteSpace(entry.Code))
			{
				IsDownloadRequestInFlight = false;
				onComplete?.Invoke(arg1: false, "Structure '" + structureId + "' has no code payload.");
				yield break;
			}
			AddUniqueCachedEntries(new List<CommunityStructureEntry> { entry });
			SaveCatalogCache();
			string text2 = ResolveStructureOutputDirectory();
			string extension = (LooksLikeJson(entry.Code) ? ".ms2.json" : ".txt");
			string text3 = BuildSafeFileName(entry, extension);
			string path = Path.Combine(text2, text3);
			try
			{
				Directory.CreateDirectory(text2);
				File.WriteAllText(path, NormalizeLineEndings(entry.Code));
				int num = ConsoleScriptPatcher.ReloadStructuresAndRefreshCommands();
				InstalledEntriesDirty = true;
				RefreshInstalledEntries();
				string arg = (string.IsNullOrWhiteSpace(entry.Name) ? structureId : entry.Name.Trim());
				ActiveDownloadRequest = null;
				IsDownloadRequestInFlight = false;
				onComplete?.Invoke(arg1: true, $"Installed '{arg}' as '{text3}'. Loaded structures: {num}.");
			}
			catch (Exception ex)
			{
				ActiveDownloadRequest = null;
				IsDownloadRequestInFlight = false;
				onComplete?.Invoke(arg1: false, "Failed writing '" + text3 + "': " + ex.Message);
			}
		}

		private static bool TryParseCatalogResponse(string json, out List<CommunityStructureEntry> entries, out string nextPageToken, out string error)
		{
			entries = new List<CommunityStructureEntry>();
			nextPageToken = string.Empty;
			error = null;
			try
			{
				FirestoreApiResponse firestoreApiResponse = DeserializeJson<FirestoreApiResponse>(json);
				if (firestoreApiResponse == null)
				{
					error = "Top-level JSON object missing.";
					return false;
				}
				if (TryReadFirestoreError(firestoreApiResponse, out var message))
				{
					error = message;
					return false;
				}
				List<FirestoreDocument> documents = firestoreApiResponse.documents;
				if (documents == null)
				{
					entries = new List<CommunityStructureEntry>();
					return true;
				}
				nextPageToken = firestoreApiResponse.nextPageToken ?? string.Empty;
				foreach (FirestoreDocument item in documents)
				{
					if (TryBuildEntryFromDocument(item, out var entry))
					{
						entries.Add(entry);
					}
				}
				entries = (from communityStructureEntry in entries
					orderby communityStructureEntry.Score descending, communityStructureEntry.CreatedAtUtc ?? DateTime.MinValue descending
					select communityStructureEntry).ThenBy<CommunityStructureEntry, string>((CommunityStructureEntry communityStructureEntry) => communityStructureEntry.Name ?? string.Empty, StringComparer.OrdinalIgnoreCase).ToList();
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				return false;
			}
		}

		private static void AddUniqueCachedEntries(List<CommunityStructureEntry> entries)
		{
			if (entries == null || entries.Count == 0)
			{
				return;
			}
			List<CommunityStructureEntry> list = (from communityStructureEntry in CachedEntriesInternal.Concat(entries)
				where communityStructureEntry != null && !string.IsNullOrWhiteSpace(communityStructureEntry.Id)
				select communityStructureEntry).ToList();
			CachedEntriesInternal.Clear();
			foreach (CommunityStructureEntry entry in list)
			{
				int num = CachedEntriesInternal.FindIndex((CommunityStructureEntry existing) => string.Equals(existing?.Id, entry.Id, StringComparison.OrdinalIgnoreCase) || IsLegacyJsonDuplicate(existing, entry));
				if (num < 0)
				{
					CachedEntriesInternal.Add(entry);
				}
				else if (IsPreferredEntry(entry, CachedEntriesInternal[num]))
				{
					CachedEntriesInternal[num] = entry;
				}
			}
			CachedEntriesInternal.Sort(delegate(CommunityStructureEntry left, CommunityStructureEntry right)
			{
				int num2 = (right?.Score ?? 0).CompareTo(left?.Score ?? 0);
				if (num2 != 0)
				{
					return num2;
				}
				int num3 = Nullable.Compare(right?.CreatedAtUtc, left?.CreatedAtUtc);
				return (num3 != 0) ? num3 : string.Compare(left?.Name ?? string.Empty, right?.Name ?? string.Empty, StringComparison.OrdinalIgnoreCase);
			});
		}

		private static void TryLoadCatalogCache()
		{
			try
			{
				string catalogCachePath = GetCatalogCachePath();
				if (!File.Exists(catalogCachePath))
				{
					return;
				}
				CommunityStructureCatalogCache communityStructureCatalogCache = DeserializeJson<CommunityStructureCatalogCache>(File.ReadAllText(catalogCachePath));
				if (communityStructureCatalogCache == null || communityStructureCatalogCache.entries == null || communityStructureCatalogCache.entries.Count == 0 || !string.Equals(communityStructureCatalogCache.catalogUrl ?? string.Empty, GetCatalogUrl(), StringComparison.OrdinalIgnoreCase) || !DateTime.TryParse(communityStructureCatalogCache.savedAtUtc ?? string.Empty, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result) || (DateTime.UtcNow - result).TotalHours > 24.0)
				{
					return;
				}
				CachedEntriesInternal.Clear();
				NextCatalogPageToken = communityStructureCatalogCache.nextPageToken ?? string.Empty;
				foreach (CommunityStructureCatalogCacheEntry entry in communityStructureCatalogCache.entries)
				{
					if (entry != null && !string.IsNullOrWhiteSpace(entry.id))
					{
						DateTime result2;
						DateTime? createdAtUtc = (DateTime.TryParse(entry.createdAtUtc ?? string.Empty, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out result2) ? new DateTime?(result2) : ((DateTime?)null));
						CachedEntriesInternal.Add(new CommunityStructureEntry
						{
							Id = entry.id,
							Name = (string.IsNullOrWhiteSpace(entry.name) ? "Untitled" : entry.name),
							Author = (string.IsNullOrWhiteSpace(entry.author) ? "Anonymous" : entry.author),
							Code = (entry.code ?? string.Empty),
							CreatedAtUtc = createdAtUtc,
							UpdatedAtUtc = ParseOptionalUtc(entry.updatedAtUtc),
							Score = entry.score
						});
					}
				}
				List<CommunityStructureEntry> entries = CachedEntriesInternal.ToList();
				CachedEntriesInternal.Clear();
				AddUniqueCachedEntries(entries);
				LastCatalogStatus = (HasMoreCatalogEntries ? $"Catalog cache loaded: {CachedEntriesInternal.Count} entries. Scroll down or refresh for more." : $"Catalog cache loaded: {CachedEntriesInternal.Count} entries.");
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("Failed loading community catalog cache: " + ex.Message));
				}
			}
		}

		private static void SaveCatalogCache()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CommunityStructureCatalogCache communityStructureCatalogCache = new CommunityStructureCatalogCache
				{
					catalogUrl = GetCatalogUrl(),
					nextPageToken = (NextCatalogPageToken ?? string.Empty),
					savedAtUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
					entries = (from entry in CachedEntriesInternal.Take(600)
						select new CommunityStructureCatalogCacheEntry
						{
							id = (entry?.Id ?? string.Empty),
							name = (entry?.Name ?? string.Empty),
							author = (entry?.Author ?? string.Empty),
							code = (entry?.Code ?? string.Empty),
							createdAtUtc = ((entry != null && entry.CreatedAtUtc.HasValue) ? entry.CreatedAtUtc.Value.ToString("o", CultureInfo.InvariantCulture) : string.Empty),
							updatedAtUtc = ((entry != null && entry.UpdatedAtUtc.HasValue) ? entry.UpdatedAtUtc.Value.ToString("o", CultureInfo.InvariantCulture) : string.Empty),
							score = (entry?.Score ?? 0)
						}).ToList()
				};
				string catalogCachePath = GetCatalogCachePath();
				Directory.CreateDirectory(Path.GetDirectoryName(catalogCachePath));
				using MemoryStream memoryStream = new MemoryStream();
				DataContractJsonSerializerSettings val = new DataContractJsonSerializerSettings
				{
					UseSimpleDictionaryFormat = true
				};
				((XmlObjectSerializer)new DataContractJsonSerializer(typeof(CommunityStructureCatalogCache), val)).WriteObject((Stream)memoryStream, (object)communityStructureCatalogCache);
				File.WriteAllBytes(catalogCachePath, memoryStream.ToArray());
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("Failed saving community catalog cache: " + ex.Message));
				}
			}
		}

		private static bool TryParseSingleDocument(string json, out CommunityStructureEntry entry, out string error)
		{
			entry = null;
			error = null;
			try
			{
				FirestoreApiResponse firestoreApiResponse = DeserializeJson<FirestoreApiResponse>(json);
				if (firestoreApiResponse == null)
				{
					error = "Top-level JSON object missing.";
					return false;
				}
				if (TryReadFirestoreError(firestoreApiResponse, out var message))
				{
					error = message;
					return false;
				}
				if (!TryBuildEntryFromDocument(new FirestoreDocument
				{
					name = firestoreApiResponse.name,
					createTime = firestoreApiResponse.createTime,
					fields = firestoreApiResponse.fields
				}, out var entry2))
				{
					error = "No valid structure document was returned.";
					return false;
				}
				entry = entry2;
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				return false;
			}
		}

		private static bool TryBuildEntryFromDocument(FirestoreDocument document, out CommunityStructureEntry entry)
		{
			entry = null;
			Dictionary<string, FirestoreFieldValue> dictionary = document?.fields;
			if (dictionary == null)
			{
				return false;
			}
			string text = ExtractDocumentId(document.name ?? string.Empty);
			if (string.IsNullOrWhiteSpace(text))
			{
				return false;
			}
			string text2 = ReadFirestoreString(dictionary, "name");
			string text3 = ReadFirestoreString(dictionary, "author");
			string text4 = ReadFirestoreString(dictionary, "code");
			int score = ReadFirestoreInt(dictionary, "score");
			DateTime? dateTime = ReadFirestoreTimestamp(dictionary, "createdAt");
			if (!dateTime.HasValue && DateTime.TryParse(document.createTime ?? string.Empty, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result))
			{
				dateTime = result;
			}
			DateTime? updatedAtUtc = ReadFirestoreTimestamp(dictionary, "updatedAt") ?? dateTime;
			entry = new CommunityStructureEntry
			{
				Id = text,
				Name = (string.IsNullOrWhiteSpace(text2) ? "Untitled" : text2),
				Author = (string.IsNullOrWhiteSpace(text3) ? "Anonymous" : text3),
				Code = (text4 ?? string.Empty),
				CreatedAtUtc = dateTime,
				UpdatedAtUtc = updatedAtUtc,
				Score = score
			};
			return true;
		}

		private static bool IsLegacyJsonDuplicate(CommunityStructureEntry left, CommunityStructureEntry right)
		{
			string text = (left?.Name ?? string.Empty).Trim();
			string text2 = (left?.Author ?? string.Empty).Trim();
			string b = (right?.Name ?? string.Empty).Trim();
			string b2 = (right?.Author ?? string.Empty).Trim();
			if (text.Length == 0 || text2.Length == 0 || !string.Equals(text, b, StringComparison.OrdinalIgnoreCase) || !string.Equals(text2, b2, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			bool flag = LooksLikeJson(left?.Code);
			bool flag2 = LooksLikeJson(right?.Code);
			if (flag == flag2)
			{
				return false;
			}
			CommunityStructureEntry communityStructureEntry = (flag ? left : right);
			CommunityStructureEntry communityStructureEntry2 = (flag ? right : left);
			DateTime obj = communityStructureEntry.UpdatedAtUtc ?? communityStructureEntry.CreatedAtUtc ?? DateTime.MinValue;
			DateTime dateTime = communityStructureEntry2.UpdatedAtUtc ?? communityStructureEntry2.CreatedAtUtc ?? DateTime.MinValue;
			return obj >= dateTime;
		}

		private static bool IsPreferredEntry(CommunityStructureEntry candidate, CommunityStructureEntry current)
		{
			DateTime dateTime = candidate?.UpdatedAtUtc ?? candidate?.CreatedAtUtc ?? DateTime.MinValue;
			DateTime dateTime2 = current?.UpdatedAtUtc ?? current?.CreatedAtUtc ?? DateTime.MinValue;
			if (dateTime != dateTime2)
			{
				return dateTime > dateTime2;
			}
			if (LooksLikeJson(candidate?.Code))
			{
				return !LooksLikeJson(current?.Code);
			}
			return false;
		}

		private static DateTime? ParseOptionalUtc(string value)
		{
			if (!DateTime.TryParse(value ?? string.Empty, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result))
			{
				return null;
			}
			return result;
		}

		private static bool TryReadFirestoreError(FirestoreApiResponse root, out string message)
		{
			message = null;
			if (root?.error == null)
			{
				return false;
			}
			string text = root.error.message;
			if (string.IsNullOrWhiteSpace(text))
			{
				text = "Remote service returned an error.";
			}
			message = text;
			return true;
		}

		private static string BuildDocumentUrl(string id)
		{
			return "https://firestore.googleapis.com/v1/projects/cu-structure-editor/databases/(default)/documents/published_levels/" + UnityWebRequest.EscapeURL(id) + "?key=AIzaSyBPuYD1WX-h5naDAfoiUnScowieUJhHHUM";
		}

		private static string GetCatalogCachePath()
		{
			return Path.Combine(Paths.CachePath, "MoreStructures", "CommunityCatalogCache.json");
		}

		private static string BuildCatalogPageUrl(string pageToken)
		{
			string text = GetCatalogUrl();
			if (text.IndexOf("pageSize=", StringComparison.OrdinalIgnoreCase) < 0)
			{
				text = AppendQueryParameter(text, "pageSize", 30.ToString(CultureInfo.InvariantCulture));
			}
			if (string.IsNullOrWhiteSpace(pageToken))
			{
				return text;
			}
			return AppendQueryParameter(text, "pageToken", pageToken.Trim());
		}

		private static string AppendQueryParameter(string url, string key, string value)
		{
			if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(key))
			{
				return url;
			}
			char c = (url.Contains("?") ? '&' : '?');
			return url + c + UnityWebRequest.EscapeURL(key) + "=" + UnityWebRequest.EscapeURL(value ?? string.Empty);
		}

		private static string ResolveStructureOutputDirectory()
		{
			string structurePath = StructureLoader.StructurePath;
			if (!string.IsNullOrWhiteSpace(structurePath))
			{
				return structurePath;
			}
			return Path.Combine(Paths.PluginPath, "Structures");
		}

		private static List<string> FindInstalledStructureFiles(string structureId)
		{
			string path = ResolveStructureOutputDirectory();
			if (!Directory.Exists(path))
			{
				return new List<string>();
			}
			string text = SanitizeFileName(structureId);
			string text2 = SanitizeFileName(CachedEntriesInternal.FirstOrDefault((CommunityStructureEntry entry) => string.Equals(entry?.Id, structureId, StringComparison.OrdinalIgnoreCase))?.Name);
			if (string.IsNullOrWhiteSpace(text) && string.IsNullOrWhiteSpace(text2))
			{
				return new List<string>();
			}
			string suffixTxt = "-" + text + ".txt";
			string suffixV2 = "-" + text + ".ms2.json";
			string namedTxt = (string.IsNullOrWhiteSpace(text2) ? null : (text2 + ".txt"));
			string namedV2 = (string.IsNullOrWhiteSpace(text2) ? null : (text2 + ".ms2.json"));
			return (from text3 in Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)
				where text3.EndsWith(suffixTxt, StringComparison.OrdinalIgnoreCase) || text3.EndsWith(suffixV2, StringComparison.OrdinalIgnoreCase) || (!string.IsNullOrWhiteSpace(namedTxt) && string.Equals(Path.GetFileName(text3), namedTxt, StringComparison.OrdinalIgnoreCase)) || (!string.IsNullOrWhiteSpace(namedV2) && string.Equals(Path.GetFileName(text3), namedV2, StringComparison.OrdinalIgnoreCase))
				select text3).ToList();
		}

		private static void RefreshInstalledEntries()
		{
			InstalledEntriesInternal.Clear();
			InstalledRemoteIds.Clear();
			InstalledDefinitionNames.Clear();
			string path = ResolveStructureOutputDirectory();
			if (!Directory.Exists(path))
			{
				InstalledEntriesDirty = false;
				return;
			}
			try
			{
				string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
				foreach (string text in files)
				{
					if ((text.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || text.EndsWith(".ms2.json", StringComparison.OrdinalIgnoreCase)) && TryBuildInstalledEntry(text, out var entry))
					{
						InstalledEntriesInternal.Add(entry);
						if (!string.IsNullOrWhiteSpace(entry.Id) && !entry.Id.StartsWith("local:", StringComparison.OrdinalIgnoreCase))
						{
							InstalledRemoteIds.Add(entry.Id);
						}
						CommunityStructureMetadata communityStructureMetadata = CommunityStructureMetadataParser.Parse(entry);
						if (!string.IsNullOrWhiteSpace(communityStructureMetadata?.DefinitionName))
						{
							InstalledDefinitionNames.Add(communityStructureMetadata.DefinitionName);
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("Failed scanning installed community structures: " + ex.Message));
				}
			}
			InstalledEntriesDirty = false;
		}

		private static void EnsureInstalledEntriesCurrent()
		{
			if (InstalledEntriesDirty)
			{
				RefreshInstalledEntries();
			}
		}

		private static bool TryBuildInstalledEntry(string path, out CommunityStructureEntry entry)
		{
			entry = null;
			try
			{
				string text = File.ReadAllText(path);
				if (string.IsNullOrWhiteSpace(text))
				{
					return false;
				}
				string text2 = ResolveRemoteIdFromInstalledFileName(path);
				string text3 = ResolveInstalledDisplayName(path);
				CommunityStructureEntry communityStructureEntry = new CommunityStructureEntry
				{
					Id = (string.IsNullOrWhiteSpace(text2) ? ("local:" + text3) : text2),
					Name = text3,
					Author = "Installed",
					Code = text,
					CreatedAtUtc = File.GetLastWriteTimeUtc(path),
					Score = 0
				};
				CommunityStructureMetadata communityStructureMetadata = CommunityStructureMetadataParser.Parse(communityStructureEntry);
				if (communityStructureMetadata != null && !string.IsNullOrWhiteSpace(communityStructureMetadata.DefinitionName))
				{
					communityStructureEntry.Name = communityStructureMetadata.DefinitionName;
				}
				if (!string.IsNullOrWhiteSpace(text2) && communityStructureMetadata != null && !string.IsNullOrWhiteSpace(communityStructureMetadata.DefinitionName))
				{
					CommunityStructureLocalPrefs.SetRemoteDefinitionName(text2, communityStructureMetadata.DefinitionName);
				}
				entry = communityStructureEntry;
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("Failed reading installed structure '" + Path.GetFileName(path) + "': " + ex.Message));
				}
				return false;
			}
		}

		private static List<CommunityStructureEntry> MergeInstalledEntriesFirst()
		{
			List<CommunityStructureEntry> list = new List<CommunityStructureEntry>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (CommunityStructureEntry item in InstalledEntriesInternal)
			{
				if (item != null && !string.IsNullOrWhiteSpace(item.Id) && hashSet.Add(item.Id))
				{
					list.Add(item);
				}
			}
			foreach (CommunityStructureEntry item2 in CachedEntriesInternal)
			{
				if (item2 != null && !string.IsNullOrWhiteSpace(item2.Id) && hashSet.Add(item2.Id))
				{
					list.Add(item2);
				}
			}
			list.Sort(delegate(CommunityStructureEntry left, CommunityStructureEntry right)
			{
				bool flag = string.Equals(left?.Author, "Installed", StringComparison.OrdinalIgnoreCase);
				bool flag2 = string.Equals(right?.Author, "Installed", StringComparison.OrdinalIgnoreCase);
				if (flag != flag2)
				{
					if (!flag)
					{
						return 1;
					}
					return -1;
				}
				int num = (right?.Score ?? 0).CompareTo(left?.Score ?? 0);
				if (num != 0)
				{
					return num;
				}
				int num2 = Nullable.Compare(right?.CreatedAtUtc, left?.CreatedAtUtc);
				return (num2 != 0) ? num2 : string.Compare(left?.Name ?? string.Empty, right?.Name ?? string.Empty, StringComparison.OrdinalIgnoreCase);
			});
			return list;
		}

		private static string ResolveRemoteIdFromInstalledFileName(string path)
		{
			string fileName = Path.GetFileName(path);
			if (string.IsNullOrWhiteSpace(fileName))
			{
				return string.Empty;
			}
			foreach (CommunityStructureEntry item in CachedEntriesInternal)
			{
				string text = SanitizeFileName(item?.Id);
				if (!string.IsNullOrWhiteSpace(text))
				{
					if (fileName.EndsWith("-" + text + ".txt", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith("-" + text + ".ms2.json", StringComparison.OrdinalIgnoreCase))
					{
						return item.Id;
					}
					string text2 = SanitizeFileName(item?.Name);
					if (!string.IsNullOrWhiteSpace(text2) && (string.Equals(fileName, text2 + ".txt", StringComparison.OrdinalIgnoreCase) || string.Equals(fileName, text2 + ".ms2.json", StringComparison.OrdinalIgnoreCase)))
					{
						return item.Id;
					}
				}
			}
			return ExtractRemoteIdFromInstalledFileName(path);
		}

		private static string ResolveInstalledDisplayName(string path)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
			if (path.EndsWith(".ms2.json", StringComparison.OrdinalIgnoreCase))
			{
				fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithoutExtension);
			}
			return fileNameWithoutExtension ?? string.Empty;
		}

		private static string ExtractRemoteIdFromInstalledFileName(string path)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
			if (path.EndsWith(".ms2.json", StringComparison.OrdinalIgnoreCase))
			{
				fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithoutExtension);
			}
			if (string.IsNullOrWhiteSpace(fileNameWithoutExtension))
			{
				return string.Empty;
			}
			int num = fileNameWithoutExtension.LastIndexOf('-');
			if (num < 0 || num >= fileNameWithoutExtension.Length - 1)
			{
				return string.Empty;
			}
			return fileNameWithoutExtension.Substring(num + 1).Trim();
		}

		private static string BuildSafeFileName(CommunityStructureEntry entry, string extension)
		{
			string text = SanitizeFileName(entry.Name);
			string text2 = SanitizeFileName(entry.Id);
			if (string.IsNullOrWhiteSpace(text))
			{
				text = "community-structure";
			}
			if (!string.IsNullOrWhiteSpace(text2) && !text.EndsWith("-" + text2, StringComparison.OrdinalIgnoreCa