Decompiled source of AutoRepairBuilding v1.3.1821

AutoRepairBuilding.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AutoRepairBuilding")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.1814.0")]
[assembly: AssemblyInformationalVersion("1.3.1814+f9281ffda4b76fe981b366f76671b715921fa315")]
[assembly: AssemblyProduct("AutoRepairBuilding")]
[assembly: AssemblyTitle("AutoRepairBuilding")]
[assembly: AssemblyVersion("1.3.1814.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AutoBuildingRepair
{
	public static class LocalizationHelper
	{
		public static string GetLanguage()
		{
			return PlayerPrefs.GetString("language", "English");
		}

		public static bool IsRussian()
		{
			return GetLanguage().Equals("Russian", StringComparison.OrdinalIgnoreCase);
		}

		public static bool IsUkrainian()
		{
			return GetLanguage().Equals("Ukrainian", StringComparison.OrdinalIgnoreCase);
		}

		public static bool IsSpanish()
		{
			return GetLanguage().Equals("Spanish", StringComparison.OrdinalIgnoreCase);
		}

		public static string T(string english, string russian, string ukrainian, string spanish)
		{
			string language = GetLanguage();
			if (language.Equals("Russian", StringComparison.OrdinalIgnoreCase))
			{
				return russian;
			}
			if (language.Equals("Ukrainian", StringComparison.OrdinalIgnoreCase))
			{
				return ukrainian;
			}
			if (language.Equals("Spanish", StringComparison.OrdinalIgnoreCase))
			{
				return spanish;
			}
			return english;
		}
	}
	public class RepairTooltipTrigger : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public string Description = "";

		public void OnPointerEnter(PointerEventData eventData)
		{
			if (!string.IsNullOrEmpty(Description))
			{
				AutoRepairSettingsMenu.ShowTooltip(Description);
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			AutoRepairSettingsMenu.HideTooltip();
		}
	}
	public class RepairTooltipFollower : MonoBehaviour
	{
		private RectTransform _rt;

		private RectTransform _canvasRt;

		private void Awake()
		{
			_rt = ((Component)this).GetComponent<RectTransform>();
		}

		private void Update()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: 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_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_canvasRt == (Object)null && (Object)(object)((Component)this).transform.parent != (Object)null)
			{
				_canvasRt = ((Component)((Component)this).transform.parent).GetComponent<RectTransform>();
			}
			if ((Object)(object)_canvasRt == (Object)null)
			{
				return;
			}
			Vector2 val = Vector2.op_Implicit(Input.mousePosition);
			Vector2 val2 = default(Vector2);
			if (RectTransformUtility.ScreenPointToLocalPointInRectangle(_canvasRt, val, (Camera)null, ref val2))
			{
				float num = 15f;
				float num2 = -15f;
				Rect rect = _rt.rect;
				float num3;
				if (!(((Rect)(ref rect)).width > 0f))
				{
					num3 = 360f;
				}
				else
				{
					rect = _rt.rect;
					num3 = ((Rect)(ref rect)).width;
				}
				float num4 = num3;
				rect = _rt.rect;
				float num5;
				if (!(((Rect)(ref rect)).height > 0f))
				{
					num5 = 75f;
				}
				else
				{
					rect = _rt.rect;
					num5 = ((Rect)(ref rect)).height;
				}
				float num6 = num5;
				rect = _canvasRt.rect;
				float num7 = ((Rect)(ref rect)).width / 2f;
				rect = _canvasRt.rect;
				float num8 = ((Rect)(ref rect)).height / 2f;
				float num9 = Mathf.Clamp(val2.x + num, 0f - num7, num7 - num4);
				float num10 = Mathf.Clamp(val2.y + num2, 0f - num8 + num6, num8);
				_rt.anchoredPosition = new Vector2(num9, num10);
			}
		}
	}
	public class RepairKeyBindListener : MonoBehaviour
	{
		private ConfigEntryBase _entry;

		private Text _text;

		private Image _btnImage;

		private Action _onFinished;

		private bool _isListening;

		private float _startTime;

		public static RepairKeyBindListener ActiveListener { get; private set; }

		public void StartListening(ConfigEntryBase entry, Text buttonText, Image btnImage, Action onFinished)
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ActiveListener != (Object)null && (Object)(object)ActiveListener != (Object)(object)this)
			{
				ActiveListener.CancelListening();
			}
			_entry = entry;
			_text = buttonText;
			_btnImage = btnImage;
			_onFinished = onFinished;
			_isListening = true;
			_startTime = Time.unscaledTime;
			ActiveListener = this;
			_text.text = LocalizationHelper.T("[ PRESS ANY KEY ]", "[ НАЖМИТЕ КЛАВИШУ ]", "[ НАТИСНІТЬ КЛАВІШУ ]", "[ PULSA UNA TECLA ]");
			((Graphic)_text).color = new Color(1f, 0.85f, 0.2f);
			if ((Object)(object)_btnImage != (Object)null)
			{
				((Graphic)_btnImage).color = new Color(0.32f, 0.38f, 0.52f, 1f);
			}
		}

		public void CancelListening()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			_isListening = false;
			if ((Object)(object)ActiveListener == (Object)(object)this)
			{
				ActiveListener = null;
			}
			if ((Object)(object)_text != (Object)null && _entry != null)
			{
				_text.text = _entry.BoxedValue?.ToString().ToUpper() ?? "NONE";
				((Graphic)_text).color = Color.white;
			}
			if ((Object)(object)_btnImage != (Object)null)
			{
				((Graphic)_btnImage).color = new Color(0.2f, 0.25f, 0.35f, 1f);
			}
		}

		private void Update()
		{
			//IL_0050: 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_0056: 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)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			if (!_isListening || Time.unscaledTime - _startTime < 0.08f)
			{
				return;
			}
			if (Input.GetKeyDown((KeyCode)27))
			{
				CancelListening();
			}
			else
			{
				if (!Input.anyKeyDown)
				{
					return;
				}
				foreach (KeyCode value in Enum.GetValues(typeof(KeyCode)))
				{
					if ((int)value != 0 && (int)value != 323 && Input.GetKeyDown(value))
					{
						ApplyKey(value);
						break;
					}
				}
			}
		}

		private void OnGUI()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (!_isListening)
			{
				return;
			}
			Event current = Event.current;
			if (current != null && current.isKey && (int)current.type == 4)
			{
				if ((int)current.keyCode == 27)
				{
					CancelListening();
				}
				else if ((int)current.keyCode != 0)
				{
					ApplyKey(current.keyCode);
				}
			}
		}

		private unsafe void ApplyKey(KeyCode key)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			_entry.BoxedValue = key;
			_isListening = false;
			if ((Object)(object)ActiveListener == (Object)(object)this)
			{
				ActiveListener = null;
			}
			if ((Object)(object)_text != (Object)null)
			{
				_text.text = ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString().ToUpper();
				((Graphic)_text).color = Color.white;
			}
			if ((Object)(object)_btnImage != (Object)null)
			{
				((Graphic)_btnImage).color = new Color(0.2f, 0.25f, 0.35f, 1f);
			}
			try
			{
				ConfigFile configInstance = AutoRepairSettingsMenu.ConfigInstance;
				if (configInstance != null)
				{
					configInstance.Save();
				}
			}
			catch
			{
			}
			_onFinished?.Invoke();
		}

		private void OnDisable()
		{
			if (_isListening)
			{
				CancelListening();
			}
		}
	}
	public static class AutoRepairSettingsMenu
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__8_0;

			internal void <OpenMenu>b__8_0()
			{
				ConfigFile configInstance = ConfigInstance;
				if (configInstance != null)
				{
					configInstance.Save();
				}
				CloseMenu();
			}
		}

		public static ConfigFile ConfigInstance;

		private static GameObject _settingsCanvas;

		private static GameObject _tooltipGO;

		private static Text _tooltipText;

		private static readonly List<Action> _uiRefreshCallbacks = new List<Action>();

		public static bool IsOpen => (Object)(object)_settingsCanvas != (Object)null;

		public static void ToggleSettingsMenu()
		{
			if ((Object)(object)_settingsCanvas == (Object)null)
			{
				OpenMenu();
			}
			else
			{
				CloseMenu();
			}
		}

		public static void OpenMenu()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Expected O, but got Unknown
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Expected O, but got Unknown
			if ((Object)(object)_settingsCanvas != (Object)null)
			{
				return;
			}
			_uiRefreshCallbacks.Clear();
			_settingsCanvas = new GameObject("AutoRepairSettingsCanvas");
			_settingsCanvas.layer = 5;
			Object.DontDestroyOnLoad((Object)(object)_settingsCanvas);
			Canvas obj = _settingsCanvas.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 10000;
			_settingsCanvas.AddComponent<CanvasScaler>();
			_settingsCanvas.AddComponent<GraphicRaycaster>();
			GameObject val = MakeRect("Background", _settingsCanvas.transform, new Color(0.06f, 0.06f, 0.07f, 0.98f));
			SetRect(val, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(680f, 430f), Vector2.zero);
			Outline obj2 = val.AddComponent<Outline>();
			((Shadow)obj2).effectColor = new Color(0.3f, 0.3f, 0.3f, 1f);
			((Shadow)obj2).effectDistance = new Vector2(2f, -2f);
			string text = LocalizationHelper.T("AUTO REPAIR CONFIGURATION", "НАСТРОЙКИ АВТОПОЧИНКИ", "НАЛАШТУВАННЯ АВТОПОЧИНКИ", "CONFIGURACIÓN DE AUTORREPARACIÓN");
			SetRect(((Component)MakeText("Header", val.transform, text, 20, new Color(1f, 0.72f, 0.15f), (FontStyle)1)).gameObject, new Vector2(0f, 0.88f), new Vector2(1f, 1f), Vector2.zero, new Vector2(0f, -4f));
			GameObject val2 = MakeRect("ScrollArea", val.transform, new Color(0f, 0f, 0f, 0.5f));
			SetRect(val2, new Vector2(0.03f, 0.16f), new Vector2(0.97f, 0.88f), Vector2.zero, Vector2.zero);
			GameObject val3 = MakeRect("Viewport", val2.transform, Color.clear);
			SetRect(val3, Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero);
			val3.AddComponent<RectMask2D>();
			GameObject obj3 = MakeRect("Content", val3.transform, Color.clear);
			RectTransform component = obj3.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(1f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.sizeDelta = Vector2.zero;
			VerticalLayoutGroup obj4 = obj3.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj4).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj4).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj4).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)obj4).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj4).spacing = 5f;
			((LayoutGroup)obj4).padding = new RectOffset(10, 10, 6, 6);
			obj3.AddComponent<ContentSizeFitter>().verticalFit = (FitMode)2;
			ScrollRect obj5 = val2.AddComponent<ScrollRect>();
			obj5.content = component;
			obj5.viewport = val3.GetComponent<RectTransform>();
			obj5.horizontal = false;
			obj5.vertical = true;
			obj5.scrollSensitivity = 40f;
			GenerateConfigRows(obj3.transform);
			GameObject val4 = MakeRect("CloseBtn", val.transform, new Color(0.75f, 0.2f, 0.2f, 1f));
			SetRect(val4, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(280f, 40f), new Vector2(0f, 32f));
			string text2 = LocalizationHelper.T("CLOSE & SAVE", "ЗАКРЫТЬ И СОХРАНИТЬ", "ЗАКРИТИ ТА ЗБЕРЕГТИ", "CERRAR Y GUARDAR");
			MakeText("CloseTxt", val4.transform, text2, 15, Color.white, (FontStyle)1);
			ButtonClickedEvent onClick = val4.AddComponent<Button>().onClick;
			object obj6 = <>c.<>9__8_0;
			if (obj6 == null)
			{
				UnityAction val5 = delegate
				{
					ConfigFile configInstance = ConfigInstance;
					if (configInstance != null)
					{
						configInstance.Save();
					}
					CloseMenu();
				};
				<>c.<>9__8_0 = val5;
				obj6 = (object)val5;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj6);
			CreateTooltipUI(_settingsCanvas.transform);
		}

		public static void CloseMenu()
		{
			HideTooltip();
			if ((Object)(object)_settingsCanvas != (Object)null)
			{
				Object.Destroy((Object)(object)_settingsCanvas);
				_settingsCanvas = null;
			}
		}

		private static void GenerateConfigRows(Transform parent)
		{
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.ModEnabled, LocalizationHelper.T("Mod Enabled", "Включение мода", "Увімкнення моду", "Mod Habilitado"), LocalizationHelper.T("Enable or disable auto repair mod globally.", "Глобальное включение или выключение мода автопочинки.", "Глобальне увімкнення або вимкнення моду автопочинки.", "Habilita o deshabilita el mod de autorreparación globalmente."));
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.RepairRadius, LocalizationHelper.T("Repair Radius (m)", "Радиус починки (м)", "Радіус починки (м)", "Radio de Reparación (m)"), LocalizationHelper.T("Radius around crafting station to search and repair pieces.", "Радиус вокруг верстака для поиска и починки построек.", "Радіус навколо верстака для пошуку та лагодження споруд.", "Radio alrededor del banco de trabajo para buscar y reparar piezas."));
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.RepairInterval, LocalizationHelper.T("Repair Interval (0 = Morning)", "Интервал починки (0 = Утром)", "Інтервал починки (0 = Вранці)", "Intervalo (0 = Mañana)"), LocalizationHelper.T("Interval in seconds between repairs. Set to 0 to repair only in the morning (at dawn).", "Интервал в секундах между циклами автопочинки. Установите 0 для починки только на рассвете (каждое игровое утро).", "Інтервал у секундах між циклами автопочинки. Встановіть 0 для лагодження лише на світанку (щоранку).", "Intervalo en segundos. Establece en 0 para reparar solo al amanecer."));
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.AllowRepairOther, LocalizationHelper.T("Repair Other Players' Pieces", "Чинить чужие постройки", "Лагодити чужі споруди", "Reparar Piezas Ajenas"), LocalizationHelper.T("Allow repairing pieces built by other players.", "Разрешить верстаку чинить постройки других игроков.", "Дозволити верстаку лагодити споруди інших гравців.", "Permitir reparar piezas construidas por otros jugadores."));
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.ShowRepairMessage, LocalizationHelper.T("HUD Notifications", "Уведомления на экране", "Сповіщення на екрані", "Notificaciones en Pantalla"), LocalizationHelper.T("Show top-left HUD message when pieces are repaired.", "Показывать уведомление в углу экрана при починке построек.", "Показувати сповіщення в кутку екрана під час лагодження споруд.", "Mostrar mensaje en la interfaz cuando se reparen piezas."));
			AddConfigRow(parent, (ConfigEntryBase)(object)Plugin.MenuHotkey, LocalizationHelper.T("Settings Menu Hotkey", "Горячая клавиша меню", "Гаряча клавіша меню", "Tecla de Menú de Ajustes"), LocalizationHelper.T("Hotkey to open this settings menu. Click to rebind.", "Горячая клавиша для открытия данного меню настроек. Нажмите для смены.", "Гаряча клавіша для відкриття цього меню налаштувань. Натисніть для зміни.", "Tecla rápida para abrir este menú de configuración. Haz clic para reasignar."));
		}

		private static void AddConfigRow(Transform parent, ConfigEntryBase entry, string localizedLabel, string localizedTooltip)
		{
			//IL_002a: 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_00a1: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = MakeRect("Row_" + entry.Definition.Key, parent, new Color(1f, 1f, 1f, 0.06f));
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.minHeight = 44f;
			obj.preferredHeight = 44f;
			if (!string.IsNullOrEmpty(localizedTooltip))
			{
				val.AddComponent<RepairTooltipTrigger>().Description = localizedTooltip;
			}
			HorizontalLayoutGroup obj2 = val.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj2).spacing = 10f;
			((LayoutGroup)obj2).padding = new RectOffset(15, 15, 5, 5);
			Text obj3 = MakeText("Label", val.transform, localizedLabel, 15, Color.white, (FontStyle)0);
			obj3.alignment = (TextAnchor)3;
			((Component)obj3).gameObject.AddComponent<LayoutElement>().flexibleWidth = 1f;
			Action action = null;
			if (entry.SettingType == typeof(bool))
			{
				action = CreateBoolToggle(val.transform, (ConfigEntry<bool>)(object)entry);
			}
			else if (entry.SettingType == typeof(KeyCode))
			{
				action = CreateKeybindButton(val.transform, entry);
			}
			else if (entry.SettingType == typeof(float) || entry.SettingType == typeof(int))
			{
				action = CreateInputField(val.transform, entry);
			}
			if (action != null)
			{
				_uiRefreshCallbacks.Add(action);
			}
			CreateResetButton(val.transform, entry, action);
		}

		private static Action CreateBoolToggle(Transform parent, ConfigEntry<bool> entry)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			GameObject btnGo = MakeRect("ToggleBtn", parent, entry.Value ? new Color(0.2f, 0.6f, 0.2f, 1f) : new Color(0.6f, 0.2f, 0.2f, 1f));
			LayoutElement obj = btnGo.AddComponent<LayoutElement>();
			obj.minWidth = 180f;
			obj.preferredWidth = 180f;
			obj.flexibleWidth = 0f;
			string onStr = LocalizationHelper.T("ENABLED", "ВКЛЮЧЕНО", "УВІМКНЕНО", "HABILITADO");
			string offStr = LocalizationHelper.T("DISABLED", "ВЫКЛЮЧЕНО", "ВИМКНЕНО", "DESACTIVADO");
			Text txt = MakeText("Txt", btnGo.transform, entry.Value ? onStr : offStr, 14, Color.white, (FontStyle)1);
			Button obj2 = btnGo.AddComponent<Button>();
			Action updateUI = delegate
			{
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				((Graphic)btnGo.GetComponent<Image>()).color = (entry.Value ? new Color(0.2f, 0.6f, 0.2f, 1f) : new Color(0.6f, 0.2f, 0.2f, 1f));
				txt.text = (entry.Value ? onStr : offStr);
			};
			((UnityEvent)obj2.onClick).AddListener((UnityAction)delegate
			{
				entry.Value = !entry.Value;
				updateUI();
			});
			return updateUI;
		}

		private static Action CreateKeybindButton(Transform parent, ConfigEntryBase entry)
		{
			//IL_0027: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			GameObject val = MakeRect("KeybindBtn", parent, new Color(0.2f, 0.25f, 0.35f, 1f));
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.minWidth = 180f;
			obj.preferredWidth = 180f;
			obj.flexibleWidth = 0f;
			Image img = val.GetComponent<Image>();
			Text txt = MakeText("Txt", val.transform, entry.BoxedValue?.ToString().ToUpper() ?? "NONE", 14, Color.white, (FontStyle)1);
			Button obj2 = val.AddComponent<Button>();
			RepairKeyBindListener listener = val.AddComponent<RepairKeyBindListener>();
			Action updateUI = delegate
			{
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				txt.text = entry.BoxedValue?.ToString().ToUpper() ?? "NONE";
				((Graphic)txt).color = Color.white;
				((Graphic)img).color = new Color(0.2f, 0.25f, 0.35f, 1f);
			};
			((UnityEvent)obj2.onClick).AddListener((UnityAction)delegate
			{
				listener.StartListening(entry, txt, img, updateUI);
			});
			return updateUI;
		}

		private static Action CreateInputField(Transform parent, ConfigEntryBase entry)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Expected O, but got Unknown
			GameObject val = MakeRect("InputContainer", parent, Color.clear);
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.minWidth = 180f;
			obj.preferredWidth = 180f;
			obj.flexibleWidth = 0f;
			HorizontalLayoutGroup obj2 = val.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj2).spacing = 3f;
			GameObject val2 = MakeRect("InputBg", val.transform, new Color(0.12f, 0.12f, 0.14f, 1f));
			Outline obj3 = val2.AddComponent<Outline>();
			((Shadow)obj3).effectColor = new Color(0.25f, 0.25f, 0.25f, 0.8f);
			((Shadow)obj3).effectDistance = new Vector2(1f, -1f);
			val2.AddComponent<LayoutElement>().flexibleWidth = 1f;
			string text = entry.BoxedValue?.ToString() ?? "";
			Text val3 = MakeText("Text", val2.transform, text, 14, Color.white, (FontStyle)0);
			val3.alignment = (TextAnchor)4;
			InputField inputField = val2.AddComponent<InputField>();
			inputField.textComponent = val3;
			inputField.text = text;
			((UnityEvent<string>)(object)inputField.onEndEdit).AddListener((UnityAction<string>)delegate(string s)
			{
				float result2;
				if (entry.SettingType == typeof(int) && int.TryParse(s, out var result))
				{
					entry.BoxedValue = Mathf.Max(0, result);
				}
				else if (entry.SettingType == typeof(float) && float.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out result2))
				{
					entry.BoxedValue = Mathf.Max(0f, result2);
				}
				else
				{
					inputField.text = entry.BoxedValue?.ToString() ?? "";
				}
			});
			GameObject val4 = MakeRect("StepperCol", val.transform, Color.clear);
			LayoutElement obj4 = val4.AddComponent<LayoutElement>();
			obj4.minWidth = 24f;
			obj4.preferredWidth = 24f;
			obj4.flexibleWidth = 0f;
			VerticalLayoutGroup obj5 = val4.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj5).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj5).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj5).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj5).childForceExpandHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj5).spacing = 2f;
			GameObject val5 = MakeRect("UpBtn", val4.transform, new Color(0.22f, 0.22f, 0.22f, 0.95f));
			MakeText("UpTxt", val5.transform, "▲", 8, Color.white, (FontStyle)0).alignment = (TextAnchor)4;
			((UnityEvent)val5.AddComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StepValue(entry, inputField, 1f);
			});
			GameObject val6 = MakeRect("DownBtn", val4.transform, new Color(0.22f, 0.22f, 0.22f, 0.95f));
			MakeText("DownTxt", val6.transform, "▼", 8, Color.white, (FontStyle)0).alignment = (TextAnchor)4;
			((UnityEvent)val6.AddComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				StepValue(entry, inputField, -1f);
			});
			return delegate
			{
				inputField.text = entry.BoxedValue?.ToString() ?? "";
			};
		}

		private static void StepValue(ConfigEntryBase entry, InputField inputField, float dir)
		{
			if (entry.SettingType == typeof(float))
			{
				float num = (float)entry.BoxedValue;
				float num2 = 1f;
				float num3 = Mathf.Max(0f, (float)Math.Round(num + dir * num2, 1));
				entry.BoxedValue = num3;
				inputField.text = num3.ToString(CultureInfo.InvariantCulture);
			}
			else if (entry.SettingType == typeof(int))
			{
				int num4 = (int)entry.BoxedValue;
				int num5 = Mathf.Max(0, num4 + (int)dir);
				entry.BoxedValue = num5;
				inputField.text = num5.ToString();
			}
		}

		private static void CreateResetButton(Transform parent, ConfigEntryBase entry, Action refreshAction)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			GameObject val = MakeRect("ResetBtn", parent, new Color(0.18f, 0.45f, 0.85f, 1f));
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.minWidth = 34f;
			obj.preferredWidth = 34f;
			obj.minHeight = 34f;
			obj.preferredHeight = 34f;
			obj.flexibleWidth = 0f;
			MakeText("ArrowTxt", val.transform, "↺", 16, Color.white, (FontStyle)1).alignment = (TextAnchor)4;
			val.AddComponent<RepairTooltipTrigger>().Description = LocalizationHelper.T($"Reset to default: {entry.DefaultValue}", $"Сбросить на значение по умолчанию: {entry.DefaultValue}", $"Скинути на стандартне значення: {entry.DefaultValue}", $"Restablecer al valor predeterminado: {entry.DefaultValue}");
			((UnityEvent)val.AddComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				entry.BoxedValue = entry.DefaultValue;
				refreshAction?.Invoke();
			});
		}

		private static void CreateTooltipUI(Transform parent)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			_tooltipGO = MakeRect("TooltipPanel", parent, new Color(0.08f, 0.08f, 0.08f, 0.95f));
			_tooltipGO.SetActive(false);
			_tooltipGO.GetComponent<RectTransform>().pivot = new Vector2(0f, 1f);
			Outline obj = _tooltipGO.AddComponent<Outline>();
			((Shadow)obj).effectColor = new Color(0.4f, 0.4f, 0.4f, 0.9f);
			((Shadow)obj).effectDistance = new Vector2(1f, -1f);
			((LayoutGroup)_tooltipGO.AddComponent<VerticalLayoutGroup>()).padding = new RectOffset(12, 12, 10, 10);
			ContentSizeFitter obj2 = _tooltipGO.AddComponent<ContentSizeFitter>();
			obj2.horizontalFit = (FitMode)2;
			obj2.verticalFit = (FitMode)2;
			_tooltipGO.AddComponent<LayoutElement>().preferredWidth = 360f;
			_tooltipText = MakeText("TooltipText", _tooltipGO.transform, "", 14, new Color(0.9f, 0.9f, 0.9f, 1f), (FontStyle)0);
			_tooltipText.alignment = (TextAnchor)3;
			_tooltipText.horizontalOverflow = (HorizontalWrapMode)0;
			_tooltipGO.AddComponent<RepairTooltipFollower>();
		}

		public static void ShowTooltip(string text)
		{
			if (!((Object)(object)_tooltipGO == (Object)null) && !((Object)(object)_tooltipText == (Object)null))
			{
				_tooltipText.text = text;
				_tooltipGO.SetActive(true);
				_tooltipGO.transform.SetAsLastSibling();
			}
		}

		public static void HideTooltip()
		{
			if ((Object)(object)_tooltipGO != (Object)null)
			{
				_tooltipGO.SetActive(false);
			}
		}

		public static GameObject MakeRect(string name, Transform parent, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				layer = 5
			};
			val.transform.SetParent(parent, false);
			((Graphic)val.AddComponent<Image>()).color = color;
			return val;
		}

		public static Text MakeText(string name, Transform parent, string text, int size, Color color, FontStyle style = (FontStyle)0)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.layer = 5;
			val.transform.SetParent(parent, false);
			Text obj = val.AddComponent<Text>();
			obj.text = text;
			obj.font = GetValheimFont();
			obj.fontSize = size;
			((Graphic)obj).color = color;
			obj.fontStyle = style;
			obj.alignment = (TextAnchor)4;
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.sizeDelta = Vector2.zero;
			component.anchoredPosition = Vector2.zero;
			return obj;
		}

		public static void SetRect(GameObject go, Vector2 min, Vector2 max, Vector2 size, Vector2 pos)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMin = min;
			component.anchorMax = max;
			component.sizeDelta = size;
			component.anchoredPosition = pos;
		}

		public static Font GetValheimFont()
		{
			Font[] array = Object.FindObjectsByType<Font>((FindObjectsSortMode)0);
			foreach (Font val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name.Contains("Averia"))
				{
					return val;
				}
			}
			return Resources.GetBuiltinResource<Font>("Arial.ttf");
		}
	}
	public static class CraftingStationAutoRepair
	{
		[HarmonyPatch(typeof(CraftingStation), "Start")]
		public static class CraftingStation_Start_Patch
		{
			public static void Postfix(CraftingStation __instance)
			{
				if (!IsWorkbench(__instance))
				{
					return;
				}
				ZNetView nview = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)nview == (Object)null || !nview.IsValid())
				{
					return;
				}
				nview.Register<bool, long, float, float, bool>("AutoBuildingRepair_SetEnabled", (Method<bool, long, float, float, bool>)delegate(long sender, bool enabled, long playerId, float radius, float interval, bool other)
				{
					if (Plugin.ModEnabled.Value && nview.IsValid() && nview.IsOwner())
					{
						Player player = Player.GetPlayer(playerId);
						ZNetView val = (((Object)(object)player != (Object)null) ? ((Component)player).GetComponent<ZNetView>() : null);
						if (!((Object)(object)val == (Object)null) && val.IsValid() && val.GetZDO().GetOwner() == sender && __instance.InUseDistance((Humanoid)(object)player))
						{
							ZDO zDO = nview.GetZDO();
							if (zDO.GetBool("VPO_AutoRepair_State", false) != enabled)
							{
								zDO.Set("VPO_AutoRepair_State", enabled);
								if (enabled)
								{
									zDO.Set("AutoBuildingRepair_Player", playerId);
									SaveSettings(zDO, radius, interval, other);
									if ((Object)(object)ZNet.instance != (Object)null)
									{
										zDO.Set("AutoBuildingRepair_LastRepairMs", (long)(ZNet.instance.GetTimeSeconds() * 1000.0));
										if ((Object)(object)EnvMan.instance != (Object)null)
										{
											zDO.Set("AutoBuildingRepair_LastDay", LastMorningDay());
										}
									}
								}
							}
							nview.InvokeRPC(sender, "AutoBuildingRepair_SetEnabledResult", new object[1] { enabled });
						}
					}
				});
				nview.Register<long, float, float, bool>("AutoBuildingRepair_Settings", (Method<long, float, float, bool>)delegate(long sender, long playerId, float radius, float interval, bool other)
				{
					if (nview.IsValid() && nview.IsOwner() && nview.GetZDO().GetLong("AutoBuildingRepair_Player", 0L) == playerId)
					{
						Player player = Player.GetPlayer(playerId);
						ZNetView val = (((Object)(object)player != (Object)null) ? ((Component)player).GetComponent<ZNetView>() : null);
						if ((Object)(object)val != (Object)null && val.IsValid() && val.GetZDO().GetOwner() == sender)
						{
							SaveSettings(nview.GetZDO(), radius, interval, other);
						}
					}
				});
				nview.Register<bool>("AutoBuildingRepair_SetEnabledResult", (Action<long, bool>)delegate(long sender, bool enabled)
				{
					if (nview.IsValid() && sender == nview.GetZDO().GetOwner() && (Object)(object)Player.m_localPlayer != (Object)null)
					{
						ShowToggleMessage(enabled);
					}
				});
			}
		}

		[HarmonyPatch(typeof(CraftingStation), "GetHoverText")]
		public static class CraftingStation_GetHoverText_Patch
		{
			public static void Postfix(CraftingStation __instance, ref string __result)
			{
				if (Plugin.ModEnabled.Value && IsWorkbench(__instance))
				{
					ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
					if (!((Object)(object)component == (Object)null) && component.IsValid())
					{
						string arg = (component.GetZDO().GetBool("VPO_AutoRepair_State", false) ? LocalizationHelper.T("<color=#55FF55>ON</color>", "<color=#55FF55>ВКЛ</color>", "<color=#55FF55>УВІМК</color>", "<color=#55FF55>ACT</color>") : LocalizationHelper.T("<color=#FF5555>OFF</color>", "<color=#FF5555>ВЫКЛ</color>", "<color=#FF5555>ВИМК</color>", "<color=#FF5555>DESACT</color>"));
						string format = LocalizationHelper.T("\n[<color=yellow><b>Hold $KEY_Use</b></color>] Auto-Repair: {0}", "\n[<color=yellow><b>Зажать $KEY_Use</b></color>] Автопочинка: {0}", "\n[<color=yellow><b>Затиснути $KEY_Use</b></color>] Автопочинка: {0}", "\n[<color=yellow><b>Mantener $KEY_Use</b></color>] Autorreparación: {0}");
						__result += Localization.instance.Localize(string.Format(format, arg));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		public static class Player_HoldE_Interaction_Patch
		{
			public static void Postfix(Player __instance)
			{
				//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !Plugin.ModEnabled.Value)
				{
					return;
				}
				if (!ZInput.GetButton("Use") && !ZInput.GetButton("JoyUse"))
				{
					_holdTimer = 0f;
					_holdExecuted = false;
					_heldStation = null;
					return;
				}
				GameObject hoverObject = ((Humanoid)__instance).GetHoverObject();
				CraftingStation val = (((Object)(object)hoverObject != (Object)null) ? hoverObject.GetComponentInParent<CraftingStation>() : null);
				if ((Object)(object)_heldStation != (Object)(object)val)
				{
					_heldStation = val;
					_holdTimer = 0f;
					_holdExecuted = false;
				}
				if (!IsWorkbench(val) || !val.InUseDistance((Humanoid)(object)__instance) || ((Character)__instance).IsDead())
				{
					_holdTimer = 0f;
					return;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					return;
				}
				_holdTimer += Time.deltaTime;
				if (_holdTimer >= 0.6f && !_holdExecuted)
				{
					_holdExecuted = true;
					if (PrivateArea.CheckAccess(((Component)val).transform.position, 0f, true, false))
					{
						ToggleStationAutoRepair(val, component);
					}
				}
			}

			private static void ToggleStationAutoRepair(CraftingStation station, ZNetView nview)
			{
				bool flag = !nview.GetZDO().GetBool("VPO_AutoRepair_State", false);
				nview.InvokeRPC("AutoBuildingRepair_SetEnabled", new object[5]
				{
					flag,
					Player.m_localPlayer.GetPlayerID(),
					Plugin.RepairRadius.Value,
					Plugin.RepairInterval.Value,
					Plugin.AllowRepairOther.Value
				});
			}
		}

		public const string ZDO_AUTO_REPAIR_KEY = "VPO_AutoRepair_State";

		private static readonly FieldInfo _allStationsField = AccessTools.Field(typeof(CraftingStation), "m_allStations");

		private static Collider[] _overlapBuffer = (Collider[])(object)new Collider[1024];

		private static readonly HashSet<Piece> _processedPieces = new HashSet<Piece>(512);

		private const string LastRepairKey = "AutoBuildingRepair_LastRepairMs";

		private const string LastDayKey = "AutoBuildingRepair_LastDay";

		private const string ToggleRpc = "AutoBuildingRepair_SetEnabled";

		private const string ToggleResultRpc = "AutoBuildingRepair_SetEnabledResult";

		private const string SettingsRpc = "AutoBuildingRepair_Settings";

		private const string RadiusKey = "AutoBuildingRepair_Radius";

		private const string IntervalKey = "AutoBuildingRepair_Interval";

		private const string OtherKey = "AutoBuildingRepair_Other";

		private const string PlayerKey = "AutoBuildingRepair_Player";

		private static float _nextSettingsSync;

		private static float _nextLoopCheckTime = 0f;

		private static float _holdTimer = 0f;

		private const float HOLD_REQUIRED_TIME = 0.6f;

		private static bool _holdExecuted = false;

		private static CraftingStation _heldStation;

		public static bool IsWorkbench(CraftingStation station)
		{
			if ((Object)(object)station == (Object)null)
			{
				return false;
			}
			if (station.m_name == "$piece_workbench")
			{
				return true;
			}
			return Utils.GetPrefabName(((Component)station).gameObject).Equals("piece_workbench", StringComparison.OrdinalIgnoreCase);
		}

		private static List<CraftingStation> GetStationList()
		{
			if (_allStationsField != null)
			{
				return _allStationsField.GetValue(null) as List<CraftingStation>;
			}
			return null;
		}

		public static void ShowPlayerMessage(MessageType type, string message)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage(type, message, 0, (Sprite)null, false, true);
			}
			else
			{
				if (!((Object)(object)Player.m_localPlayer != (Object)null))
				{
					return;
				}
				MethodInfo methodInfo = AccessTools.Method(typeof(Player), "Message", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					object[] array = new object[parameters.Length];
					if (parameters.Length != 0)
					{
						array[0] = type;
					}
					if (parameters.Length > 1)
					{
						array[1] = message;
					}
					for (int i = 2; i < parameters.Length; i++)
					{
						array[i] = (parameters[i].HasDefaultValue ? parameters[i].DefaultValue : null);
					}
					methodInfo.Invoke(Player.m_localPlayer, array);
				}
			}
		}

		public static void UpdateAutoRepairLoop()
		{
			if (!Plugin.ModEnabled.Value || (Object)(object)ZNet.instance == (Object)null || (Object)(object)EnvMan.instance == (Object)null || Time.time < _nextLoopCheckTime)
			{
				return;
			}
			_nextLoopCheckTime = Time.time + 0.25f;
			List<CraftingStation> stationList = GetStationList();
			if (stationList == null)
			{
				return;
			}
			long num = (long)(ZNet.instance.GetTimeSeconds() * 1000.0);
			int day = EnvMan.instance.GetDay(ZNet.instance.GetTimeSeconds());
			bool flag = EnvMan.IsDay();
			bool flag2 = Time.time >= _nextSettingsSync;
			if (flag2)
			{
				_nextSettingsSync = Time.time + 2f;
			}
			for (int i = 0; i < stationList.Count; i++)
			{
				CraftingStation val = stationList[i];
				if (!IsWorkbench(val))
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				ZDO zDO = component.GetZDO();
				if (!zDO.GetBool("VPO_AutoRepair_State", false))
				{
					continue;
				}
				if (component.IsOwner() && zDO.GetFloat("AutoBuildingRepair_Interval", -1f) < 0f)
				{
					SaveSettings(zDO, Plugin.RepairRadius.Value, Plugin.RepairInterval.Value, Plugin.AllowRepairOther.Value);
					Piece component2 = ((Component)val).GetComponent<Piece>();
					if ((Object)(object)component2 != (Object)null)
					{
						zDO.Set("AutoBuildingRepair_Player", component2.GetCreator());
					}
				}
				Player localPlayer = Player.m_localPlayer;
				if (flag2 && (Object)(object)localPlayer != (Object)null && zDO.GetLong("AutoBuildingRepair_Player", 0L) == localPlayer.GetPlayerID() && (zDO.GetFloat("AutoBuildingRepair_Radius", -1f) != Plugin.RepairRadius.Value || zDO.GetFloat("AutoBuildingRepair_Interval", -1f) != Plugin.RepairInterval.Value || zDO.GetBool("AutoBuildingRepair_Other", false) != Plugin.AllowRepairOther.Value))
				{
					component.InvokeRPC("AutoBuildingRepair_Settings", new object[4]
					{
						localPlayer.GetPlayerID(),
						Plugin.RepairRadius.Value,
						Plugin.RepairInterval.Value,
						Plugin.AllowRepairOther.Value
					});
				}
				if (!component.IsOwner())
				{
					continue;
				}
				float num2 = zDO.GetFloat("AutoBuildingRepair_Interval", Plugin.RepairInterval.Value);
				if (float.IsNaN(num2) || float.IsInfinity(num2))
				{
					continue;
				}
				bool flag3;
				if (num2 > 0f)
				{
					long num3 = zDO.GetLong("AutoBuildingRepair_LastRepairMs", -1L);
					if (num3 < 0 || num3 > num)
					{
						zDO.Set("AutoBuildingRepair_LastRepairMs", num);
						continue;
					}
					flag3 = (double)(num - num3) >= Math.Max(1000.0, (double)num2 * 1000.0);
				}
				else
				{
					int num4 = zDO.GetInt("AutoBuildingRepair_LastDay", int.MinValue);
					if (num4 == int.MinValue || num4 > day)
					{
						zDO.Set("AutoBuildingRepair_LastDay", LastMorningDay());
						continue;
					}
					flag3 = flag && day > num4;
				}
				if (flag3)
				{
					zDO.Set("AutoBuildingRepair_LastRepairMs", num);
					zDO.Set("AutoBuildingRepair_LastDay", LastMorningDay());
					PerformStationRepair(val, suppressMessage: false);
				}
			}
		}

		private static int LastMorningDay()
		{
			double timeSeconds = ZNet.instance.GetTimeSeconds();
			int day = EnvMan.instance.GetDay(timeSeconds);
			if (!(timeSeconds < EnvMan.instance.GetMorningStartSec(day)))
			{
				return day;
			}
			return day - 1;
		}

		private static void SaveSettings(ZDO zdo, float radius, float interval, bool other)
		{
			if (!float.IsNaN(radius) && !float.IsInfinity(radius) && !(radius <= 0f) && !float.IsNaN(interval) && !float.IsInfinity(interval) && !(interval < 0f))
			{
				zdo.Set("AutoBuildingRepair_Radius", radius);
				zdo.Set("AutoBuildingRepair_Interval", interval);
				zdo.Set("AutoBuildingRepair_Other", other);
			}
		}

		private static void ShowToggleMessage(bool enabled)
		{
			string message = (enabled ? LocalizationHelper.T("Workbench Auto-Repair: ENABLED", "Автопочинка верстака: ВКЛЮЧЕНА", "Автопочинка верстака: УВІМКНЕНА", "Autorreparación del banco: ACTIVADA") : LocalizationHelper.T("Workbench Auto-Repair: DISABLED", "Автопочинка верстака: ВЫКЛЮЧЕНА", "Автопочинка верстака: ВИМКНЕНА", "Autorreparación del banco: DESACTIVADA"));
			ShowPlayerMessage((MessageType)2, message);
		}

		private static int PerformStationRepair(CraftingStation station, bool suppressMessage)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = ((Component)station).GetComponent<ZNetView>().GetZDO();
			float num = zDO.GetFloat("AutoBuildingRepair_Radius", Plugin.RepairRadius.Value);
			if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f)
			{
				return 0;
			}
			int num2;
			for (num2 = Physics.OverlapSphereNonAlloc(((Component)station).transform.position, num, _overlapBuffer, Plugin.DestroyMask); num2 == _overlapBuffer.Length; num2 = Physics.OverlapSphereNonAlloc(((Component)station).transform.position, num, _overlapBuffer, Plugin.DestroyMask))
			{
				Array.Resize(ref _overlapBuffer, _overlapBuffer.Length * 2);
			}
			if (num2 == 0)
			{
				return 0;
			}
			int num3 = 0;
			_processedPieces.Clear();
			bool flag = zDO.GetBool("AutoBuildingRepair_Other", Plugin.AllowRepairOther.Value);
			Piece component = ((Component)station).GetComponent<Piece>();
			long num4 = zDO.GetLong("AutoBuildingRepair_Player", ((Object)(object)component != (Object)null) ? component.GetCreator() : 0);
			for (int i = 0; i < num2; i++)
			{
				Collider val = _overlapBuffer[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Piece componentInParent = ((Component)val).GetComponentInParent<Piece>();
				if ((Object)(object)componentInParent == (Object)null || !_processedPieces.Add(componentInParent) || (!flag && (num4 == 0L || componentInParent.GetCreator() != num4)))
				{
					continue;
				}
				WearNTear component2 = ((Component)componentInParent).GetComponent<WearNTear>();
				if (!((Object)(object)component2 == (Object)null))
				{
					ZNetView component3 = ((Component)component2).GetComponent<ZNetView>();
					if (!((Object)(object)component3 == (Object)null) && component3.IsValid() && component3.HasOwner() && component3.GetZDO().GetFloat(ZDOVars.s_health, component2.m_health) < component2.m_health - 0.05f && component2.Repair())
					{
						num3++;
					}
				}
			}
			if (!suppressMessage && num3 > 0 && Plugin.ShowRepairMessage.Value && (Object)(object)Player.m_localPlayer != (Object)null && Vector3.Distance(((Component)station).transform.position, ((Component)Player.m_localPlayer).transform.position) <= num)
			{
				string message = string.Format(LocalizationHelper.T("[AutoRepair] Repaired {0} pieces.", "[Автопочинка] Верстак починил {0} деталей.", "[Автопочинка] Верстак полагодив {0} деталей.", "[Autorreparación] Banco reparó {0} piezas."), num3);
				ShowPlayerMessage((MessageType)1, message);
			}
			return num3;
		}
	}
	[BepInPlugin("skarif.AutoBuildingRepair", "AutoBuildingRepair", "1.3.1814")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "skarif.AutoBuildingRepair";

		public const string ModName = "AutoBuildingRepair";

		public const string ModVersion = "1.3.1814";

		private Harmony _harmony;

		public static ConfigEntry<bool> ModEnabled;

		public static ConfigEntry<float> RepairRadius;

		public static ConfigEntry<float> RepairInterval;

		public static ConfigEntry<bool> AllowRepairOther;

		public static ConfigEntry<bool> ShowRepairMessage;

		public static ConfigEntry<KeyCode> MenuHotkey;

		public static int DestroyMask;

		public static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			DestroyMask = LayerMask.GetMask(new string[5] { "piece", "piece_nonsolid", "Default", "Default_small", "static_solid" });
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1. General", "Mod Enabled", true, "Enable or disable auto repair mod globally.");
			RepairRadius = ((BaseUnityPlugin)this).Config.Bind<float>("2. Repair", "Repair Radius", 20f, "Radius around crafting station to search and repair pieces.");
			RepairInterval = ((BaseUnityPlugin)this).Config.Bind<float>("2. Repair", "Repair Interval (s)", 0f, "Interval in seconds between repairs (0 = morning wake up).");
			AllowRepairOther = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Repair", "Allow Repair Other", true, "Allow repairing pieces built by other players.");
			ShowRepairMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("3. UI", "Show Notification", false, "Show top-left HUD message when pieces are repaired.");
			MenuHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("3. UI", "Settings Menu Hotkey", (KeyCode)289, "Hotkey to open the in-game settings menu.");
			AutoRepairSettingsMenu.ConfigInstance = ((BaseUnityPlugin)this).Config;
			_harmony = new Harmony("skarif.AutoBuildingRepair");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("[{0}] Loaded successfully. Press {1} to configure.", "AutoBuildingRepair", MenuHotkey.Value));
		}

		private void Update()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			CraftingStationAutoRepair.UpdateAutoRepairLoop();
			if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsDedicated())
			{
				if (AutoRepairSettingsMenu.IsOpen && Input.GetKeyDown((KeyCode)27) && (Object)(object)RepairKeyBindListener.ActiveListener == (Object)null)
				{
					AutoRepairSettingsMenu.CloseMenu();
				}
				else if ((Object)(object)RepairKeyBindListener.ActiveListener == (Object)null && Input.GetKeyDown(MenuHotkey.Value))
				{
					AutoRepairSettingsMenu.ToggleSettingsMenu();
				}
			}
		}

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