Decompiled source of balrond hearth marks v1.0.1

plugins/BalrondHearthMarks.dll

Decompiled 2 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using HarmonyLib;
using LitJson2;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("BalrondHearthMarks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BalrondHearthMarks")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("cde312a0-cf19-4264-8616-e1c74774beed")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[DisallowMultipleComponent]
public class BalrondHearthMark : MonoBehaviour, TextReceiver, Hoverable, Interactable
{
	private enum EditMode
	{
		None,
		Name,
		Radius
	}

	public const string RpcSetName = "RPC_BalrondHearthMark_SetName";

	public const string RpcSetRadius = "RPC_BalrondHearthMark_SetRadius";

	public const string RpcSetEnabled = "RPC_BalrondHearthMark_SetEnabled";

	public const string RpcSetAreaMarkerVisible = "RPC_BalrondHearthMark_SetAreaMarkerVisible";

	public const string ZdoKeyName = "balrond_hearth_mark_name";

	public const string ZdoKeyRadius = "balrond_hearth_mark_radius";

	public const string ZdoKeyEnabled = "balrond_hearth_mark_enabled";

	public const string ZdoKeyInitialized = "balrond_hearth_mark_initialized";

	public const string ZdoKeyAreaMarkerVisible = "balrond_hearth_mark_area_marker_visible";

	public const float DefaultRadius = 15f;

	public const float MinRadius = 1f;

	public const float MaxRadius = 50f;

	public const float RadiusStep = 1f;

	private const float ConnectionBeamHeight = -0.15f;

	public string m_name = "$tag_hearthmark_name_bal";

	[Header("Range")]
	public float m_radius = 15f;

	public float m_updateConnectionsInterval = 2f;

	public CircleProjector m_areaMarker;

	public GameObject m_connectEffect;

	public GameObject m_inRangeEffect;

	[Header("Visual state")]
	public GameObject m_enabledVisual;

	public GameObject m_disabledVisual;

	public EffectList m_enableEffect = new EffectList();

	public EffectList m_disableEffect = new EffectList();

	[Header("Trigger")]
	public CapsuleCollider m_triggerCollider;

	public bool m_createTriggerIfMissing = true;

	[Header("Access")]
	public bool m_requireWardAccess = true;

	[Header("Message")]
	public bool m_playStinger = true;

	public float m_localZoneMessageCooldown = 8f;

	public float m_globalMessageCooldown = 2f;

	public float m_sameTextRepeatCooldown = 16f;

	public float m_presenceCheckInterval = 0.1f;

	[Header("Input")]
	public int m_nameCharacterLimit = 64;

	public int m_radiusCharacterLimit = 8;

	private static readonly List<BalrondHearthMark> s_all = new List<BalrondHearthMark>();

	private static float s_lastGlobalMessageTime = -999f;

	private static string s_lastGlobalMessageText = string.Empty;

	private readonly List<GameObject> m_connectionInstances = new List<GameObject>();

	private readonly List<BalrondHearthMark> m_connectedAreas = new List<BalrondHearthMark>();

	private ZNetView m_nview;

	private Piece m_piece;

	private EditMode m_editMode = EditMode.None;

	private bool m_localPlayerInside;

	private bool m_tempChecked;

	private float m_connectionUpdateTime = -1000f;

	private float m_lastHoverTime = -1000f;

	private float m_lastLocalZoneMessageTime = -999f;

	private float m_nextPresenceCheckTime = -999f;

	private string m_lastEnteredResolvedName = string.Empty;

	private void Awake()
	{
		m_nview = ((Component)this).GetComponent<ZNetView>();
		m_piece = ((Component)this).GetComponent<Piece>();
		if (!s_all.Contains(this))
		{
			s_all.Add(this);
		}
		if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
		{
			m_nview.Register<string>("RPC_BalrondHearthMark_SetName", (Action<long, string>)RPC_SetName);
			m_nview.Register<float>("RPC_BalrondHearthMark_SetRadius", (Action<long, float>)RPC_SetRadius);
			m_nview.Register<bool>("RPC_BalrondHearthMark_SetEnabled", (Action<long, bool>)RPC_SetEnabled);
			m_nview.Register<bool>("RPC_BalrondHearthMark_SetAreaMarkerVisible", (Action<long, bool>)RPC_SetAreaMarkerVisible);
			if (m_nview.IsOwner() && m_nview.GetZDO().GetInt("balrond_hearth_mark_initialized", 0) == 0)
			{
				m_nview.GetZDO().Set("balrond_hearth_mark_initialized", 1);
				m_nview.GetZDO().Set("balrond_hearth_mark_radius", Mathf.Clamp(m_radius, 1f, 50f));
				m_nview.GetZDO().Set("balrond_hearth_mark_name", string.Empty);
				m_nview.GetZDO().Set("balrond_hearth_mark_enabled", true);
				m_nview.GetZDO().Set("balrond_hearth_mark_area_marker_visible", false);
			}
			EnsureAreaMarker();
			EnsureTrigger();
			if ((Object)(object)m_areaMarker != (Object)null)
			{
				m_areaMarker.m_radius = GetRadius();
				((Component)m_areaMarker).gameObject.SetActive(IsEnabled() && IsAreaMarkerVisiblePersistent());
			}
			if ((Object)(object)m_inRangeEffect != (Object)null)
			{
				m_inRangeEffect.SetActive(false);
			}
			ApplyRadiusVisuals(GetRadius());
			UpdateVisualState();
		}
	}

	private void OnDestroy()
	{
		StopConnectionEffects();
		s_all.Remove(this);
		InvalidateAllConnectionCaches();
		((MonoBehaviour)this).CancelInvoke();
	}

	private void Update()
	{
		HandleRangeInput();
		if (Time.time >= m_nextPresenceCheckTime)
		{
			m_nextPresenceCheckTime = Time.time + m_presenceCheckInterval;
			UpdateLocalPlayerPresence();
		}
	}

	public string GetHoverName()
	{
		return GetDisplayName();
	}

	public string GetHoverText()
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		if (!IsValid())
		{
			return string.Empty;
		}
		m_lastHoverTime = Time.time;
		if (IsEnabled())
		{
			ShowAreaMarker();
			PokeConnectionEffects();
		}
		if (m_requireWardAccess && !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false))
		{
			return Localize(GetDisplayName() + "\n$tag_hearthmark_no_access_bal");
		}
		StringBuilder stringBuilder = new StringBuilder(256);
		stringBuilder.Append(GetDisplayName());
		stringBuilder.Append(" <color=orange><b>(");
		stringBuilder.Append(IsEnabled() ? "$tag_hearthmark_state_on_bal" : "$tag_hearthmark_state_off_bal");
		stringBuilder.Append(")</b></color>");
		AppendAction(stringBuilder, "$KEY_Use", "$tag_hearthmark_set_name_bal", null);
		AppendAction(stringBuilder, "Shift + $KEY_Use", IsEnabled() ? "$tag_hearthmark_disable_bal" : "$tag_hearthmark_enable_bal", null);
		AppendAction(stringBuilder, "Alt + $KEY_Use", IsAreaMarkerVisiblePersistent() ? "$tag_hearthmark_marker_hide_bal" : "$tag_hearthmark_marker_show_bal", null);
		AppendAction(stringBuilder, "+ / -", "$tag_hearthmark_adjust_range_bal", Mathf.RoundToInt(GetRadius()) + "/" + Mathf.RoundToInt(50f) + "m");
		int count = GetConnectedAreas().Count;
		if (count > 1)
		{
			stringBuilder.Append("\n<color=grey>$tag_hearthmark_connected_bal: ").Append(count).Append("</color>");
		}
		if (!IsEnabled())
		{
			stringBuilder.Append("\n<color=grey>$tag_hearthmark_disabled_hint_bal</color>");
		}
		return Localize(stringBuilder.ToString());
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		if (hold)
		{
			return false;
		}
		if (!IsValid())
		{
			return false;
		}
		if (m_requireWardAccess && !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return true;
		}
		if (IsAltHeld())
		{
			ToggleAreaMarkerVisible(user);
			return true;
		}
		if (alt)
		{
			ToggleNetworkEnabled(user);
			return true;
		}
		RequestNameInput();
		return true;
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		return false;
	}

	private static void AppendAction(StringBuilder text, string key, string label, string value)
	{
		text.Append("\n[<color=yellow><b>").Append(key).Append("</b></color>] ")
			.Append(label);
		if (!string.IsNullOrEmpty(value))
		{
			text.Append(" : <color=yellow><b>").Append(value).Append("</b></color>");
		}
	}

	public bool IsEnabled()
	{
		return IsValid() && m_nview.GetZDO().GetBool("balrond_hearth_mark_enabled", true);
	}

	private bool IsAreaMarkerVisiblePersistent()
	{
		return IsValid() && m_nview.GetZDO().GetBool("balrond_hearth_mark_area_marker_visible", false);
	}

	private void ToggleAreaMarkerVisible(Humanoid user)
	{
		if (IsValid() && IsEnabled())
		{
			bool flag = !IsAreaMarkerVisiblePersistent();
			if (!m_nview.HasOwner())
			{
				m_nview.ClaimOwnership();
			}
			m_nview.InvokeRPC("RPC_BalrondHearthMark_SetAreaMarkerVisible", new object[1] { flag });
			Player val = (Player)(object)((user is Player) ? user : null);
			if ((Object)(object)val != (Object)null)
			{
				((Character)val).Message((MessageType)2, flag ? "$tag_hearthmark_marker_enabled_bal" : "$tag_hearthmark_marker_disabled_bal", 0, (Sprite)null);
			}
		}
	}

	private void RPC_SetAreaMarkerVisible(long sender, bool visible)
	{
		if (IsValid() && m_nview.IsOwner())
		{
			m_nview.GetZDO().Set("balrond_hearth_mark_area_marker_visible", visible);
			ApplyAreaMarkerVisibleState();
		}
	}

	private void ApplyAreaMarkerVisibleState()
	{
		EnsureAreaMarker();
		if (!((Object)(object)m_areaMarker == (Object)null))
		{
			bool active = IsEnabled() && IsAreaMarkerVisiblePersistent();
			m_areaMarker.m_radius = GetRadius();
			((Component)m_areaMarker).gameObject.SetActive(active);
		}
	}

	private void ToggleNetworkEnabled(Humanoid user)
	{
		if (!IsValid())
		{
			return;
		}
		bool flag = !IsEnabled();
		List<BalrondHearthMark> list = (IsEnabled() ? GetConnectedAreas(forceUpdate: true) : new List<BalrondHearthMark> { this });
		for (int i = 0; i < list.Count; i++)
		{
			BalrondHearthMark balrondHearthMark = list[i];
			if (!((Object)(object)balrondHearthMark == (Object)null) && balrondHearthMark.IsValid())
			{
				if (!balrondHearthMark.m_nview.HasOwner())
				{
					balrondHearthMark.m_nview.ClaimOwnership();
				}
				balrondHearthMark.m_nview.InvokeRPC("RPC_BalrondHearthMark_SetEnabled", new object[1] { flag });
			}
		}
		Player val = (Player)(object)((user is Player) ? user : null);
		if ((Object)(object)val != (Object)null)
		{
			((Character)val).Message((MessageType)2, flag ? "$tag_hearthmark_msg_enabled_bal" : "$tag_hearthmark_msg_disabled_bal", 0, (Sprite)null);
		}
	}

	private void RPC_SetEnabled(long sender, bool enabled)
	{
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		if (!IsValid() || !m_nview.IsOwner())
		{
			return;
		}
		bool flag = IsEnabled();
		m_nview.GetZDO().Set("balrond_hearth_mark_enabled", enabled);
		if (!enabled)
		{
			m_localPlayerInside = false;
			m_lastEnteredResolvedName = string.Empty;
			HideMarker();
			StopConnectionEffects();
		}
		UpdateVisualState();
		InvalidateAllConnectionCaches();
		if (flag != enabled)
		{
			if (enabled)
			{
				m_enableEffect.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1);
			}
			else
			{
				m_disableEffect.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1);
			}
		}
	}

	private void UpdateVisualState()
	{
		bool flag = IsEnabled();
		if ((Object)(object)m_enabledVisual != (Object)null)
		{
			m_enabledVisual.SetActive(flag);
		}
		if ((Object)(object)m_disabledVisual != (Object)null)
		{
			m_disabledVisual.SetActive(!flag);
		}
		ApplyAreaMarkerVisibleState();
	}

	private void HandleRangeInput()
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		if (!(Time.time - m_lastHoverTime > 0.25f) && (!m_requireWardAccess || PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false)))
		{
			if (Input.GetKeyDown((KeyCode)61) || Input.GetKeyDown((KeyCode)270))
			{
				ChangeRadius(1f);
			}
			if (Input.GetKeyDown((KeyCode)45) || Input.GetKeyDown((KeyCode)269))
			{
				ChangeRadius(-1f);
			}
		}
	}

	private void ChangeRadius(float delta)
	{
		if (!IsValid())
		{
			return;
		}
		if (!m_nview.HasOwner())
		{
			m_nview.ClaimOwnership();
		}
		if (m_nview.IsOwner())
		{
			float radius = GetRadius();
			float num = Mathf.Clamp(radius + delta, 1f, 50f);
			if (!Mathf.Approximately(radius, num))
			{
				m_nview.GetZDO().Set("balrond_hearth_mark_radius", num);
				m_radius = num;
				ApplyRadiusVisuals(num);
				InvalidateAllConnectionCaches();
				ShowCenterMessage("$tag_hearthmark_msg_range_bal " + Mathf.RoundToInt(num) + "m");
			}
		}
	}

	private void RequestNameInput()
	{
		if (!((Object)(object)TextInput.instance == (Object)null))
		{
			m_editMode = EditMode.Name;
			TextInput.instance.RequestText((TextReceiver)(object)this, "$tag_hearthmark_input_name_title_bal", m_nameCharacterLimit);
		}
	}

	private void RequestRadiusInput()
	{
		if (!((Object)(object)TextInput.instance == (Object)null))
		{
			m_editMode = EditMode.Radius;
			TextInput.instance.RequestText((TextReceiver)(object)this, "$tag_hearthmark_input_radius_title_bal", m_radiusCharacterLimit);
		}
	}

	public string GetText()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		if (m_editMode == EditMode.Name)
		{
			return GetZoneNameRaw();
		}
		if (m_editMode == EditMode.Radius)
		{
			return GetRadius().ToString(CultureInfo.InvariantCulture);
		}
		return string.Empty;
	}

	public void SetText(string text)
	{
		if (IsValid())
		{
			if (m_editMode == EditMode.Name)
			{
				SetNameFromInput(text);
			}
			else if (m_editMode == EditMode.Radius)
			{
				SetRadiusFromInput(text);
			}
			m_editMode = EditMode.None;
		}
	}

	private void SetNameFromInput(string text)
	{
		string text2 = (text ?? string.Empty).Trim();
		if (string.IsNullOrEmpty(text2))
		{
			ShowCenterMessage("$tag_hearthmark_msg_name_empty_bal");
			return;
		}
		if (text2.Length > m_nameCharacterLimit)
		{
			text2 = text2.Substring(0, m_nameCharacterLimit);
		}
		m_nview.InvokeRPC("RPC_BalrondHearthMark_SetName", new object[1] { text2 });
		ShowCenterMessage("$tag_hearthmark_msg_name_set_bal: " + text2);
	}

	private void SetRadiusFromInput(string text)
	{
		string s = (text ?? string.Empty).Trim();
		if (!float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
		{
			ShowCenterMessage("$tag_hearthmark_msg_radius_not_number_bal");
			return;
		}
		if (result < 1f || result > 50f)
		{
			ShowCenterMessage("$tag_hearthmark_msg_radius_invalid_bal");
			return;
		}
		m_nview.InvokeRPC("RPC_BalrondHearthMark_SetRadius", new object[1] { result });
		ShowCenterMessage("$tag_hearthmark_msg_radius_set_bal: " + Mathf.RoundToInt(result) + "m");
	}

	private void RPC_SetName(long sender, string name)
	{
		if (!IsValid() || !m_nview.IsOwner())
		{
			return;
		}
		string text = (name ?? string.Empty).Trim();
		if (text.Length > m_nameCharacterLimit)
		{
			text = text.Substring(0, m_nameCharacterLimit);
		}
		List<BalrondHearthMark> list = (IsEnabled() ? GetConnectedAreas(forceUpdate: true) : new List<BalrondHearthMark> { this });
		for (int i = 0; i < list.Count; i++)
		{
			BalrondHearthMark balrondHearthMark = list[i];
			if (!((Object)(object)balrondHearthMark == (Object)null) && balrondHearthMark.IsValid())
			{
				if (!balrondHearthMark.m_nview.HasOwner())
				{
					balrondHearthMark.m_nview.ClaimOwnership();
				}
				if (balrondHearthMark.m_nview.IsOwner())
				{
					balrondHearthMark.m_nview.GetZDO().Set("balrond_hearth_mark_name", text);
				}
				balrondHearthMark.InvalidateConnectionCache();
			}
		}
	}

	private void RPC_SetRadius(long sender, float radius)
	{
		if (IsValid() && m_nview.IsOwner())
		{
			float num = Mathf.Clamp(radius, 1f, 50f);
			m_nview.GetZDO().Set("balrond_hearth_mark_radius", num);
			m_radius = num;
			ApplyRadiusVisuals(num);
			InvalidateAllConnectionCaches();
		}
	}

	public bool IsValid()
	{
		return (Object)(object)m_nview != (Object)null && m_nview.IsValid() && m_nview.GetZDO() != null;
	}

	public float GetRadius()
	{
		if (!IsValid())
		{
			return Mathf.Clamp(m_radius, 1f, 50f);
		}
		return Mathf.Clamp(m_nview.GetZDO().GetFloat("balrond_hearth_mark_radius", m_radius), 1f, 50f);
	}

	public string GetZoneNameRaw()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		return m_nview.GetZDO().GetString("balrond_hearth_mark_name", string.Empty);
	}

	public string GetDisplayName()
	{
		string resolvedNetworkName = GetResolvedNetworkName();
		if (!string.IsNullOrWhiteSpace(resolvedNetworkName))
		{
			return resolvedNetworkName;
		}
		if ((Object)(object)m_piece != (Object)null && !string.IsNullOrEmpty(m_piece.m_name))
		{
			return Localize(m_piece.m_name);
		}
		return Localize(m_name);
	}

	private string GetResolvedNetworkName()
	{
		string zoneNameRaw = GetZoneNameRaw();
		if (!string.IsNullOrWhiteSpace(zoneNameRaw))
		{
			return zoneNameRaw;
		}
		if (!IsEnabled())
		{
			return string.Empty;
		}
		List<BalrondHearthMark> connectedAreas = GetConnectedAreas();
		for (int i = 0; i < connectedAreas.Count; i++)
		{
			BalrondHearthMark balrondHearthMark = connectedAreas[i];
			if (!((Object)(object)balrondHearthMark == (Object)null) && !((Object)(object)balrondHearthMark == (Object)(object)this) && balrondHearthMark.IsEnabled())
			{
				string zoneNameRaw2 = balrondHearthMark.GetZoneNameRaw();
				if (!string.IsNullOrWhiteSpace(zoneNameRaw2))
				{
					return zoneNameRaw2;
				}
			}
		}
		return string.Empty;
	}

	public List<BalrondHearthMark> GetConnectedAreas(bool forceUpdate = false)
	{
		if (forceUpdate || Time.time - m_connectionUpdateTime > m_updateConnectionsInterval)
		{
			GetAllConnectedAreas(m_connectedAreas);
			m_connectionUpdateTime = Time.time;
		}
		return m_connectedAreas;
	}

	private void GetAllConnectedAreas(List<BalrondHearthMark> areas)
	{
		areas.Clear();
		if (!IsEnabled())
		{
			areas.Add(this);
			return;
		}
		Queue<BalrondHearthMark> queue = new Queue<BalrondHearthMark>();
		for (int i = 0; i < s_all.Count; i++)
		{
			if ((Object)(object)s_all[i] != (Object)null)
			{
				s_all[i].m_tempChecked = false;
			}
		}
		m_tempChecked = true;
		queue.Enqueue(this);
		areas.Add(this);
		while (queue.Count > 0)
		{
			BalrondHearthMark a = queue.Dequeue();
			for (int j = 0; j < s_all.Count; j++)
			{
				BalrondHearthMark balrondHearthMark = s_all[j];
				if (IsValidMark(balrondHearthMark) && !balrondHearthMark.m_tempChecked && AreTalismansConnected(a, balrondHearthMark))
				{
					balrondHearthMark.m_tempChecked = true;
					areas.Add(balrondHearthMark);
					queue.Enqueue(balrondHearthMark);
				}
			}
		}
	}

	private static bool AreTalismansConnected(BalrondHearthMark a, BalrondHearthMark b)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)a == (Object)null || (Object)(object)b == (Object)null || (Object)(object)a == (Object)(object)b)
		{
			return false;
		}
		if (!a.IsEnabled() || !b.IsEnabled())
		{
			return false;
		}
		float num = Utils.DistanceXZ(((Component)a).transform.position, ((Component)b).transform.position);
		return num <= a.GetRadius() || num <= b.GetRadius();
	}

	private static bool IsValidMark(BalrondHearthMark mark)
	{
		return (Object)(object)mark != (Object)null && mark.IsValid();
	}

	private static void InvalidateAllConnectionCaches()
	{
		for (int i = 0; i < s_all.Count; i++)
		{
			if ((Object)(object)s_all[i] != (Object)null)
			{
				s_all[i].InvalidateConnectionCache();
			}
		}
	}

	private void InvalidateConnectionCache()
	{
		m_connectedAreas.Clear();
		m_connectionUpdateTime = -1000f;
	}

	private void ShowAreaMarker()
	{
		if (!IsEnabled())
		{
			return;
		}
		EnsureAreaMarker();
		if (!((Object)(object)m_areaMarker == (Object)null))
		{
			m_areaMarker.m_radius = GetRadius();
			if (IsAreaMarkerVisiblePersistent())
			{
				((Component)m_areaMarker).gameObject.SetActive(true);
				return;
			}
			((Component)m_areaMarker).gameObject.SetActive(true);
			((MonoBehaviour)this).CancelInvoke("HideMarker");
			((MonoBehaviour)this).Invoke("HideMarker", 0.5f);
		}
	}

	private void HideMarker()
	{
		if (!IsAreaMarkerVisiblePersistent() && (Object)(object)m_areaMarker != (Object)null)
		{
			((Component)m_areaMarker).gameObject.SetActive(false);
		}
	}

	private void PokeConnectionEffects()
	{
		if (!IsEnabled())
		{
			return;
		}
		List<BalrondHearthMark> connectedAreas = GetConnectedAreas();
		StartConnectionEffects();
		for (int i = 0; i < connectedAreas.Count; i++)
		{
			BalrondHearthMark balrondHearthMark = connectedAreas[i];
			if ((Object)(object)balrondHearthMark != (Object)null && (Object)(object)balrondHearthMark != (Object)(object)this && balrondHearthMark.IsEnabled())
			{
				balrondHearthMark.StartConnectionEffects();
			}
		}
	}

	private void StartConnectionEffects()
	{
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		if (!IsEnabled() || (Object)(object)m_connectEffect == (Object)null)
		{
			return;
		}
		List<BalrondHearthMark> list = new List<BalrondHearthMark>();
		for (int i = 0; i < s_all.Count; i++)
		{
			BalrondHearthMark balrondHearthMark = s_all[i];
			if (IsValidMark(balrondHearthMark) && !((Object)(object)balrondHearthMark == (Object)(object)this) && balrondHearthMark.IsEnabled() && AreTalismansConnected(this, balrondHearthMark))
			{
				list.Add(balrondHearthMark);
			}
		}
		Vector3 val = ((Component)this).transform.position + Vector3.up * -0.15f;
		if (m_connectionInstances.Count != list.Count)
		{
			StopConnectionEffects();
			for (int j = 0; j < list.Count; j++)
			{
				GameObject item = Object.Instantiate<GameObject>(m_connectEffect, val, Quaternion.identity, ((Component)this).transform);
				m_connectionInstances.Add(item);
			}
		}
		for (int k = 0; k < list.Count; k++)
		{
			Vector3 val2 = ((Component)list[k]).transform.position + Vector3.up * -0.15f;
			Vector3 val3 = val2 - val;
			if (!(((Vector3)(ref val3)).sqrMagnitude <= 0.001f))
			{
				GameObject val4 = m_connectionInstances[k];
				if (!((Object)(object)val4 == (Object)null))
				{
					val4.transform.position = val;
					val4.transform.rotation = Quaternion.LookRotation(((Vector3)(ref val3)).normalized);
					val4.transform.localScale = new Vector3(1f, 1f, ((Vector3)(ref val3)).magnitude);
				}
			}
		}
		if ((Object)(object)m_inRangeEffect != (Object)null)
		{
			m_inRangeEffect.SetActive(true);
		}
		((MonoBehaviour)this).CancelInvoke("StopConnectionEffects");
		((MonoBehaviour)this).Invoke("StopConnectionEffects", 0.3f);
	}

	private void StopConnectionEffects()
	{
		for (int i = 0; i < m_connectionInstances.Count; i++)
		{
			if ((Object)(object)m_connectionInstances[i] != (Object)null)
			{
				Object.Destroy((Object)(object)m_connectionInstances[i]);
			}
		}
		m_connectionInstances.Clear();
		if ((Object)(object)m_inRangeEffect != (Object)null)
		{
			m_inRangeEffect.SetActive(false);
		}
	}

	private void EnsureAreaMarker()
	{
		if (!((Object)(object)m_areaMarker != (Object)null))
		{
			Transform val = ((Component)this).transform.Find("AreaMarker");
			if ((Object)(object)val != (Object)null)
			{
				m_areaMarker = ((Component)val).GetComponent<CircleProjector>();
			}
			if ((Object)(object)m_areaMarker == (Object)null)
			{
				m_areaMarker = ((Component)this).GetComponentInChildren<CircleProjector>(true);
			}
		}
	}

	private void EnsureTrigger()
	{
		if ((Object)(object)m_triggerCollider == (Object)null)
		{
			m_triggerCollider = ((Component)this).GetComponentInChildren<CapsuleCollider>(true);
		}
		if ((Object)(object)m_triggerCollider == (Object)null && m_createTriggerIfMissing)
		{
			m_triggerCollider = ((Component)this).gameObject.AddComponent<CapsuleCollider>();
			m_triggerCollider.height = 20f;
		}
		if ((Object)(object)m_triggerCollider != (Object)null)
		{
			((Collider)m_triggerCollider).isTrigger = true;
			m_triggerCollider.radius = GetRadius();
		}
	}

	private void ApplyRadiusVisuals(float radius)
	{
		if ((Object)(object)m_triggerCollider != (Object)null)
		{
			m_triggerCollider.radius = radius;
		}
		EnsureAreaMarker();
		if ((Object)(object)m_areaMarker != (Object)null)
		{
			m_areaMarker.m_radius = radius;
		}
	}

	private void UpdateLocalPlayerPresence()
	{
		if (!IsEnabled())
		{
			m_localPlayerInside = false;
			m_lastEnteredResolvedName = string.Empty;
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || (Object)(object)m_triggerCollider == (Object)null)
		{
			return;
		}
		bool flag = IsPlayerInsideZone(localPlayer);
		if (flag != m_localPlayerInside)
		{
			m_localPlayerInside = flag;
			if (flag)
			{
				m_lastEnteredResolvedName = GetResolvedNetworkName();
				TryShowEnterMessage();
			}
			else
			{
				m_lastEnteredResolvedName = string.Empty;
			}
		}
	}

	private bool IsPlayerInsideZone(Player player)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: 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_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: 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_0055: 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_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: 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_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player == (Object)null || (Object)(object)m_triggerCollider == (Object)null || !((Collider)m_triggerCollider).enabled)
		{
			return false;
		}
		Vector3 position = ((Component)player).transform.position;
		Vector3 point = position + Vector3.up * 0.9f;
		Vector3 point2 = position + Vector3.up * 1.6f;
		return IsPointInsideTrigger(position) || IsPointInsideTrigger(point) || IsPointInsideTrigger(point2);
	}

	private bool IsPointInsideTrigger(Vector3 point)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)m_triggerCollider == (Object)null)
		{
			return false;
		}
		Vector3 val = ((Collider)m_triggerCollider).ClosestPoint(point);
		Vector3 val2 = val - point;
		return ((Vector3)(ref val2)).sqrMagnitude <= 0.0001f;
	}

	private void TryShowEnterMessage()
	{
		string resolvedNetworkName = GetResolvedNetworkName();
		if (string.IsNullOrWhiteSpace(resolvedNetworkName))
		{
			return;
		}
		float time = Time.time;
		if (!(time - m_lastLocalZoneMessageTime < m_localZoneMessageCooldown) && !(time - s_lastGlobalMessageTime < m_globalMessageCooldown) && (!(s_lastGlobalMessageText == resolvedNetworkName) || !(time - s_lastGlobalMessageTime < m_sameTextRepeatCooldown)))
		{
			m_lastLocalZoneMessageTime = time;
			s_lastGlobalMessageTime = time;
			s_lastGlobalMessageText = resolvedNetworkName;
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowBiomeFoundMsg(Localize(resolvedNetworkName), m_playStinger);
			}
			else
			{
				ShowCenterMessage(resolvedNetworkName);
			}
		}
	}

	private void ShowCenterMessage(string text)
	{
		if ((Object)(object)Player.m_localPlayer != (Object)null)
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, Localize(text), 0, (Sprite)null);
		}
	}

	private string Localize(string text)
	{
		if (string.IsNullOrEmpty(text))
		{
			return string.Empty;
		}
		return (Localization.instance != null) ? Localization.instance.Localize(text) : text;
	}

	private static bool IsAltHeld()
	{
		return Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307);
	}
}
[DisallowMultipleComponent]
public class BuildPieceNamedZone : MonoBehaviour, TextReceiver
{
	private enum EditMode
	{
		None,
		Radius,
		Name
	}

	public const string RpcSetName = "RPC_BPNamedZone_SetName";

	public const string RpcSetRadius = "RPC_BPNamedZone_SetRadius";

	public const string ZdoKeyName = "bp_named_zone_name";

	public const string ZdoKeyRadius = "bp_named_zone_radius";

	public const int DefaultRadius = 15;

	public const int MinRadius = 1;

	public const int MaxRadius = 50;

	public const string TagHoverSetName = "$tag_housezone_set_name";

	public const string TagHoverSetRadius = "$tag_housezone_set_radius";

	public const string TagHoverNameLabel = "$tag_housezone_name_label";

	public const string TagHoverNoName = "$tag_housezone_no_name";

	public const string TagInputTitleName = "$tag_housezone_input_name_title";

	public const string TagInputTitleRadius = "$tag_housezone_input_radius_title";

	public const string TagMsgNameEmpty = "$tag_housezone_name_empty";

	public const string TagMsgNameSet = "$tag_housezone_name_set";

	public const string TagMsgRadiusNotInt = "$tag_housezone_radius_not_int";

	public const string TagMsgRadiusInvalid = "$tag_housezone_radius_invalid";

	public const string TagMsgRadiusSet = "$tag_housezone_radius_set";

	public const string TagMsgZoneLeft = "$tag_housezone_left";

	public const string TagDefaultDisplayName = "$tag_housezone_default_name";

	public const string TagHoverDisplayOn = "$tag_housezone_display_on";

	public const string TagHoverDisplayOff = "$tag_housezone_display_off";

	public const string TagHoverDisplayShow = "$tag_housezone_display_show";

	public const string TagHoverDisplayHide = "$tag_housezone_display_hide";

	public const string TagMsgDisplayOn = "$tag_housezone_display_enabled";

	public const string TagMsgDisplayOff = "$tag_housezone_display_disabled";

	public CircleProjector circleProjector = null;

	private static readonly List<BuildPieceNamedZone> s_allZones = new List<BuildPieceNamedZone>();

	private static readonly Queue<BuildPieceNamedZone> s_bfsQueue = new Queue<BuildPieceNamedZone>();

	private static float s_lastGlobalMessageTime = -999f;

	private static string s_lastGlobalMessageText = string.Empty;

	[Header("Trigger")]
	public CapsuleCollider m_triggerCollider;

	public bool m_createTriggerIfMissing = true;

	[Header("Switches")]
	public Switch m_nameSwitch;

	public Switch m_radiusSwitch;

	public Switch m_displaySwitch;

	[Header("Access")]
	public bool m_requireWardAccess = true;

	[Header("Message")]
	public bool m_playStinger = true;

	public bool m_showLeaveMessage = true;

	public float m_localZoneMessageCooldown = 4f;

	public float m_globalMessageCooldown = 2f;

	public float m_sameTextRepeatCooldown = 8f;

	public float m_presenceCheckInterval = 0.1f;

	[Header("Connections")]
	public float m_connectionCacheInterval = 2f;

	public bool m_propagateNameToConnectedZones = true;

	public bool m_autoInheritNameFromConnectedZones = true;

	[Header("Input")]
	public int m_nameCharacterLimit = 64;

	public int m_radiusCharacterLimit = 8;

	private ZNetView m_nview;

	private Piece m_piece;

	private EditMode m_editMode = EditMode.None;

	private bool m_localPlayerInside;

	private float m_lastLocalZoneMessageTime = -999f;

	private bool m_initialized;

	private bool m_tempChecked;

	private string m_lastEnteredResolvedName = string.Empty;

	private float m_nextPresenceCheckTime = -999f;

	private readonly List<BuildPieceNamedZone> m_connectedZonesCache = new List<BuildPieceNamedZone>();

	private float m_connectedZonesCacheTime = -999f;

	private void Awake()
	{
		m_nview = ((Component)this).GetComponent<ZNetView>();
		m_piece = ((Component)this).GetComponent<Piece>();
		if (!s_allZones.Contains(this))
		{
			s_allZones.Add(this);
		}
		if ((Object)(object)m_nview != (Object)null && m_nview.IsValid())
		{
			m_nview.Register<string>("RPC_BPNamedZone_SetName", (Action<long, string>)RPC_SetName);
			m_nview.Register<int>("RPC_BPNamedZone_SetRadius", (Action<long, int>)RPC_SetRadius);
		}
		EnsureCircleProjectorReference();
		SetupSwitches();
		EnsureTrigger();
		if (IsValid() && m_nview.IsOwner())
		{
			ZDO zDO = m_nview.GetZDO();
			int @int = zDO.GetInt("bp_named_zone_radius", 0);
			if (!IsRadiusAllowed(@int))
			{
				zDO.Set("bp_named_zone_radius", 15);
			}
		}
		ApplyRadiusVisuals(GetRadius());
		RefreshAreaMarkerDefaultState();
		((MonoBehaviour)this).InvokeRepeating("DelayedInitialize", 0.5f, 1f);
	}

	private void OnEnable()
	{
		EnsureCircleProjectorReference();
		SetupSwitches();
		EnsureTrigger();
		ApplyRadiusVisuals(GetRadius());
		RefreshAreaMarkerDefaultState();
	}

	private void Start()
	{
		RefreshAreaMarkerDefaultState();
	}

	private void Update()
	{
		if (!(Time.time < m_nextPresenceCheckTime))
		{
			m_nextPresenceCheckTime = Time.time + m_presenceCheckInterval;
			UpdateLocalPlayerPresence();
		}
	}

	private void OnDestroy()
	{
		s_allZones.Remove(this);
		((MonoBehaviour)this).CancelInvoke();
	}

	private void SetupSwitches()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Expected O, but got Unknown
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Expected O, but got Unknown
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Expected O, but got Unknown
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Expected O, but got Unknown
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Expected O, but got Unknown
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Expected O, but got Unknown
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Expected O, but got Unknown
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Expected O, but got Unknown
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Expected O, but got Unknown
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Expected O, but got Unknown
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Expected O, but got Unknown
		if ((Object)(object)m_nameSwitch != (Object)null)
		{
			Switch nameSwitch = m_nameSwitch;
			nameSwitch.m_onUse = (Callback)Delegate.Remove((Delegate?)(object)nameSwitch.m_onUse, (Delegate?)new Callback(OnUseNameSwitch));
			Switch nameSwitch2 = m_nameSwitch;
			nameSwitch2.m_onUse = (Callback)Delegate.Combine((Delegate?)(object)nameSwitch2.m_onUse, (Delegate?)new Callback(OnUseNameSwitch));
			m_nameSwitch.m_onHover = new TooltipCallback(GetNameSwitchHoverText);
		}
		if ((Object)(object)m_radiusSwitch != (Object)null)
		{
			Switch radiusSwitch = m_radiusSwitch;
			radiusSwitch.m_onUse = (Callback)Delegate.Remove((Delegate?)(object)radiusSwitch.m_onUse, (Delegate?)new Callback(OnUseRadiusSwitch));
			Switch radiusSwitch2 = m_radiusSwitch;
			radiusSwitch2.m_onUse = (Callback)Delegate.Combine((Delegate?)(object)radiusSwitch2.m_onUse, (Delegate?)new Callback(OnUseRadiusSwitch));
			m_radiusSwitch.m_onHover = new TooltipCallback(GetRadiusSwitchHoverText);
		}
		if ((Object)(object)m_displaySwitch != (Object)null)
		{
			Switch displaySwitch = m_displaySwitch;
			displaySwitch.m_onUse = (Callback)Delegate.Remove((Delegate?)(object)displaySwitch.m_onUse, (Delegate?)new Callback(OnUseDisplaySwitch));
			Switch displaySwitch2 = m_displaySwitch;
			displaySwitch2.m_onUse = (Callback)Delegate.Combine((Delegate?)(object)displaySwitch2.m_onUse, (Delegate?)new Callback(OnUseDisplaySwitch));
			m_displaySwitch.m_onHover = new TooltipCallback(GetDisplaySwitchHoverText);
		}
	}

	private void DelayedInitialize()
	{
		if (m_initialized)
		{
			((MonoBehaviour)this).CancelInvoke("DelayedInitialize");
			return;
		}
		m_initialized = true;
		EnsureCircleProjectorReference();
		SetupSwitches();
		EnsureTrigger();
		ApplyRadiusVisuals(GetRadius());
		if (m_autoInheritNameFromConnectedZones)
		{
			TryInheritNameFromConnectedZones();
		}
		RefreshAreaMarkerDefaultState();
		((MonoBehaviour)this).CancelInvoke("DelayedInitialize");
	}

	private void EnsureTrigger()
	{
		if ((Object)(object)m_triggerCollider != (Object)null)
		{
			ConfigureTriggerCollider(m_triggerCollider);
			return;
		}
		CapsuleCollider val = ((Component)this).GetComponentInChildren<CapsuleCollider>(true);
		if ((Object)(object)val == (Object)null && m_createTriggerIfMissing)
		{
			val = ((Component)this).gameObject.AddComponent<CapsuleCollider>();
			val.height = 20f;
		}
		m_triggerCollider = val;
		if ((Object)(object)m_triggerCollider != (Object)null)
		{
			ConfigureTriggerCollider(m_triggerCollider);
		}
	}

	private void ConfigureTriggerCollider(CapsuleCollider capsule)
	{
		if (!((Object)(object)capsule == (Object)null))
		{
			((Collider)capsule).isTrigger = true;
		}
	}

	private void EnsureCircleProjectorReference()
	{
		if (!((Object)(object)circleProjector != (Object)null))
		{
			Transform val = ((Component)this).transform.Find("AreaMarker");
			if ((Object)(object)val != (Object)null)
			{
				circleProjector = ((Component)val).GetComponent<CircleProjector>();
			}
			if ((Object)(object)circleProjector == (Object)null)
			{
				circleProjector = ((Component)this).GetComponentInChildren<CircleProjector>(true);
			}
		}
	}

	private void RefreshAreaMarkerDefaultState()
	{
		EnsureCircleProjectorReference();
		if (!((Object)(object)circleProjector == (Object)null))
		{
			bool areaMarkerVisible = !IsPlacedAndInitialized();
			SetAreaMarkerVisible(areaMarkerVisible);
		}
	}

	private bool IsPlacedAndInitialized()
	{
		return IsValid() && m_initialized;
	}

	private void SetAreaMarkerVisible(bool visible)
	{
		EnsureCircleProjectorReference();
		if (!((Object)(object)circleProjector == (Object)null))
		{
			GameObject gameObject = ((Component)circleProjector).gameObject;
			if ((Object)(object)gameObject != (Object)null && gameObject.activeSelf != visible)
			{
				gameObject.SetActive(visible);
			}
		}
	}

	private bool IsAreaMarkerVisible()
	{
		EnsureCircleProjectorReference();
		return (Object)(object)circleProjector != (Object)null && (Object)(object)((Component)circleProjector).gameObject != (Object)null && ((Component)circleProjector).gameObject.activeSelf;
	}

	private void UpdateLocalPlayerPresence()
	{
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || (Object)(object)m_triggerCollider == (Object)null)
		{
			return;
		}
		bool flag = IsPlayerInsideZone(localPlayer);
		if (flag != m_localPlayerInside)
		{
			m_localPlayerInside = flag;
			if (flag)
			{
				m_lastEnteredResolvedName = GetResolvedNetworkName();
				TryShowEnterMessage();
			}
			else
			{
				TryShowLeaveMessage();
				m_lastEnteredResolvedName = string.Empty;
			}
		}
	}

	private bool IsPlayerInsideZone(Player player)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: 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_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: 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_0055: 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_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: 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_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player == (Object)null || (Object)(object)m_triggerCollider == (Object)null || !((Collider)m_triggerCollider).enabled)
		{
			return false;
		}
		Vector3 position = ((Component)player).transform.position;
		Vector3 point = position + Vector3.up * 0.9f;
		Vector3 point2 = position + Vector3.up * 1.6f;
		return IsPointInsideTrigger(position) || IsPointInsideTrigger(point) || IsPointInsideTrigger(point2);
	}

	private bool IsPointInsideTrigger(Vector3 point)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)m_triggerCollider == (Object)null)
		{
			return false;
		}
		Vector3 val = ((Collider)m_triggerCollider).ClosestPoint(point);
		Vector3 val2 = val - point;
		return ((Vector3)(ref val2)).sqrMagnitude <= 0.0001f;
	}

	private static bool IsRadiusAllowed(int radius)
	{
		return radius >= 1 && radius <= 50;
	}

	private void ApplyRadiusToTrigger(int radius)
	{
		if (!((Object)(object)m_triggerCollider == (Object)null))
		{
			m_triggerCollider.radius = radius;
		}
	}

	private void ApplyRadiusToProjector(int radius)
	{
		EnsureCircleProjectorReference();
		if (!((Object)(object)circleProjector == (Object)null))
		{
			circleProjector.m_radius = radius;
			circleProjector.m_nrOfSegments = Mathf.Max(circleProjector.m_nrOfSegments, 1);
		}
	}

	private void ApplyRadiusVisuals(int radius)
	{
		ApplyRadiusToTrigger(radius);
		ApplyRadiusToProjector(radius);
	}

	private bool OnUseNameSwitch(Switch sw, Humanoid user, ItemData item)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (!IsValid())
		{
			return false;
		}
		if (m_requireWardAccess && !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return true;
		}
		if ((Object)(object)TextInput.instance == (Object)null)
		{
			return false;
		}
		m_editMode = EditMode.Name;
		TextInput.instance.RequestText((TextReceiver)(object)this, Localize("$tag_housezone_input_name_title"), m_nameCharacterLimit);
		return true;
	}

	private bool OnUseRadiusSwitch(Switch sw, Humanoid user, ItemData item)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (!IsValid())
		{
			return false;
		}
		if (m_requireWardAccess && !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return true;
		}
		if ((Object)(object)TextInput.instance == (Object)null)
		{
			return false;
		}
		m_editMode = EditMode.Radius;
		TextInput.instance.RequestText((TextReceiver)(object)this, Localize("$tag_housezone_input_radius_title"), m_radiusCharacterLimit);
		return true;
	}

	private bool OnUseDisplaySwitch(Switch sw, Humanoid user, ItemData item)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (!IsValid())
		{
			return false;
		}
		if (m_requireWardAccess && !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return true;
		}
		EnsureCircleProjectorReference();
		if ((Object)(object)circleProjector == (Object)null)
		{
			return false;
		}
		bool flag = !IsAreaMarkerVisible();
		SetAreaMarkerVisible(flag);
		ShowCenterMessage(flag ? "$tag_housezone_display_enabled" : "$tag_housezone_display_disabled");
		return true;
	}

	private string GetPieceName()
	{
		return ((Object)(object)m_piece != (Object)null) ? m_piece.m_name : string.Empty;
	}

	private string GetNameSwitchHoverText()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		string zoneName = GetZoneName();
		string text = GetPieceName() + ": " + GetDisplayName() + "\n[<color=yellow><b>$KEY_Use</b></color>] $tag_housezone_set_name";
		return Localize(text);
	}

	private string GetRadiusSwitchHoverText()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		int radius = GetRadius();
		string text = GetPieceName() + ": " + GetDisplayName() + "\n[<color=yellow><b>$KEY_Use</b></color>] $tag_housezone_set_radius <color=yellow><b>Radius: </b></color>" + radius.ToString(CultureInfo.InvariantCulture) + "/" + 50.ToString(CultureInfo.InvariantCulture);
		return Localize(text);
	}

	private string GetDisplaySwitchHoverText()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		bool flag = IsAreaMarkerVisible();
		string text = (flag ? "$tag_housezone_display_on" : "$tag_housezone_display_off");
		string text2 = (flag ? "$tag_housezone_display_hide" : "$tag_housezone_display_show");
		string text3 = GetPieceName() + ": " + GetDisplayName() + "\n[<color=yellow><b>$KEY_Use</b></color>] " + text2 + "\n";
		return Localize(text3);
	}

	public string GetText()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		if (m_editMode == EditMode.Name)
		{
			return GetZoneNameRaw();
		}
		if (m_editMode == EditMode.Radius)
		{
			return GetRadius().ToString(CultureInfo.InvariantCulture);
		}
		return string.Empty;
	}

	public void SetText(string text)
	{
		if (IsValid())
		{
			if (m_editMode == EditMode.Name)
			{
				SetNameFromInput(text);
			}
			else if (m_editMode == EditMode.Radius)
			{
				SetRadiusFromInput(text);
			}
			m_editMode = EditMode.None;
		}
	}

	private void SetNameFromInput(string text)
	{
		string text2 = (text ?? string.Empty).Trim();
		if (string.IsNullOrEmpty(text2))
		{
			ShowCenterMessage("$tag_housezone_name_empty");
			return;
		}
		if (text2.Length > m_nameCharacterLimit)
		{
			text2 = text2.Substring(0, m_nameCharacterLimit);
		}
		m_nview.InvokeRPC("RPC_BPNamedZone_SetName", new object[1] { text2 });
		ShowCenterMessage("$tag_housezone_name_set: " + text2);
	}

	private void SetRadiusFromInput(string text)
	{
		string s = (text ?? string.Empty).Trim();
		if (!int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
		{
			ShowCenterMessage("$tag_housezone_radius_not_int");
			return;
		}
		if (!IsRadiusAllowed(result))
		{
			ShowCenterMessage("$tag_housezone_radius_invalid");
			return;
		}
		ApplyRadiusVisuals(result);
		m_nview.InvokeRPC("RPC_BPNamedZone_SetRadius", new object[1] { result });
		ShowCenterMessage("$tag_housezone_radius_set: " + result.ToString(CultureInfo.InvariantCulture) + "m");
	}

	private void RPC_SetName(long sender, string name)
	{
		if (IsValid() && m_nview.IsOwner())
		{
			string text = (name ?? string.Empty).Trim();
			if (text.Length > m_nameCharacterLimit)
			{
				text = text.Substring(0, m_nameCharacterLimit);
			}
			m_nview.GetZDO().Set("bp_named_zone_name", text);
			if (m_propagateNameToConnectedZones && !string.IsNullOrEmpty(text))
			{
				PropagateNameToConnectedZones(text);
			}
			InvalidateConnectionCacheAroundThis();
		}
	}

	private void RPC_SetRadius(long sender, int radius)
	{
		if (IsValid() && m_nview.IsOwner() && IsRadiusAllowed(radius))
		{
			m_nview.GetZDO().Set("bp_named_zone_radius", radius);
			ApplyRadiusVisuals(radius);
			InvalidateConnectionCacheAroundThis();
			if (m_autoInheritNameFromConnectedZones && string.IsNullOrEmpty(GetZoneNameRaw()))
			{
				TryInheritNameFromConnectedZones();
			}
		}
	}

	public bool IsValid()
	{
		return (Object)(object)m_nview != (Object)null && m_nview.IsValid() && m_nview.GetZDO() != null;
	}

	public int GetRadius()
	{
		if (!IsValid())
		{
			return 15;
		}
		int @int = m_nview.GetZDO().GetInt("bp_named_zone_radius", 15);
		if (!IsRadiusAllowed(@int))
		{
			return 15;
		}
		return @int;
	}

	public string GetZoneNameRaw()
	{
		if (!IsValid())
		{
			return string.Empty;
		}
		return m_nview.GetZDO().GetString("bp_named_zone_name", string.Empty);
	}

	public string GetZoneName()
	{
		return GetZoneNameRaw();
	}

	public string GetDisplayName()
	{
		string resolvedNetworkName = GetResolvedNetworkName();
		if (!string.IsNullOrEmpty(resolvedNetworkName))
		{
			return resolvedNetworkName;
		}
		if ((Object)(object)m_piece != (Object)null)
		{
			return Localization.instance.Localize(m_piece.m_name);
		}
		return Localize("$tag_housezone_default_name");
	}

	private void TryShowEnterMessage()
	{
		string resolvedNetworkName = GetResolvedNetworkName();
		if (!string.IsNullOrWhiteSpace(resolvedNetworkName))
		{
			float time = Time.time;
			if (!(time - m_lastLocalZoneMessageTime < m_localZoneMessageCooldown) && !(time - s_lastGlobalMessageTime < m_globalMessageCooldown) && (!(s_lastGlobalMessageText == resolvedNetworkName) || !(time - s_lastGlobalMessageTime < m_sameTextRepeatCooldown)))
			{
				m_lastLocalZoneMessageTime = time;
				s_lastGlobalMessageTime = time;
				s_lastGlobalMessageText = resolvedNetworkName;
				ShowBiomeLikeMessage(resolvedNetworkName, m_playStinger);
			}
		}
	}

	private void TryShowLeaveMessage()
	{
		if (m_showLeaveMessage)
		{
			string value = m_lastEnteredResolvedName;
			if (string.IsNullOrWhiteSpace(value))
			{
				value = GetResolvedNetworkName();
			}
			if (!string.IsNullOrWhiteSpace(value))
			{
			}
		}
	}

	private void ShowBiomeLikeMessage(string text, bool playStinger)
	{
		if (!string.IsNullOrWhiteSpace(text))
		{
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowBiomeFoundMsg(Localize(text), playStinger);
			}
			else
			{
				ShowCenterMessage(text);
			}
		}
	}

	private void ShowCenterMessage(string text)
	{
		if ((Object)(object)Player.m_localPlayer != (Object)null)
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, Localize(text), 0, (Sprite)null);
		}
	}

	private string Localize(string text)
	{
		if (string.IsNullOrEmpty(text))
		{
			return string.Empty;
		}
		if (Localization.instance == null)
		{
			return text;
		}
		return Localization.instance.Localize(text);
	}

	private bool Overlaps(BuildPieceNamedZone other)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)other == (Object)null || (Object)(object)other == (Object)(object)this)
		{
			return false;
		}
		float num = Utils.DistanceXZ(((Component)this).transform.position, ((Component)other).transform.position);
		return num <= (float)(GetRadius() + other.GetRadius());
	}

	private void InvalidateOwnConnectionCache()
	{
		m_connectedZonesCacheTime = -999f;
	}

	private void InvalidateConnectionCacheAroundThis()
	{
		InvalidateOwnConnectionCache();
		for (int i = 0; i < s_allZones.Count; i++)
		{
			BuildPieceNamedZone buildPieceNamedZone = s_allZones[i];
			if (!((Object)(object)buildPieceNamedZone == (Object)null) && ((Object)(object)buildPieceNamedZone == (Object)(object)this || Overlaps(buildPieceNamedZone)))
			{
				buildPieceNamedZone.InvalidateOwnConnectionCache();
			}
		}
	}

	private List<BuildPieceNamedZone> GetConnectedZones(bool forceUpdate)
	{
		if (!forceUpdate && Time.time - m_connectedZonesCacheTime <= m_connectionCacheInterval)
		{
			return m_connectedZonesCache;
		}
		m_connectedZonesCache.Clear();
		for (int i = 0; i < s_allZones.Count; i++)
		{
			BuildPieceNamedZone buildPieceNamedZone = s_allZones[i];
			if ((Object)(object)buildPieceNamedZone != (Object)null)
			{
				buildPieceNamedZone.m_tempChecked = false;
			}
		}
		s_bfsQueue.Clear();
		m_tempChecked = true;
		s_bfsQueue.Enqueue(this);
		while (s_bfsQueue.Count > 0)
		{
			BuildPieceNamedZone buildPieceNamedZone2 = s_bfsQueue.Dequeue();
			for (int j = 0; j < s_allZones.Count; j++)
			{
				BuildPieceNamedZone buildPieceNamedZone3 = s_allZones[j];
				if (!((Object)(object)buildPieceNamedZone3 == (Object)null) && !buildPieceNamedZone3.m_tempChecked && buildPieceNamedZone3.IsValid() && buildPieceNamedZone2.Overlaps(buildPieceNamedZone3))
				{
					buildPieceNamedZone3.m_tempChecked = true;
					s_bfsQueue.Enqueue(buildPieceNamedZone3);
					m_connectedZonesCache.Add(buildPieceNamedZone3);
				}
			}
		}
		m_connectedZonesCacheTime = Time.time;
		return m_connectedZonesCache;
	}

	private BuildPieceNamedZone FindBestNamedConnectedZone()
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		BuildPieceNamedZone result = null;
		float num = float.MaxValue;
		List<BuildPieceNamedZone> connectedZones = GetConnectedZones(forceUpdate: true);
		for (int i = 0; i < connectedZones.Count; i++)
		{
			BuildPieceNamedZone buildPieceNamedZone = connectedZones[i];
			if ((Object)(object)buildPieceNamedZone == (Object)null)
			{
				continue;
			}
			string zoneNameRaw = buildPieceNamedZone.GetZoneNameRaw();
			if (!string.IsNullOrWhiteSpace(zoneNameRaw))
			{
				float num2 = Utils.DistanceXZ(((Component)this).transform.position, ((Component)buildPieceNamedZone).transform.position);
				if (num2 < num)
				{
					num = num2;
					result = buildPieceNamedZone;
				}
			}
		}
		return result;
	}

	private string GetResolvedNetworkName()
	{
		string zoneName = GetZoneName();
		if (!string.IsNullOrWhiteSpace(zoneName))
		{
			return zoneName;
		}
		BuildPieceNamedZone buildPieceNamedZone = FindBestNamedConnectedZone();
		if ((Object)(object)buildPieceNamedZone != (Object)null)
		{
			return buildPieceNamedZone.GetZoneName();
		}
		return string.Empty;
	}

	private void TryInheritNameFromConnectedZones()
	{
		if (!IsValid() || !m_nview.IsOwner() || !string.IsNullOrWhiteSpace(GetZoneNameRaw()))
		{
			return;
		}
		BuildPieceNamedZone buildPieceNamedZone = FindBestNamedConnectedZone();
		if (!((Object)(object)buildPieceNamedZone == (Object)null))
		{
			string zoneNameRaw = buildPieceNamedZone.GetZoneNameRaw();
			if (!string.IsNullOrWhiteSpace(zoneNameRaw))
			{
				m_nview.GetZDO().Set("bp_named_zone_name", zoneNameRaw);
				InvalidateConnectionCacheAroundThis();
			}
		}
	}

	private void PropagateNameToConnectedZones(string newName)
	{
		if (string.IsNullOrWhiteSpace(newName))
		{
			return;
		}
		if (IsValid() && m_nview.IsOwner())
		{
			m_nview.GetZDO().Set("bp_named_zone_name", newName);
		}
		List<BuildPieceNamedZone> connectedZones = GetConnectedZones(forceUpdate: true);
		for (int i = 0; i < connectedZones.Count; i++)
		{
			BuildPieceNamedZone buildPieceNamedZone = connectedZones[i];
			if (!((Object)(object)buildPieceNamedZone == (Object)null) && buildPieceNamedZone.IsValid() && buildPieceNamedZone.m_nview.IsOwner())
			{
				buildPieceNamedZone.m_nview.GetZDO().Set("bp_named_zone_name", newName);
				buildPieceNamedZone.InvalidateOwnConnectionCache();
			}
		}
		InvalidateOwnConnectionCache();
	}
}
namespace BalrondHearthMarks
{
	public class BalrondTranslator
	{
		public static Dictionary<string, Dictionary<string, string>> translations = new Dictionary<string, Dictionary<string, string>>();

		public static Dictionary<string, string> getLanguage(string language)
		{
			if (string.IsNullOrEmpty(language))
			{
				return null;
			}
			if (translations.TryGetValue(language, out var value))
			{
				return value;
			}
			return null;
		}
	}
	public class ShaderReplacment
	{
		public static List<GameObject> prefabsToReplaceShader = new List<GameObject>();

		public static List<Material> materialsInPrefabs = new List<Material>();

		public string[] shaderlist = new string[49]
		{
			"Custom/AlphaParticle", "Custom/Blob", "Custom/Bonemass", "Custom/Clouds", "Custom/Creature", "Custom/Decal", "Custom/Distortion", "Custom/Flow", "Custom/FlowOpaque", "Custom/Grass",
			"Custom/GuiScroll", "Custom/Heightmap", "Custom/icon", "Custom/InteriorSide", "Custom/LitGui", "Custom/LitParticles", "Custom/mapshader", "Custom/ParticleDecal", "Custom/Piece", "Custom/Player",
			"Custom/Rug", "Custom/ShadowBlob", "Custom/SkyboxProcedural", "Custom/SkyObject", "Custom/StaticRock", "Custom/Tar", "Custom/Trilinearmap", "Custom/UI/BGBlur", "Custom/Vegetation", "Custom/Water",
			"Custom/WaterBottom", "Custom/WaterMask", "Custom/Yggdrasil", "Custom/Yggdrasil/root", "Hidden/BlitCopyHDRTonemap", "Hidden/Dof/DepthOfFieldHdr", "Hidden/Dof/DX11Dof", "Hidden/Internal-Loading", "Hidden/Internal-UIRDefaultWorld", "Hidden/SimpleClear",
			"Hidden/SunShaftsComposite", "Lux Lit Particles/ Bumped", "Lux Lit Particles/ Tess Bumped", "Particles/Standard Surface2", "Particles/Standard Unlit2", "Standard TwoSided", "ToonDeferredShading2017", "Unlit/DepthWrite", "Unlit/Lighting"
		};

		public static List<Shader> shaders = new List<Shader>();

		private static readonly HashSet<Shader> CachedShaders = new HashSet<Shader>();

		public static bool debug = true;

		public static Shader findShader(string name)
		{
			Shader[] array = Resources.FindObjectsOfTypeAll<Shader>();
			if (array.Length == 0)
			{
				Debug.LogWarning((object)"SHADER LIST IS EMPTY!");
				return null;
			}
			if (debug)
			{
			}
			return shaders.Find((Shader x) => ((Object)x).name == name);
		}

		public static Shader GetShaderByName(string name)
		{
			return shaders.Find((Shader x) => ((Object)x).name == name.Trim());
		}

		public static void debugShaderList(List<Shader> shadersRes)
		{
			foreach (Shader shadersRe in shadersRes)
			{
				Debug.LogWarning((object)("SHADER NAME IS: " + ((Object)shadersRe).name));
			}
			debug = false;
		}

		public static void Replace(GameObject gameObject)
		{
			prefabsToReplaceShader.Add(gameObject);
			GetMaterialsInPrefab(gameObject);
		}

		public static void GetMaterialsInPrefab(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(true);
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				Material[] sharedMaterials = val.sharedMaterials;
				if (sharedMaterials == null || sharedMaterials.Length == 0)
				{
					continue;
				}
				Material[] array2 = sharedMaterials;
				foreach (Material val2 in array2)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						materialsInPrefabs.Add(val2);
					}
				}
			}
		}

		public static void getMeShaders()
		{
			AssetBundle[] array = Resources.FindObjectsOfTypeAll<AssetBundle>();
			AssetBundle[] array2 = array;
			foreach (AssetBundle val in array2)
			{
				IEnumerable<Shader> enumerable3;
				try
				{
					IEnumerable<Shader> enumerable2;
					if (!val.isStreamedSceneAssetBundle || !Object.op_Implicit((Object)(object)val))
					{
						IEnumerable<Shader> enumerable = val.LoadAllAssets<Shader>();
						enumerable2 = enumerable;
					}
					else
					{
						enumerable2 = from shader in ((IEnumerable<string>)val.GetAllAssetNames()).Select((Func<string, Shader>)val.LoadAsset<Shader>)
							where (Object)(object)shader != (Object)null
							select shader;
					}
					enumerable3 = enumerable2;
				}
				catch (Exception)
				{
					continue;
				}
				if (enumerable3 == null)
				{
					continue;
				}
				foreach (Shader item in enumerable3)
				{
					CachedShaders.Add(item);
				}
			}
		}

		public static void runMaterialFix()
		{
			getMeShaders();
			shaders.AddRange(CachedShaders);
			foreach (Material materialsInPrefab in materialsInPrefabs)
			{
				Shader shader = materialsInPrefab.shader;
				if (!((Object)(object)shader == (Object)null))
				{
					string name = ((Object)shader).name;
					if (!(name == "Standard") && name.Contains("Balrond"))
					{
						setProperValue(materialsInPrefab, name);
					}
				}
			}
		}

		private static void setProperValue(Material material, string shaderName)
		{
			string name = shaderName.Replace("Balrond", "Custom");
			name = checkNaming(name);
			Shader shaderByName = GetShaderByName(name);
			if ((Object)(object)shaderByName == (Object)null)
			{
				Debug.LogWarning((object)("Shader not found " + name));
			}
			else
			{
				material.shader = shaderByName;
			}
		}

		private static string checkNaming(string name)
		{
			string result = name;
			if (name.Contains("Bumped"))
			{
				result = name.Replace("Custom", "Lux Lit Particles");
			}
			if (name.Contains("Tess Bumped"))
			{
				result = name.Replace("Custom", "Lux Lit Particles");
			}
			if (name.Contains("Standard Surface"))
			{
				result = name.Replace("Custom", "Particles");
				result = result.Replace("Standard Surface2", "Standard Surface");
			}
			if (name.Contains("Standard Unlit"))
			{
				result = name.Replace("Custom", "Particles");
				result = result.Replace("Standard Unlit", "Standard Unlit2");
				result = result.Replace("Standard Unlit22", "Standard Unlit2");
			}
			return result;
		}
	}
	public class JsonLoader
	{
		public string defaultPath = string.Empty;

		public void loadJson()
		{
			LoadTranslations();
			justDefaultPath();
		}

		public void justDefaultPath()
		{
			string configPath = Paths.ConfigPath;
			string text = Path.Combine(configPath, "BalrondHearthMarks-translation/");
			defaultPath = text;
		}

		public void createDefaultPath()
		{
			string configPath = Paths.ConfigPath;
			string text = Path.Combine(configPath, "BalrondHearthMarks-translation/");
			if (!Directory.Exists(text))
			{
				CreateFolder(text);
			}
			else
			{
				Debug.Log((object)("BalrondHearthMarks: Folder already exists: " + text));
			}
			defaultPath = text;
		}

		private string[] jsonFilePath(string folderName, string extension)
		{
			string configPath = Paths.ConfigPath;
			string text = Path.Combine(configPath, "BalrondHearthMarks-translation/");
			if (!Directory.Exists(text))
			{
				CreateFolder(text);
			}
			else
			{
				Debug.Log((object)("BalrondHearthMarks: Folder already exists: " + text));
			}
			string[] files = Directory.GetFiles(text, extension);
			Debug.Log((object)("BalrondHearthMarks:" + folderName + " Json Files Found: " + files.Length));
			return files;
		}

		private static void CreateFolder(string path)
		{
			try
			{
				Directory.CreateDirectory(path);
				Debug.Log((object)"BalrondHearthMarks: Folder created successfully.");
			}
			catch (Exception ex)
			{
				Debug.Log((object)("BalrondHearthMarks: Error creating folder: " + ex.Message));
			}
		}

		private void LoadTranslations()
		{
			int num = 0;
			string[] array = jsonFilePath("Translation", "*.json");
			foreach (string text in array)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
				string json = File.ReadAllText(text);
				JsonData jsonData = JsonMapper.ToObject(json);
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				foreach (string key in jsonData.Keys)
				{
					dictionary[key] = jsonData[key].ToString();
				}
				if (dictionary != null)
				{
					BalrondTranslator.translations.Add(fileNameWithoutExtension, dictionary);
					Debug.Log((object)("BalrondHearthMarks: Json Files Language: " + fileNameWithoutExtension));
					num++;
				}
				else
				{
					Debug.LogError((object)("BalrondHearthMarks: Loading FAILED file: " + text));
				}
			}
			Debug.Log((object)("BalrondHearthMarks: Translation JsonFiles Loaded: " + num));
		}
	}
	[BepInPlugin("balrond.astafaraios.BalrondHearthMarks", "BalrondHearthMarks", "1.0.1")]
	public class Launch : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ZNetScene_Awake_Patch
		{
			private static void Prefix(ZNetScene __instance)
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				GameObject val = __instance.m_prefabs.Find((GameObject x) => ((Object)x).name == "Hammer");
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				ItemDrop component = val.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null)
				{
					return;
				}
				PieceTable buildPieces = component.m_itemData.m_shared.m_buildPieces;
				if ((Object)(object)buildPieces == (Object)null)
				{
					return;
				}
				foreach (GameObject prefab in prefabs)
				{
					if (!((Object)(object)prefab == (Object)null))
					{
						ShaderReplacment.Replace(prefab);
						if (((Object)prefab).name == "piece_hearthmark_bal")
						{
							SetupHearthMark(prefab, __instance);
							CreateHearthMarkRecipe(prefab, __instance);
						}
						if (((Object)prefab).name == "piece_standsign_bal")
						{
							CreateSignStandRecipe(prefab, __instance);
						}
						if (!buildPieces.m_pieces.Any((GameObject x) => (Object)(object)x != (Object)null && ((Object)x).name == ((Object)prefab).name))
						{
							buildPieces.m_pieces.Add(prefab);
						}
						if (!__instance.m_prefabs.Any((GameObject x) => (Object)(object)x != (Object)null && ((Object)x).name == ((Object)prefab).name))
						{
							__instance.m_prefabs.Add(prefab);
						}
					}
				}
				ShaderReplacment.runMaterialFix();
			}
		}

		public const string PluginGUID = "balrond.astafaraios.BalrondHearthMarks";

		public const string PluginName = "BalrondHearthMarks";

		public const string PluginVersion = "1.0.1";

		public static JsonLoader jsonLoader = new JsonLoader();

		private readonly Harmony harmony = new Harmony("balrond.astafaraios.BalrondHearthMarks");

		private static AssetBundle assetBundle;

		private static readonly List<GameObject> prefabs = new List<GameObject>();

		private static readonly string[] bundleNames = new string[1] { "hearthmark" };

		private static readonly string[] prefabNames = new string[1] { "piece_hearthmark_bal" };

		private void Awake()
		{
			jsonLoader.loadJson();
			LoadAllAssetBundles();
			harmony.PatchAll();
		}

		private void OnDestroy()
		{
			harmony.UnpatchSelf();
		}

		private static void LoadAllAssetBundles()
		{
			string[] array = bundleNames;
			foreach (string filename in array)
			{
				assetBundle = GetAssetBundleFromResources(filename);
				if ((Object)(object)assetBundle != (Object)null)
				{
					LoadPrefabs(assetBundle);
				}
			}
		}

		private static AssetBundle GetAssetBundleFromResources(string filename)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text = executingAssembly.GetManifestResourceNames().SingleOrDefault((string str) => str.EndsWith(filename));
			if (string.IsNullOrEmpty(text))
			{
				Debug.LogError((object)("[BalrondHearthMarks] Missing embedded asset bundle: " + filename));
				return null;
			}
			using Stream stream = executingAssembly.GetManifestResourceStream(text);
			if (stream == null)
			{
				Debug.LogError((object)("[BalrondHearthMarks] Failed opening embedded asset bundle stream: " + filename));
				return null;
			}
			return AssetBundle.LoadFromStream(stream);
		}

		private static void LoadPrefabs(AssetBundle bundle)
		{
			if ((Object)(object)bundle == (Object)null)
			{
				return;
			}
			string[] array = prefabNames;
			foreach (string text in array)
			{
				GameObject prefab = bundle.LoadAsset<GameObject>("Assets/Custom/BalrondHearthMarks/Pieces/" + text + ".prefab");
				if ((Object)(object)prefab == (Object)null)
				{
					Debug.LogError((object)("[BalrondHearthMarks] Missing prefab in bundle: " + text));
					continue;
				}
				prefab.SetActive(true);
				if (!prefabs.Any((GameObject x) => (Object)(object)x != (Object)null && ((Object)x).name == ((Object)prefab).name))
				{
					prefabs.Add(prefab);
				}
			}
		}

		private static void SetupHearthMark(GameObject prefab, ZNetScene scene)
		{
			if (!((Object)(object)prefab == (Object)null) && !((Object)(object)scene == (Object)null))
			{
				EnsureZNetView(prefab);
				EnsurePiece(prefab);
				BalrondHearthMark balrondHearthMark = prefab.GetComponent<BalrondHearthMark>();
				if ((Object)(object)balrondHearthMark == (Object)null)
				{
					balrondHearthMark = prefab.AddComponent<BalrondHearthMark>();
				}
				GameObject val = scene.m_prefabs.Find((GameObject x) => ((Object)x).name == "guard_stone");
				PrivateArea val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<PrivateArea>() : null);
				Transform val3 = prefab.transform.Find("AreaMarker");
				Transform val4 = prefab.transform.Find("zone");
				Transform val5 = prefab.transform.Find("_enabled");
				Transform val6 = prefab.transform.Find("_disabled");
				balrondHearthMark.m_name = "$tag_hearthmark_name_bal";
				balrondHearthMark.m_radius = 15f;
				balrondHearthMark.m_updateConnectionsInterval = 2f;
				balrondHearthMark.m_requireWardAccess = true;
				balrondHearthMark.m_localZoneMessageCooldown = 4f;
				balrondHearthMark.m_globalMessageCooldown = 2f;
				balrondHearthMark.m_sameTextRepeatCooldown = 8f;
				balrondHearthMark.m_presenceCheckInterval = 0.1f;
				balrondHearthMark.m_nameCharacterLimit = 64;
				balrondHearthMark.m_radiusCharacterLimit = 8;
				balrondHearthMark.m_areaMarker = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<CircleProjector>() : prefab.GetComponentInChildren<CircleProjector>(true));
				balrondHearthMark.m_enabledVisual = (((Object)(object)val5 != (Object)null) ? ((Component)val5).gameObject : null);
				balrondHearthMark.m_disabledVisual = (((Object)(object)val6 != (Object)null) ? ((Component)val6).gameObject : null);
				balrondHearthMark.m_triggerCollider = (((Object)(object)val4 != (Object)null) ? ((Component)val4).GetComponent<CapsuleCollider>() : null);
				balrondHearthMark.m_createTriggerIfMissing = false;
				if ((Object)(object)balrondHearthMark.m_triggerCollider == (Object)null)
				{
					Debug.LogWarning((object)("[BalrondHearthMarks] Missing CapsuleCollider on child 'zone' in prefab '" + ((Object)prefab).name + "'."));
				}
				if ((Object)(object)val2 != (Object)null)
				{
					balrondHearthMark.m_connectEffect = val2.m_connectEffect;
					balrondHearthMark.m_inRangeEffect = val2.m_inRangeEffect;
					balrondHearthMark.m_enableEffect = val2.m_activateEffect;
					balrondHearthMark.m_disableEffect = val2.m_deactivateEffect;
				}
				SetupAreaMarker(balrondHearthMark);
				SetupTrigger(balrondHearthMark);
				SetupVisualStateObjects(balrondHearthMark);
			}
		}

		private static void SetupAreaMarker(BalrondHearthMark mark)
		{
			if (!((Object)(object)mark == (Object)null) && !((Object)(object)mark.m_areaMarker == (Object)null))
			{
				mark.m_areaMarker.m_radius = mark.m_radius;
				((Component)mark.m_areaMarker).gameObject.SetActive(false);
			}
		}

		private static void SetupTrigger(BalrondHearthMark mark)
		{
			if (!((Object)(object)mark == (Object)null) && !((Object)(object)mark.m_triggerCollider == (Object)null))
			{
				((Collider)mark.m_triggerCollider).isTrigger = true;
				mark.m_triggerCollider.radius = mark.m_radius;
			}
		}

		private static void SetupVisualStateObjects(BalrondHearthMark mark)
		{
			if (!((Object)(object)mark == (Object)null))
			{
				if ((Object)(object)mark.m_enabledVisual != (Object)null)
				{
					mark.m_enabledVisual.SetActive(true);
				}
				if ((Object)(object)mark.m_disabledVisual != (Object)null)
				{
					mark.m_disabledVisual.SetActive(false);
				}
			}
		}

		private static void EnsureZNetView(GameObject prefab)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)prefab.GetComponent<ZNetView>() != (Object)null))
			{
				ZNetView val = prefab.AddComponent<ZNetView>();
				val.m_persistent = true;
				val.m_type = (ObjectType)0;
			}
		}

		private static void EnsurePiece(GameObject prefab)
		{
			if ((Object)(object)prefab.GetComponent<Piece>() == (Object)null)
			{
				prefab.AddComponent<Piece>();
			}
		}

		private static void CreateHearthMarkRecipe(GameObject prefab, ZNetScene scene)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Piece component = prefab.GetComponent<Piece>();
			if (!((Object)(object)component == (Object)null))
			{
				component.m_name = "$tag_hearthmark_name_bal";
				component.m_description = "$piece_hearthtmark_bal_description";
				component.m_category = (PieceCategory)0;
				GameObject val = scene.m_prefabs.Find((GameObject x) => ((Object)x).name == "piece_workbench");
				if ((Object)(object)val != (Object)null)
				{
					component.m_craftingStation = val.GetComponent<CraftingStation>();
				}
				component.m_resources = ((IEnumerable<Requirement>)(object)new Requirement[4]
				{
					Requirement(scene, "Thunderstone", 1),
					Requirement(scene, "Feathers", 3),
					Requirement(scene, "FineWood", 2),
					Requirement(scene, "BoneFragments", 3)
				}).Where((Requirement x) => (Object)(object)x.m_resItem != (Object)null).ToArray();
			}
		}

		private static void CreateSignStandRecipe(GameObject prefab, ZNetScene scene)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Piece component = prefab.GetComponent<Piece>();
			if (!((Object)(object)component == (Object)null))
			{
				component.m_name = "$piece_standsign_bal";
				component.m_description = "";
				component.m_category = (PieceCategory)0;
				GameObject val = scene.m_prefabs.Find((GameObject x) => ((Object)x).name == "forge");
				if ((Object)(object)val != (Object)null)
				{
					component.m_craftingStation = val.GetComponent<CraftingStation>();
				}
				component.m_resources = ((IEnumerable<Requirement>)(object)new Requirement[3]
				{
					Requirement(scene, "Copper", 2),
					Requirement(scene, "FineWood", 6),
					Requirement(scene, "Coal", 1)
				}).Where((Requirement x) => (Object)(object)x.m_resItem != (Object)null).ToArray();
			}
		}

		private static Requirement Requirement(ZNetScene scene, string prefabName, int amount)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			GameObject val = scene.m_prefabs.Find((GameObject x) => ((Object)x).name == prefabName);
			return new Requirement
			{
				m_amount = amount,
				m_recover = true,
				m_resItem = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null)
			};
		}
	}
	[HarmonyPatch]
	internal static class TranslationPatches
	{
		[HarmonyPatch(typeof(FejdStartup), "SetupGui")]
		private class FejdStartup_SetupGUI
		{
			private static void Postfix()
			{
				string selectedLanguage = Localization.instance.GetSelectedLanguage();
				Dictionary<string, string> translations = GetTranslations(selectedLanguage);
				AddTranslations(translations);
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Localization), "SetupLanguage")]
		private class Translation_SetupLanguage
		{
			private static void Prefix(Localization __instance, string language)
			{
				Dictionary<string, string> translations = GetTranslations(language);
				AddTranslations(translations, __instance);
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Localization), "LoadCSV")]
		private class Translation_LoadCSV
		{
			private static void Prefix(Localization __instance, string language)
			{
				Dictionary<string, string> translations = GetTranslations(language);
				AddTranslations(translations, __instance);
			}
		}

		private static Dictionary<string, string> GetTranslations(string language)
		{
			Dictionary<string, string> result = BalrondTranslator.getLanguage("English");
			if (!string.Equals(language, "English", StringComparison.OrdinalIgnoreCase))
			{
				Dictionary<string, string> language2 = BalrondTranslator.getLanguage(language);
				if (language2 != null)
				{
					result = language2;
				}
				else
				{
					Debug.Log((object)("BalrondHearthMarks: Did not find translation file for '" + language + "', loading English"));
				}
			}
			return result;
		}

		private static void AddTranslations(Dictionary<string, string> translations, Localization localizationInstance = null)
		{
			if (translations == null)
			{
				Debug.LogWarning((object)"BalrondHearthMarks: No translation file found!");
				return;
			}
			if (localizationInstance != null)
			{
				foreach (KeyValuePair<string, string> translation in translations)
				{
					localizationInstance.AddWord(translation.Key, translation.Value);
				}
				return;
			}
			foreach (KeyValuePair<string, string> translation2 in translations)
			{
				Localization.instance.AddWord(translation2.Key, translation2.Value);
			}
		}
	}
}
namespace LitJson2
{
	internal enum JsonType
	{
		None,
		Object,
		Array,
		String,
		Int,
		Long,
		Double,
		Boolean
	}
	internal interface IJsonWrapper : IList, IOrderedDictionary, IDictionary, ICollection, IEnumerable
	{
		bool IsArray { get; }

		bool IsBoolean { get; }

		bool IsDouble { get; }

		bool IsInt { get; }

		bool IsLong { get; }

		bool IsObject { get; }

		bool IsString { get; }

		bool GetBoolean();

		double GetDouble();

		int GetInt();

		JsonType GetJsonType();

		long GetLong();

		string GetString();

		void SetBoolean(bool val);

		void SetDouble(double val);

		void SetInt(int val);

		void SetJsonType(JsonType type);

		void SetLong(long val);

		void SetString(string val);

		string ToJson();

		void ToJson(JsonWriter writer);
	}
	internal class JsonData : IJsonWrapper, IList, IOrderedDictionary, IDictionary, ICollection, IEnumerable, IEquatable<JsonData>
	{
		private IList<JsonData> inst_array;

		private bool inst_boolean;

		private double inst_double;

		private int inst_int;

		private long inst_long;

		private IDictionary<string, JsonData> inst_object;

		private string inst_string;

		private string json;

		private JsonType type;

		private IList<KeyValuePair<string, JsonData>> object_list;

		public int Count => EnsureCollection().Count;

		public bool IsArray => type == JsonType.Array;

		public bool IsBoolean => type == JsonType.Boolean;

		public bool IsDouble => type == JsonType.Double;

		public bool IsInt => type == JsonType.Int;

		public bool IsLong => type == JsonType.Long;

		public bool IsObject => type == JsonType.Object;

		public bool IsString => type == JsonType.String;

		public ICollection<string> Keys
		{
			get
			{
				EnsureDictionary();
				return inst_object.Keys;
			}
		}

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => EnsureCollection().IsSynchronized;

		object ICollection.SyncRoot => EnsureCollection().SyncRoot;

		bool IDictionary.IsFixedSize => EnsureDictionary().IsFixedSize;

		bool IDictionary.IsReadOnly => EnsureDictionary().IsReadOnly;

		ICollection IDictionary.Keys
		{
			get
			{
				EnsureDictionary();
				IList<string> list = new List<string>();
				foreach (KeyValuePair<string, JsonData> item in object_list)
				{
					list.Add(item.Key);
				}
				return (ICollection)list;
			}
		}

		ICollection IDictionary.Values
		{
			get
			{
				EnsureDictionary();
				IList<JsonData> list = new List<JsonData>();
				foreach (KeyValuePair<string, JsonData> item in object_list)
				{
					list.Add(item.Value);
				}
				return (ICollection)list;
			}
		}

		bool IJsonWrapper.IsArray => IsArray;

		bool IJsonWrapper.IsBoolean => IsBoolean;

		bool IJsonWrapper.IsDouble => IsDouble;

		bool IJsonWrapper.IsInt => IsInt;

		bool IJsonWrapper.IsLong => IsLong;

		bool IJsonWrapper.IsObject => IsObject;

		bool IJsonWrapper.IsString => IsString;

		bool IList.IsFixedSize => EnsureList().IsFixedSize;

		bool IList.IsReadOnly => EnsureList().IsReadOnly;

		object IDictionary.this[object key]
		{
			get
			{
				return EnsureDictionary()[key];
			}
			set
			{
				if (!(key is string))
				{
					throw new ArgumentException("The key has to be a string");
				}
				JsonData value2 = ToJsonData(value);
				this[(string)key] = value2;
			}
		}

		object IOrderedDictionary.this[int idx]
		{
			get
			{
				EnsureDictionary();
				return object_list[idx].Value;
			}
			set
			{
				EnsureDictionary();
				JsonData value2 = ToJsonData(value);
				KeyValuePair<string, JsonData> keyValuePair = object_list[idx];
				inst_object[keyValuePair.Key] = value2;
				KeyValuePair<string, JsonData> value3 = new KeyValuePair<string, JsonData>(keyValuePair.Key, value2);
				object_list[idx] = value3;
			}
		}

		object IList.this[int index]
		{
			get
			{
				return EnsureList()[index];
			}
			set
			{
				EnsureList();
				JsonData value2 = ToJsonData(value);
				this[index] = value2;
			}
		}

		public JsonData this[string prop_name]
		{
			get
			{
				EnsureDictionary();
				return inst_object[prop_name];
			}
			set
			{
				EnsureDictionary();
				KeyValuePair<string, JsonData> keyValuePair = new KeyValuePair<string, JsonData>(prop_name, value);
				if (inst_object.ContainsKey(prop_name))
				{
					for (int i = 0; i < object_list.Count; i++)
					{
						if (object_list[i].Key == prop_name)
						{
							object_list[i] = keyValuePair;
							break;
						}
					}
				}
				else
				{
					object_list.Add(keyValuePair);
				}
				inst_object[prop_name] = value;
				json = null;
			}
		}

		public JsonData this[int index]
		{
			get
			{
				EnsureCollection();
				if (type == JsonType.Array)
				{
					return inst_array[index];
				}
				return object_list[index].Value;
			}
			set
			{
				EnsureCollection();
				if (type == JsonType.Array)
				{
					inst_array[index] = value;
				}
				else
				{
					KeyValuePair<string, JsonData> keyValuePair = object_list[index];
					KeyValuePair<string, JsonData> value2 = new KeyValuePair<string, JsonData>(keyValuePair.Key, value);
					object_list[index] = value2;
					inst_object[keyValuePair.Key] = value;
				}
				json = null;
			}
		}

		public JsonData()
		{
		}

		public JsonData(bool boolean)
		{
			type = JsonType.Boolean;
			inst_boolean = boolean;
		}

		public JsonData(double number)
		{
			type = JsonType.Double;
			inst_double = number;
		}

		public JsonData(int number)
		{
			type = JsonType.Int;
			inst_int = number;
		}

		public JsonData(long number)
		{
			type = JsonType.Long;
			inst_long = number;
		}

		public JsonData(object obj)
		{
			if (obj is bool)
			{
				type = JsonType.Boolean;
				inst_boolean = (bool)obj;
				return;
			}
			if (obj is double)
			{
				type = JsonType.Double;
				inst_double = (double)obj;
				return;
			}
			if (obj is int)
			{
				type = JsonType.Int;
				inst_int = (int)obj;
				return;
			}
			if (obj is long)
			{
				type = JsonType.Long;
				inst_long = (long)obj;
				return;
			}
			if (obj is string)
			{
				type = JsonType.String;
				inst_string = (string)obj;
				return;
			}
			throw new ArgumentException("Unable to wrap the given object with JsonData");
		}

		public JsonData(string str)
		{
			type = JsonType.String;
			inst_string = str;
		}

		public static implicit operator JsonData(bool data)
		{
			return new JsonData(data);
		}

		public static implicit operator JsonData(double data)
		{
			return new JsonData(data);
		}

		public static implicit operator JsonData(int data)
		{
			return new JsonData(data);
		}

		public static implicit operator JsonData(long data)
		{
			return new JsonData(data);
		}

		public static implicit operator JsonData(string data)
		{
			return new JsonData(data);
		}

		public static explicit operator bool(JsonData data)
		{
			if (data.type != JsonType.Boolean)
			{
				throw new InvalidCastException("Instance of JsonData doesn't hold a double");
			}
			return data.inst_boolean;
		}

		public static explicit operator double(JsonData data)
		{
			if (data.type != JsonType.Double)
			{
				throw new InvalidCastException("Instance of JsonData doesn't hold a double");
			}
			return data.inst_double;
		}

		public static explicit operator int(JsonData data)
		{
			if (data.type != JsonType.Int)
			{
				throw new InvalidCastException("Instance of JsonData doesn't hold an int");
			}
			return data.inst_int;
		}

		public static explicit operator long(JsonData data)
		{
			if (data.type != JsonType.Long)
			{
				throw new InvalidCastException("Instance of JsonData doesn't hold an int");
			}
			return data.inst_long;
		}

		public static explicit operator string(JsonData data)
		{
			if (data.type != JsonType.String)
			{
				throw new InvalidCastException("Instance of JsonData doesn't hold a string");
			}
			return data.inst_string;
		}

		void ICollection.CopyTo(Array array, int index)
		{
			EnsureCollection().CopyTo(array, index);
		}

		void IDictionary.Add(object key, object value)
		{
			JsonData value2 = ToJsonData(value);
			EnsureDictionary().Add(key, value2);
			KeyValuePair<string, JsonData> item = new KeyValuePair<string, JsonData>((string)key, value2);
			object_list.Add(item);
			json = null;
		}

		void IDictionary.Clear()
		{
			EnsureDictionary().Clear();
			object_list.Clear();
			json = null;
		}

		bool IDictionary.Contains(object key)
		{
			return EnsureDictionary().Contains(key);
		}

		IDictionaryEnumerator IDictionary.GetEnumerator()
		{
			return ((IOrderedDictionary)this).GetEnumerator();
		}

		void IDictionary.Remove(object key)
		{
			EnsureDictionary().Remove(key);
			for (int i = 0; i < object_list.Count; i++)
			{
				if (object_list[i].Key == (string)key)
				{
					object_list.RemoveAt(i);
					break;
				}
			}
			json = null;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return EnsureCollection().GetEnumerator();
		}

		bool IJsonWrapper.GetBoolean()
		{
			if (type != JsonType.Boolean)
			{
				throw new InvalidOperationException("JsonData instance doesn't hold a boolean");
			}
			return inst_boolean;
		}

		double IJsonWrapper.GetDouble()
		{
			if (type != JsonType.Double)
			{
				throw new InvalidOperationException("JsonData instance doesn't hold a double");
			}
			return inst_double;
		}

		int IJsonWrapper.GetInt()
		{
			if (type != JsonType.Int)
			{
				throw new InvalidOperationException("JsonData instance doesn't hold an int");
			}
			return inst_int;
		}

		long IJsonWrapper.GetLong()
		{
			if (type != JsonType.Long)
			{
				throw new InvalidOperationException("JsonData instance doesn't hold a long");
			}
			return inst_long;
		}

		string IJsonWrapper.GetString()
		{
			if (type != JsonType.String)
			{
				throw new InvalidOperationException("JsonData instance doesn't hold a string");
			}
			return inst_string;
		}

		void IJsonWrapper.SetBoolean(bool val)
		{
			type = JsonType.Boolean;
			inst_boolean = val;
			json = null;
		}

		void IJsonWrapper.SetDouble(double val)
		{
			type = JsonType.Double;
			inst_double = val;
			json = null;
		}

		void IJsonWrapper.SetInt(int val)
		{
			type = JsonType.Int;
			inst_int = val;
			json = null;
		}

		void IJsonWrapper.SetLong(long val)
		{
			type = JsonType.Long;
			inst_long = val;
			json = null;
		}

		void IJsonWrapper.SetString(string val)
		{
			type = JsonType.String;
			inst_string = val;
			json = null;
		}

		string IJsonWrapper.ToJson()
		{
			return ToJson();
		}

		void IJsonWrapper.ToJson(JsonWriter writer)
		{
			ToJson(writer);
		}

		int IList.Add(object value)
		{
			return Add(value);
		}

		void IList.Clear()
		{
			EnsureList().Clear();
			json = null;
		}

		bool IList.Contains(object value)
		{
			return EnsureList().Contains(value);
		}

		int IList.IndexOf(object value)
		{
			return EnsureList().IndexOf(value);
		}

		void IList.Insert(int index, object value)
		{
			EnsureList().Insert(index, value);
			json = null;
		}

		void IList.Remove(object value)
		{
			EnsureList().Remove(value);
			json = null;
		}

		void IList.RemoveAt(int index)
		{
			EnsureList().RemoveAt(index);
			json = null;
		}

		IDictionaryEnumerator IOrderedDictionary.GetEnumerator()
		{
			EnsureDictionary();
			return new OrderedDictionaryEnumerator(object_list.GetEnumerator());
		}

		void IOrderedDictionary.Insert(int idx, object key, object value)
		{
			string text = (string)key;
			JsonData value2 = (this[text] = ToJsonData(value));
			KeyValuePair<string, JsonData> item = new KeyValuePair<string, JsonData>(text, value2);
			object_list.Insert(idx, item);
		}

		void IOrderedDictionary.RemoveAt(int idx)
		{
			EnsureDictionary();
			inst_object.Remove(object_list[idx].Key);
			object_list.RemoveAt(idx);
		}

		private ICollection EnsureCollection()
		{
			if (type == JsonType.Array)
			{
				return (ICollection)inst_array;
			}
			if (type == JsonType.Object)
			{
				return (ICollection)inst_object;
			}
			throw new InvalidOperationException("The JsonData instance has to be initialized first");
		}

		private IDictionary EnsureDictionary()
		{
			if (type == JsonType.Object)
			{
				return (IDictionary)inst_object;
			}
			if (type != 0)
			{
				throw new InvalidOperationException("Instance of JsonData is not a dictionary");
			}
			type = JsonType.Object;
			inst_object = new Dictionary<string, JsonData>();
			object_list = new List<KeyValuePair<string, JsonData>>();
			return (IDictionary)inst_object;
		}

		private IList EnsureList()
		{
			if (type == JsonType.Array)
			{
				return (IList)inst_array;
			}
			if (type != 0)
			{
				throw new InvalidOperationException("Instance of JsonData is not a list");
			}
			type = JsonType.Array;
			inst_array = new List<JsonData>();
			return (IList)inst_array;
		}

		private JsonData ToJsonData(object obj)
		{
			if (obj == null)
			{
				return null;
			}
			if (obj is JsonData)
			{
				return (JsonData)obj;
			}
			return new JsonData(obj);
		}

		private static void WriteJson(IJsonWrapper obj, JsonWriter writer)
		{
			if (obj == null)
			{
				writer.Write(null);
			}
			else if (obj.IsString)
			{
				writer.Write(obj.GetString());
			}
			else if (obj.IsBoolean)
			{
				writer.Write(obj.GetBoolean());
			}
			else if (obj.IsDouble)
			{
				writer.Write(obj.GetDouble());
			}
			else if (obj.IsInt)
			{
				writer.Write(obj.GetInt());
			}
			else if (obj.IsLong)
			{
				writer.Write(obj.GetLong());
			}
			else if (obj.IsArray)
			{
				writer.WriteArrayStart();
				foreach (object item in (IEnumerable)obj)
				{
					WriteJson((JsonData)item, writer);
				}
				writer.WriteArrayEnd();
			}
			else
			{
				if (!obj.IsObject)
				{
					return;
				}
				writer.WriteObjectStart();
				foreach (DictionaryEntry item2 in (IDictionary)obj)
				{
					writer.WritePropertyName((string)item2.Key);
					WriteJson((JsonData)item2.Value, writer);
				}
				writer.WriteObjectEnd();
			}
		}

		public int Add(object value)
		{
			JsonData value2 = ToJsonData(value);
			json = null;
			return EnsureList().Add(value2);
		}

		public void Clear()
		{
			if (IsObject)
			{
				((IDictionary)this).Clear();
			}
			else if (IsArray)
			{
				((IList)this).Clear();
			}
		}

		public bool Equals(JsonData x)
		{
			if (x == null)
			{
				return false;
			}
			if (x.type != type)
			{
				return false;
			}
			return type switch
			{
				JsonType.None => true, 
				JsonType.Object => inst_object.Equals(x.inst_object), 
				JsonType.Array => inst_array.Equals(x.inst_array), 
				JsonType.String => inst_string.Equals(x.inst_string), 
				JsonType.Int => inst_int.Equals(x.inst_int), 
				JsonType.Long => inst_long.Equals(x.inst_long), 
				JsonType.Double => inst_double.Equals(x.inst_double), 
				JsonType.Boolean => inst_boolean.Equals(x.inst_boolean), 
				_ => false, 
			};
		}

		public JsonType GetJsonType()
		{
			return type;
		}

		public void SetJsonType(JsonType type)
		{
			if (this.type != type)
			{
				switch (type)
				{
				case JsonType.Object:
					inst_object = new Dictionary<string, JsonData>();
					object_list = new List<KeyValuePair<string, JsonData>>();
					break;
				case JsonType.Array:
					inst_array = new List<JsonData>();
					break;
				case JsonType.String:
					inst_string = null;
					break;
				case JsonType.Int:
					inst_int = 0;
					break;
				case JsonType.Long:
					inst_long = 0L;
					break;
				case JsonType.Double:
					inst_double = 0.0;
					break;
				case JsonType.Boolean:
					inst_boolean = false;
					break;
				}
				this.type = type;
			}
		}

		public string ToJson()
		{
			if (json != null)
			{
				return json;
			}
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = new JsonWriter(stringWriter);
			jsonWriter.Validate = false;
			WriteJson(this, jsonWriter);
			json = stringWriter.ToString();
			return json;
		}

		public void ToJson(JsonWriter writer)
		{
			bool validate = writer.Validate;
			writer.Validate = false;
			WriteJson(this, writer);
			writer.Validate = validate;
		}

		public override string ToString()
		{
			return type switch
			{
				JsonType.Array => "JsonData array", 
				JsonType.Boolean => inst_boolean.ToString(), 
				JsonType.Double => inst_double.ToString(), 
				JsonType.Int => inst_int.ToString(), 
				JsonType.Long => inst_long.ToString(), 
				JsonType.Object => "JsonData object", 
				JsonType.String => inst_string, 
				_ => "Uninitialized JsonData", 
			};
		}
	}
	internal class OrderedDictionaryEnumerator : IDictionaryEnumerator, IEnumerator
	{
		private IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;

		public object Current => Entry;

		public DictionaryEntry Entry
		{
			get
			{
				KeyValuePair<string, JsonData> current = list_enumerator.Current;
				return new DictionaryEntry(current.Key, current.Value);
			}
		}

		public object Key => list_enumerator.Current.Key;

		public object Value => list_enumerator.Current.Value;

		public OrderedDictionaryEnumerator(IEnumerator<KeyValuePair<string, JsonData>> enumerator)
		{
			list_enumerator = enumerator;
		}

		public bool MoveNext()
		{
			return list_enumerator.MoveNext();
		}

		public void Reset()
		{
			list_enumerator.Reset();
		}
	}
	internal class JsonException : ApplicationException
	{
		public JsonException()
		{
		}

		internal JsonException(ParserToken token)
			: base($"Invalid token '{token}' in input string")
		{
		}

		internal JsonException(ParserToken token, Exception inner_exception)
			: base($"Invalid token '{token}' in input string", inner_exception)
		{
		}

		internal JsonException(int c)
			: base($"Invalid character '{(char)c}' in input string")
		{
		}

		internal JsonException(int c, Exception inner_exception)
			: base($"Invalid character '{(char)c}' in input string", inner_exception)
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception inner_exception)
			: base(message, inner_exception)
		{
		}
	}
	internal struct PropertyMetadata
	{
		public MemberInfo Info;

		public bool IsField;

		public Type Type;
	}
	internal struct ArrayMetadata
	{
		private Type element_type;

		private bool is_array;

		private bool is_list;

		public Type ElementType
		{
			get
			{
				if (element_type == null)
				{
					return typeof(JsonData);
				}
				return element_type;
			}
			set
			{
				element_type = value;
			}
		}

		public bool IsArray
		{
			get
			{
				return is_array;
			}
			set
			{
				is_array = value;
			}
		}

		public bool IsList
		{
			get
			{
				return is_list;
			}
			set
			{
				is_list = value;
			}
		}
	}
	internal struct ObjectMetadata
	{
		private Type element_type;

		private bool is_dictionary;

		private IDictionary<string, PropertyMetadata> properties;

		public Type ElementType
		{
			get
			{
				if (element_type == null)
				{
					return typeof(JsonData);
				}
				return element_type;
			}
			set
			{
				element_type = value;
			}
		}

		public bool IsDictionary
		{
			get
			{
				return is_dictionary;
			}
			set
			{
				is_dictionary = value;
			}
		}

		public IDictionary<string, PropertyMetadata> Properties
		{
			get
			{
				return properties;
			}
			set
			{
				properties = value;
			}
		}
	}
	internal delegate void ExporterFunc(object obj, JsonWriter writer);
	internal delegate void ExporterFunc<T>(T obj, JsonWriter writer);
	internal delegate object ImporterFunc(object input);
	internal delegate TValue ImporterFunc<TJson, TValue>(TJson input);
	internal delegate IJsonWrapper WrapperFactory();
	internal class JsonMapper
	{
		private static int max_nesting_depth;

		private static IFormatProvider datetime_format;

		private static IDictionary<Type, ExporterFunc> base_exporters_table;

		private static IDictionary<Type, ExporterFunc> custom_exporters_table;

		private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table;

		private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table;

		private static IDictionary<Type, ArrayMetadata> array_metadata;

		private static readonly object array_metadata_lock;

		private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops;

		private static readonly object conv_ops_lock;

		private static IDictionary<Type, ObjectMetadata> object_metadata;

		private static readonly object object_metadata_lock;

		private static IDictionary<Type, IList<PropertyMetadata>> type_properties;

		private static readonly object type_properties_lock;

		private static JsonWriter static_writer;

		private static readonly object static_writer_lock;

		static JsonMapper()
		{
			array_metadata_lock = new object();
			conv_ops_lock = new object();
			object_metadata_lock = new object();
			type_properties_lock = new object();
			static_writer_lock = new object();
			max_nesting_depth = 100;
			array_metadata = new Dictionary<Type, ArrayMetadata>();
			conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>>();
			object_metadata = new Dictionary<Type, ObjectMetadata>();
			type_properties = new Dictionary<Type, IList<PropertyMetadata>>();
			static_writer = new JsonWriter();
			datetime_format = DateTimeFormatInfo.InvariantInfo;
			base_exporters_table = new Dictionary<Type, ExporterFunc>();
			custom_exporters_table = new Dictionary<Type, ExporterFunc>();
			base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>>();
			custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>>();
			RegisterBaseExporters();
			RegisterBaseImporters();
		}

		private static void AddArrayMetadata(Type type)
		{
			if (array_metadata.ContainsKey(