Decompiled source of ValheimLocationRestorer v0.3.0

plugins/ValheimLocationRestorer.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using SoftReferenceableAssets;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using ValheimLocationRestorer.Commands;
using ValheimLocationRestorer.Configuration;
using ValheimLocationRestorer.Core;
using ValheimLocationRestorer.Cycle;
using ValheimLocationRestorer.History;
using ValheimLocationRestorer.Locations;
using ValheimLocationRestorer.Logic;
using ValheimLocationRestorer.Network;
using ValheimLocationRestorer.Patches;
using ValheimLocationRestorer.Persistence;
using ValheimLocationRestorer.Protection;
using ValheimLocationRestorer.Restoration;
using ValheimLocationRestorer.Safety;
using ValheimLocationRestorer.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("VLR.IntegrationTests")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ValheimLocationRestorer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0")]
[assembly: AssemblyProduct("ValheimLocationRestorer")]
[assembly: AssemblyTitle("ValheimLocationRestorer")]
[assembly: AssemblyVersion("0.3.0.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 ValheimLocationRestorer
{
	internal sealed class ModContext
	{
		private const float WarmupSeconds = 10f;

		public readonly ConfigurationManager Config;

		public readonly PrefabAnalyzer Analyzer;

		public readonly LocationDatabase Database;

		public readonly SafetyManager Safety;

		public readonly BannerProtectionManager Banners;

		public readonly LocationScanner Scanner;

		public readonly WorldStateStore Store;

		public readonly HistoryManager History;

		public readonly RestorationEngine Engine;

		public readonly DungeonResetManager Dungeons;

		public readonly RestorationScheduler Scheduler;

		public readonly NetworkManager Network;

		public readonly SleepNotificationManager Notifications;

		public readonly WorldCycleManager Cycle;

		public readonly UIManager UI;

		private float _warmup;

		private int _delayNotifiedCycle = -1;

		public static ModContext Current { get; private set; }

		public bool WorldReady { get; private set; }

		public ModContext(ConfigurationManager config)
		{
			Current = this;
			Config = config;
			Analyzer = new PrefabAnalyzer();
			Database = new LocationDatabase();
			Safety = new SafetyManager(config, Analyzer);
			Banners = new BannerProtectionManager(config);
			Scanner = new LocationScanner(config, Database, Analyzer, Safety, Banners);
			Store = new WorldStateStore();
			History = new HistoryManager(config, Store);
			Engine = new RestorationEngine(config, Scanner, Analyzer, Safety, History, Store);
			Dungeons = new DungeonResetManager(Analyzer, Safety);
			Scheduler = new RestorationScheduler(config, Database, Engine, Dungeons, History);
			Network = new NetworkManager(config);
			Notifications = new SleepNotificationManager(config, Network);
			Cycle = new WorldCycleManager(config, Scheduler, Notifications, Store);
			UI = new UIManager(config, Network);
			Store.BeforeSave += ExportState;
			Scheduler.JobFinished += Network.OnJobFinished;
			Scheduler.JobDeferred += OnJobDeferred;
		}

		public void Tick(float deltaTime)
		{
			Texts.English = Config.EnglishUi;
			Network.Tick();
			UI.Tick();
			if (!GameApi.ServerWorldReady)
			{
				if (WorldReady)
				{
					UnloadWorld();
				}
				_warmup = 0f;
			}
			else
			{
				if (!Config.EnableMod.Value)
				{
					return;
				}
				if (!WorldReady)
				{
					_warmup += deltaTime;
					if (_warmup < 10f || !ZoneSystem.instance.LocationsGenerated)
					{
						return;
					}
					LoadWorld();
					if (!WorldReady)
					{
						return;
					}
				}
				Safety.SampleFrame(deltaTime);
				int currentDay = Cycle.CurrentDay;
				Banners.Tick(deltaTime, currentDay);
				if (Banners.Changed)
				{
					Banners.Changed = false;
					Store.MarkDirty();
				}
				Scanner.Tick(deltaTime);
				if (Scanner.Changed)
				{
					Scanner.Changed = false;
					Store.MarkDirty();
				}
				Cycle.Tick(deltaTime);
				Scheduler.Tick(deltaTime);
				History.Tick(deltaTime);
				Store.Tick(deltaTime);
			}
		}

		private void LoadWorld()
		{
			try
			{
				Store.Open(GameApi.GetWorldName(), GameApi.GetWorldUid());
				Analyzer.ClearCache();
				Analyzer.LoadUserRules();
				Banners.Reset();
				Banners.Load(Store.State.banners);
				Database.Build(Analyzer, Store.State.locations);
				Scanner.Reset();
				Scheduler.Reset();
				History.Load();
				Cycle.Load(Store.State.cycle, GameApi.GetCurrentDay());
				if (!GameApi.CanSpawnLocations)
				{
					Log.Error("Restauração indisponível nesta versão do jogo (SpawnLocation não encontrado). Varredura e proteção continuam ativas.");
				}
				RecoverInterruptedJobs();
				WorldReady = true;
				Log.Info("Mundo '" + GameApi.GetWorldName() + "' pronto. " + Cycle.Describe());
			}
			catch (Exception ex)
			{
				Log.Exception("Falha ao carregar o mundo no Location Restorer", ex);
				WorldReady = false;
				_warmup = -60f;
			}
		}

		private void RecoverInterruptedJobs()
		{
			List<JournalDto> list = Engine.LoadJournals();
			if (list.Count == 0)
			{
				return;
			}
			if (!Config.EnableRecoverySystem.Value)
			{
				Log.Warn($"{list.Count} restauração(ões) interrompida(s) encontradas, mas o sistema de recuperação está desativado.");
				return;
			}
			foreach (JournalDto item in list)
			{
				LocationRecord locationRecord = Database.Get(item.locationId);
				if (locationRecord == null)
				{
					Log.Warn("Diário de recuperação para local inexistente descartado: " + item.locationId);
					Engine.DropJournal(item.jobId);
				}
				else if (item.attempts >= Engine.MaxAttempts)
				{
					History.Record(HistoryResult.Failed, locationRecord.Id, locationRecord.PrefabName, "Recuperação", "Tentativas de recuperação esgotadas; verifique o local manualmente.");
					Engine.DropJournal(item.jobId);
				}
				else
				{
					RestorationJob restorationJob = Engine.CreateRecoveryJob(locationRecord, item);
					Scheduler.EnqueueRecovery(locationRecord, restorationJob);
					Log.Warn($"Retomando restauração interrompida de {locationRecord.Id} (fase '{item.phase}', tentativa {restorationJob.Attempts}).");
				}
			}
		}

		private void UnloadWorld()
		{
			Log.Info("Mundo descarregado: salvando estado do Location Restorer.");
			try
			{
				Scheduler.Reset();
				History.Flush();
				Store.SaveNow();
			}
			catch (Exception ex)
			{
				Log.Exception("Salvar ao descarregar", ex);
			}
			Store.Close();
			Cycle.Unload();
			Database.Clear();
			Banners.Reset();
			Engine.ClearJournals();
			History.Clear();
			WorldReady = false;
		}

		public void Shutdown()
		{
			if (WorldReady)
			{
				UnloadWorld();
			}
			UI.Destroy();
			if (Current == this)
			{
				Current = null;
			}
		}

		public void OnWorldSaved()
		{
			if (WorldReady)
			{
				Store.SaveNow();
				History.Flush();
			}
		}

		private void ExportState()
		{
			if (Store.State != null)
			{
				Database.Export(Store.State.locations);
				Banners.Export(Store.State.banners);
			}
		}

		private void OnJobDeferred(RestorationJob job)
		{
			if (job.Plan.Automatic && job.Plan.CycleId != _delayNotifiedCycle && job.Message != null && job.Message.IndexOf("Jogadores", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				_delayNotifiedCycle = job.Plan.CycleId;
				Notifications.SendDelayed();
			}
		}

		public string StatusText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Valheim Location Restorer 0.3.0");
			stringBuilder.AppendLine(Cycle.Describe());
			int count = Database.Count;
			int num = Database.All.Count((LocationRecord r) => r.Placed);
			int num2 = Database.All.Count((LocationRecord r) => r.Availability == LocationAvailability.Eligible);
			int num3 = Database.All.Count((LocationRecord r) => r.Availability == LocationAvailability.Protected);
			stringBuilder.AppendLine($"Locais: {count} no mundo, {num} gerados, {num2} livres, {num3} protegidos por bandeira.");
			stringBuilder.AppendLine($"Fila: {Scheduler.QueueCount} | em execução: {Scheduler.ActiveCount} | bandeiras ativas: {Banners.Count}" + (Banners.InitialScanComplete ? "" : " (primeira varredura em andamento)"));
			stringBuilder.Append("Restauração disponível: " + (GameApi.CanSpawnLocations ? "sim" : "NÃO (SpawnLocation ausente)"));
			return stringBuilder.ToString();
		}

		public string BannersText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Tipos reconhecidos: " + string.Join(", ", Banners.BannerPrefabNames.ToArray()));
			stringBuilder.AppendLine($"Raio: {Config.ProtectionRadius.Value:0} m | bandeiras registradas: {Banners.Count}");
			foreach (BannerEntry item in Banners.Banners.Take(40))
			{
				stringBuilder.AppendLine($"  {item.Prefab} em ({item.Position.x:0}, {item.Position.z:0}) desde o dia {item.FirstSeenDay}" + ((item.MissingScans > 0) ? $" [ausente em {item.MissingScans} varredura(s)]" : ""));
			}
			return stringBuilder.ToString();
		}

		public string Rescan(string idOrAll)
		{
			if (string.IsNullOrEmpty(idOrAll) || idOrAll.Equals("all", StringComparison.OrdinalIgnoreCase))
			{
				Banners.RequestRescan();
				foreach (LocationRecord item in Database.All)
				{
					item.Scanned = false;
				}
				return "Nova varredura de bandeiras agendada; locais serão reavaliados.";
			}
			LocationRecord locationRecord = Database.Get(idOrAll);
			if (locationRecord == null)
			{
				return "Local não encontrado: " + idOrAll;
			}
			Scanner.Scan(locationRecord);
			return $"{locationRecord.Id}: {locationRecord.Condition}, {locationRecord.Availability} {locationRecord.Reason}";
		}
	}
	[BepInPlugin("Braian.ValheimLocationRestorer", "Valheim Location Restorer", "0.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "Braian.ValheimLocationRestorer";

		public const string PluginName = "Valheim Location Restorer";

		public const string PluginVersion = "0.3.0";

		private Harmony _harmony;

		private ModContext _context;

		private void Awake()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			Log.Init(((BaseUnityPlugin)this).Logger);
			try
			{
				ConfigurationManager config = new ConfigurationManager(((BaseUnityPlugin)this).Config);
				Log.DebugEnabled = () => config.EnableDebugLogs.Value;
				_context = new ModContext(config);
				_harmony = new Harmony("Braian.ValheimLocationRestorer");
				_harmony.PatchAll(typeof(Plugin).Assembly);
				OptionalPatches.Apply(_harmony, _context);
				RestorerCommand.Register();
				Log.Info("Valheim Location Restorer 0.3.0 carregado.");
			}
			catch (Exception ex)
			{
				Log.Exception("Valheim Location Restorer falhou ao iniciar", ex);
			}
		}

		private void Update()
		{
			try
			{
				_context?.Tick(Time.unscaledDeltaTime);
			}
			catch (Exception ex)
			{
				Log.Exception("Update", ex);
			}
		}

		private void OnDestroy()
		{
			try
			{
				_context?.Shutdown();
			}
			catch (Exception ex)
			{
				Log.Exception("Shutdown", ex);
			}
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}
namespace ValheimLocationRestorer.UI
{
	internal sealed class UIManager
	{
		private sealed class RowWidgets
		{
			public GameObject Root;

			public GameObject Name;

			public GameObject Biome;

			public GameObject Coords;

			public GameObject Distance;

			public GameObject State;

			public GameObject Protection;

			public GameObject Line;

			public Button View;

			public Button Restore;

			public LocationRow Data;
		}

		private const float Width = 1000f;

		private const float Height = 700f;

		private const int Rows = 12;

		private const float RowTop = 175f;

		private const float RowHeight = 30f;

		private readonly ConfigurationManager _config;

		private readonly NetworkManager _network;

		private GameObject _panel;

		private GameObject _title;

		private GameObject _header;

		private GameObject _pageLabel;

		private GameObject _status;

		private GameObject _selectedLabel;

		private readonly List<RowWidgets> _rows = new List<RowWidgets>();

		private readonly List<KeyValuePair<int, Button>> _categoryButtons = new List<KeyValuePair<int, Button>>();

		private readonly List<KeyValuePair<RestorationMode, Button>> _modeButtons = new List<KeyValuePair<RestorationMode, Button>>();

		private readonly List<KeyValuePair<ElementClass, Button>> _classButtons = new List<KeyValuePair<ElementClass, Button>>();

		private Button _exteriorButton;

		private Button _interiorButton;

		private GameObject _optionsRoot;

		private GameObject _customRoot;

		private bool _historyTab;

		private int _category = -1;

		private int _page;

		private int _totalPages = 1;

		private LocationPage _lastPage;

		private LocationRow _selected;

		private RestorationMode _mode;

		private ElementClass _customClasses = ElementClass.All;

		private bool _customExterior = true;

		private bool _customInterior = true;

		public bool IsOpen
		{
			get
			{
				if ((Object)(object)_panel != (Object)null)
				{
					return _panel.activeSelf;
				}
				return false;
			}
		}

		public UIManager(ConfigurationManager config, NetworkManager network)
		{
			_config = config;
			_network = network;
			_network.LocationPageReceived += OnLocationPage;
			_network.HistoryPageReceived += OnHistoryPage;
			_network.TextReceived += delegate(string text)
			{
				SetStatus(text);
			};
		}

		public void Tick()
		{
			//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)
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				if (IsOpen)
				{
					Close();
				}
			}
			else if (IsOpen && Input.GetKeyDown((KeyCode)27))
			{
				Close();
			}
			else if (!TextInputBusy())
			{
				KeyboardShortcut value = _config.UiToggleKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					Toggle();
				}
			}
		}

		private static bool TextInputBusy()
		{
			try
			{
				if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
				{
					return true;
				}
				if (Console.IsVisible())
				{
					return true;
				}
				if (TextInput.IsVisible())
				{
					return true;
				}
				if (Menu.IsVisible())
				{
					return true;
				}
			}
			catch (Exception ex)
			{
				Log.Debug("TextInputBusy: " + ex.Message);
			}
			return false;
		}

		public void Toggle()
		{
			if (IsOpen)
			{
				Close();
			}
			else
			{
				Open();
			}
		}

		private static bool LocalPlayerMayAdmin(ConfigurationManager config)
		{
			if (!config.ValidateServerPermissions.Value)
			{
				return true;
			}
			if (GameApi.IsServer)
			{
				return true;
			}
			try
			{
				return SynchronizationManager.Instance.PlayerIsAdmin;
			}
			catch
			{
				return false;
			}
		}

		public void Open()
		{
			if (GameApi.InWorld)
			{
				if (!LocalPlayerMayAdmin(_config))
				{
					GameApi.ShowLocalCenterMessage(Texts.Get("no.permission"));
				}
				else if (!((Object)(object)_panel == (Object)null) || Build())
				{
					_panel.SetActive(true);
					GUIManager.BlockInput(true);
					RefreshTexts();
					Request();
				}
			}
		}

		public void Close()
		{
			if (!((Object)(object)_panel == (Object)null))
			{
				if (_panel.activeSelf)
				{
					GUIManager.BlockInput(false);
				}
				_panel.SetActive(false);
			}
		}

		public void Destroy()
		{
			Close();
			if ((Object)(object)_panel != (Object)null)
			{
				Object.Destroy((Object)(object)_panel);
			}
			_panel = null;
			_rows.Clear();
			_categoryButtons.Clear();
			_modeButtons.Clear();
			_classButtons.Clear();
		}

		private bool Build()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: 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_02e2: Unknown result type (might be due to invalid IL or missing references)
			if (GUIManager.Instance == null || (Object)(object)GUIManager.CustomGUIFront == (Object)null)
			{
				Log.Warn("GUI do Jötunn indisponível; painel não criado.");
				return false;
			}
			try
			{
				_panel = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, 1000f, 700f, true);
				((Object)_panel).name = "ValheimLocationRestorerPanel";
				Transform transform = _panel.transform;
				_title = Label(transform, 20f, 12f, 960f, 36f, Texts.Get("title"), 26, GUIManager.Instance.ValheimOrange, (TextAnchor)4);
				Btn(transform, 20f, 55f, 140f, 32f, Texts.Get("tab.locations"), delegate
				{
					_historyTab = false;
					_page = 0;
					Request();
				});
				Btn(transform, 170f, 55f, 140f, 32f, Texts.Get("tab.history"), delegate
				{
					_historyTab = true;
					_page = 0;
					Request();
				});
				Btn(transform, 320f, 55f, 140f, 32f, Texts.Get("refresh"), delegate
				{
					_network.RequestRescan("all");
					Request();
				});
				Btn(transform, 840f, 55f, 140f, 32f, Texts.Get("close"), Close);
				float x = 20f;
				AddCategoryButton(transform, ref x, -1, Texts.Get("all"));
				LocationCategory[] restorable = LocationCategoryNames.Restorable;
				foreach (LocationCategory locationCategory in restorable)
				{
					AddCategoryButton(transform, ref x, (int)locationCategory, Texts.Category(locationCategory));
				}
				_header = Label(transform, 20f, 140f, 960f, 28f, "", 15, GUIManager.Instance.ValheimOrange, (TextAnchor)3);
				for (int num2 = 0; num2 < 12; num2++)
				{
					_rows.Add(BuildRow(transform, 175f + (float)num2 * 30f));
				}
				float num3 = 541f;
				Btn(transform, 20f, num3, 130f, 30f, Texts.Get("prev"), delegate
				{
					if (_page > 0)
					{
						_page--;
						Request();
					}
				});
				_pageLabel = Label(transform, 160f, num3, 200f, 30f, "", 15, Color.white, (TextAnchor)4);
				Btn(transform, 370f, num3, 130f, 30f, Texts.Get("next"), delegate
				{
					if (_page < _totalPages - 1)
					{
						_page++;
						Request();
					}
				});
				BuildOptions(transform, num3 + 38f);
				_status = Label(transform, 20f, 660f, 960f, 30f, "", 14, Color.white, (TextAnchor)3);
				_panel.SetActive(false);
				return true;
			}
			catch (Exception ex)
			{
				Log.Exception("Falha ao criar o painel", ex);
				if ((Object)(object)_panel != (Object)null)
				{
					Object.Destroy((Object)(object)_panel);
				}
				_panel = null;
				return false;
			}
		}

		private void AddCategoryButton(Transform root, ref float x, int category, string label)
		{
			int captured = category;
			Button val = Btn(root, x, 98f, 104f, 30f, label, delegate
			{
				_category = captured;
				_page = 0;
				_historyTab = false;
				Request();
			});
			SetFontSize(((Component)val).gameObject, 12);
			_categoryButtons.Add(new KeyValuePair<int, Button>(category, val));
			x += 108f;
		}

		private RowWidgets BuildRow(Transform root, float y)
		{
			//IL_002c: 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_007e: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			RowWidgets rowWidgets = new RowWidgets();
			rowWidgets.Name = Label(root, 20f, y, 230f, 30f, "", 14, Color.white, (TextAnchor)3);
			rowWidgets.Biome = Label(root, 255f, y, 90f, 30f, "", 13, Color.white, (TextAnchor)3);
			rowWidgets.Coords = Label(root, 350f, y, 120f, 30f, "", 13, Color.white, (TextAnchor)3);
			rowWidgets.Distance = Label(root, 475f, y, 65f, 30f, "", 13, Color.white, (TextAnchor)3);
			rowWidgets.State = Label(root, 545f, y, 110f, 30f, "", 13, Color.white, (TextAnchor)3);
			rowWidgets.Protection = Label(root, 660f, y, 160f, 30f, "", 13, Color.white, (TextAnchor)3);
			rowWidgets.Line = Label(root, 20f, y, 960f, 30f, "", 12, Color.white, (TextAnchor)3);
			RowWidgets captured = rowWidgets;
			rowWidgets.View = Btn(root, 825f, y + 2f, 55f, 26f, Texts.Get("view"), delegate
			{
				OnView(captured);
			});
			rowWidgets.Restore = Btn(root, 885f, y + 2f, 95f, 26f, Texts.Get("restore"), delegate
			{
				OnSelect(captured);
			});
			SetFontSize(((Component)rowWidgets.View).gameObject, 12);
			SetFontSize(((Component)rowWidgets.Restore).gameObject, 12);
			return rowWidgets;
		}

		private void BuildOptions(Transform root, float y)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			_optionsRoot = new GameObject("Options", new Type[1] { typeof(RectTransform) });
			_optionsRoot.transform.SetParent(root, false);
			Stretch(_optionsRoot);
			Transform transform = _optionsRoot.transform;
			_selectedLabel = Label(transform, 20f, y, 300f, 30f, "", 14, GUIManager.Instance.ValheimOrange, (TextAnchor)3);
			float num = 330f;
			foreach (RestorationMode value in Enum.GetValues(typeof(RestorationMode)))
			{
				RestorationMode captured = value;
				Button val = Btn(transform, num, y, 120f, 30f, ModeLabel(value), delegate
				{
					_mode = captured;
					RefreshOptions();
				});
				SetFontSize(((Component)val).gameObject, 13);
				_modeButtons.Add(new KeyValuePair<RestorationMode, Button>(value, val));
				num += 124f;
			}
			Btn(transform, 830f, y, 70f, 30f, Texts.Get("confirm"), OnConfirm);
			Btn(transform, 905f, y, 75f, 30f, Texts.Get("cancel"), delegate
			{
				_selected = null;
				RefreshOptions();
			});
			_customRoot = new GameObject("Custom", new Type[1] { typeof(RectTransform) });
			_customRoot.transform.SetParent(transform, false);
			Stretch(_customRoot);
			Transform transform2 = _customRoot.transform;
			float y2 = y + 36f;
			float num2 = 20f;
			KeyValuePair<ElementClass, string>[] array = new KeyValuePair<ElementClass, string>[7]
			{
				new KeyValuePair<ElementClass, string>(ElementClass.Structures, "cls.structures"),
				new KeyValuePair<ElementClass, string>(ElementClass.Doors, "cls.doors"),
				new KeyValuePair<ElementClass, string>(ElementClass.Containers, "cls.containers"),
				new KeyValuePair<ElementClass, string>(ElementClass.Creatures, "cls.creatures"),
				new KeyValuePair<ElementClass, string>(ElementClass.Resources, "cls.resources"),
				new KeyValuePair<ElementClass, string>(ElementClass.DungeonLayout, "cls.layout"),
				new KeyValuePair<ElementClass, string>(ElementClass.Other, "cls.other")
			};
			for (int num3 = 0; num3 < array.Length; num3++)
			{
				KeyValuePair<ElementClass, string> keyValuePair = array[num3];
				ElementClass captured2 = keyValuePair.Key;
				Button val2 = Btn(transform2, num2, y2, 108f, 28f, Texts.Get(keyValuePair.Value), delegate
				{
					_customClasses ^= captured2;
					RefreshOptions();
				});
				SetFontSize(((Component)val2).gameObject, 12);
				_classButtons.Add(new KeyValuePair<ElementClass, Button>(keyValuePair.Key, val2));
				num2 += 112f;
			}
			_exteriorButton = Btn(transform2, num2, y2, 90f, 28f, Texts.Get("region.exterior"), delegate
			{
				_customExterior = !_customExterior;
				RefreshOptions();
			});
			_interiorButton = Btn(transform2, num2 + 94f, y2, 90f, 28f, Texts.Get("region.interior"), delegate
			{
				_customInterior = !_customInterior;
				RefreshOptions();
			});
			SetFontSize(((Component)_exteriorButton).gameObject, 12);
			SetFontSize(((Component)_interiorButton).gameObject, 12);
			RefreshOptions();
		}

		private void Request()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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)
			SetStatus(Texts.Get("loading"));
			if (_historyTab)
			{
				_network.RequestHistory(_page);
			}
			else
			{
				Vector3 reference = (((Object)(object)Player.m_localPlayer != (Object)null) ? ((Component)Player.m_localPlayer).transform.position : Vector3.zero);
				_network.RequestList(_category, _page, reference, onlyEligible: false, string.Empty);
			}
			RefreshTexts();
		}

		private void OnLocationPage(LocationPage page)
		{
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			if (!IsOpen || _historyTab)
			{
				return;
			}
			_lastPage = page;
			_page = page.Page;
			_totalPages = page.TotalPages;
			SetText(_header, string.Format("{0,-28} {1}        {2}          ", Texts.Get("col.name"), Texts.Get("col.biome"), Texts.Get("col.coords")) + Texts.Get("col.distance") + "     " + Texts.Get("col.state") + "              " + Texts.Get("col.protection"));
			for (int i = 0; i < _rows.Count; i++)
			{
				RowWidgets rowWidgets = _rows[i];
				LocationRow locationRow = (rowWidgets.Data = ((i < page.Rows.Count) ? page.Rows[i] : null));
				SetRowMode(rowWidgets, history: false, locationRow != null);
				if (locationRow != null)
				{
					SetText(rowWidgets.Name, (locationRow.HasInterior ? "◆ " : "") + locationRow.Name);
					SetText(rowWidgets.Biome, locationRow.Biome);
					SetText(rowWidgets.Coords, $"{locationRow.Position.x:0}, {locationRow.Position.z:0}");
					SetText(rowWidgets.Distance, $"{locationRow.Distance:0} m");
					GameObject state = rowWidgets.State;
					LocationCondition condition = (LocationCondition)locationRow.Condition;
					SetText(state, Texts.Get("cond." + condition) + ActivitySuffix(locationRow.Activity));
					LocationAvailability availability = (LocationAvailability)locationRow.Availability;
					SetText(rowWidgets.Protection, Texts.Get("avail." + availability));
					SetColor(rowWidgets.Protection, (availability == LocationAvailability.Eligible) ? new Color(0.6f, 1f, 0.6f) : new Color(1f, 0.75f, 0.45f));
					((Selectable)rowWidgets.Restore).interactable = availability == LocationAvailability.Eligible;
				}
			}
			SetText(_pageLabel, $"{page.Page + 1} / {page.TotalPages}  ({page.Total})");
			SetStatus(string.Empty);
			RefreshTexts();
		}

		private void OnHistoryPage(HistoryPage page)
		{
			if (!IsOpen || !_historyTab)
			{
				return;
			}
			_page = page.Page;
			_totalPages = page.TotalPages;
			SetText(_header, Texts.Get("tab.history"));
			for (int i = 0; i < _rows.Count; i++)
			{
				RowWidgets rowWidgets = _rows[i];
				rowWidgets.Data = null;
				bool flag = i < page.Lines.Count;
				SetRowMode(rowWidgets, history: true, flag);
				if (flag)
				{
					SetText(rowWidgets.Line, page.Lines[i]);
				}
			}
			SetText(_pageLabel, $"{page.Page + 1} / {page.TotalPages}");
			SetStatus(string.Empty);
			_selected = null;
			RefreshOptions();
		}

		private static string ActivitySuffix(int activity)
		{
			return (LocationActivity)activity switch
			{
				LocationActivity.Queued => " (fila)", 
				LocationActivity.Deferred => " (adiado)", 
				LocationActivity.Restoring => " (restaurando)", 
				_ => string.Empty, 
			};
		}

		private void SetRowMode(RowWidgets w, bool history, bool visible)
		{
			GameObject[] array = (GameObject[])(object)new GameObject[6] { w.Name, w.Biome, w.Coords, w.Distance, w.State, w.Protection };
			for (int i = 0; i < array.Length; i++)
			{
				array[i].SetActive(visible && !history);
			}
			((Component)w.View).gameObject.SetActive(visible && !history);
			((Component)w.Restore).gameObject.SetActive(visible && !history);
			w.Line.SetActive(visible && history);
		}

		private void OnView(RowWidgets row)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (row.Data != null)
			{
				bool flag = GameApi.ShowOnMap(row.Data.Position, row.Data.Name);
				SetStatus($"{row.Data.Name}: x={row.Data.Position.x:0} z={row.Data.Position.z:0}" + (flag ? " — mapa" : ""));
			}
		}

		private void OnSelect(RowWidgets row)
		{
			if (row.Data != null)
			{
				_selected = row.Data;
				if (!_selected.HasInterior && _mode == RestorationMode.Dungeon)
				{
					_mode = RestorationMode.Complete;
				}
				RefreshOptions();
			}
		}

		private void OnConfirm()
		{
			if (_selected != null)
			{
				ElementClass classes = ((_mode == RestorationMode.Custom) ? _customClasses : ElementClass.All);
				_network.RequestRestore(_selected.Id, _mode, classes, _customExterior, _customInterior, force: false);
				SetStatus(Texts.Get("request.sent") + " " + _selected.Name + " — " + ModeLabel(_mode));
				_selected = null;
				RefreshOptions();
			}
		}

		private void RefreshTexts()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<int, Button> categoryButton in _categoryButtons)
			{
				SetColor(((Component)categoryButton.Value).gameObject, (!_historyTab && categoryButton.Key == _category) ? GUIManager.Instance.ValheimOrange : Color.white);
			}
		}

		private void RefreshOptions()
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: 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_018c: 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_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_optionsRoot == (Object)null)
			{
				return;
			}
			_optionsRoot.SetActive(_selected != null);
			if (_selected == null)
			{
				return;
			}
			SetText(_selectedLabel, Texts.Get("selected") + ": " + _selected.Name);
			foreach (KeyValuePair<RestorationMode, Button> modeButton in _modeButtons)
			{
				((Selectable)modeButton.Value).interactable = modeButton.Key != RestorationMode.Dungeon || _selected.HasInterior;
				SetColor(((Component)modeButton.Value).gameObject, (modeButton.Key == _mode) ? GUIManager.Instance.ValheimOrange : Color.white);
			}
			_customRoot.SetActive(_mode == RestorationMode.Custom);
			foreach (KeyValuePair<ElementClass, Button> classButton in _classButtons)
			{
				SetColor(((Component)classButton.Value).gameObject, (Color)(((_customClasses & classButton.Key) != ElementClass.None) ? GUIManager.Instance.ValheimOrange : new Color(0.55f, 0.55f, 0.55f)));
			}
			SetColor(((Component)_exteriorButton).gameObject, (Color)(_customExterior ? GUIManager.Instance.ValheimOrange : new Color(0.55f, 0.55f, 0.55f)));
			SetColor(((Component)_interiorButton).gameObject, (Color)(_customInterior ? GUIManager.Instance.ValheimOrange : new Color(0.55f, 0.55f, 0.55f)));
			((Selectable)_interiorButton).interactable = _selected.HasInterior;
		}

		private static string ModeLabel(RestorationMode mode)
		{
			return mode switch
			{
				RestorationMode.Complete => Texts.Get("mode.complete"), 
				RestorationMode.Structural => Texts.Get("mode.structural"), 
				RestorationMode.Dungeon => Texts.Get("mode.dungeon"), 
				_ => Texts.Get("mode.custom"), 
			};
		}

		private void SetStatus(string text)
		{
			if ((Object)(object)_status != (Object)null)
			{
				SetText(_status, text ?? string.Empty);
			}
		}

		private static Vector2 TopLeftCenter(float x, float y, float w, float h)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2(x + w / 2f, 0f - (y + h / 2f));
		}

		private static GameObject Label(Transform parent, float x, float y, float w, float h, string text, int size, Color color, TextAnchor anchor)
		{
			//IL_0012: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GUIManager.Instance.CreateText(text, parent, new Vector2(0f, 1f), new Vector2(0f, 1f), TopLeftCenter(x, y, w, h), GUIManager.Instance.AveriaSerifBold, size, color, true, Color.black, w, h, false);
			Text component = obj.GetComponent<Text>();
			if ((Object)(object)component != (Object)null)
			{
				component.alignment = anchor;
				component.horizontalOverflow = (HorizontalWrapMode)0;
				component.verticalOverflow = (VerticalWrapMode)0;
			}
			return obj;
		}

		private static Button Btn(Transform parent, float x, float y, float w, float h, string text, Action onClick)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_0062: Expected O, but got Unknown
			Button component = GUIManager.Instance.CreateButton(text, parent, new Vector2(0f, 1f), new Vector2(0f, 1f), TopLeftCenter(x, y, w, h), w, h).GetComponent<Button>();
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				try
				{
					onClick();
				}
				catch (Exception ex)
				{
					Log.Exception("UI", ex);
				}
			});
			return component;
		}

		private static void Stretch(GameObject go)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)go.transform;
			val.anchorMin = Vector2.zero;
			val.anchorMax = Vector2.one;
			val.offsetMin = Vector2.zero;
			val.offsetMax = Vector2.zero;
		}

		private static void SetText(GameObject go, string text)
		{
			if ((Object)(object)go == (Object)null)
			{
				return;
			}
			Text componentInChildren = go.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.text = text;
				return;
			}
			Component[] componentsInChildren = go.GetComponentsInChildren<Component>(true);
			foreach (Component val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					PropertyInfo property = ((object)val).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
					if (property != null && property.PropertyType == typeof(string) && property.CanWrite)
					{
						property.SetValue(val, text, null);
						break;
					}
				}
			}
		}

		private static void SetColor(GameObject go, Color color)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)go == (Object)null)
			{
				return;
			}
			Text componentInChildren = go.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Graphic)componentInChildren).color = color;
				return;
			}
			Component[] componentsInChildren = go.GetComponentsInChildren<Component>(true);
			foreach (Component val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && ((object)val).GetType().Name.Contains("Text"))
				{
					PropertyInfo property = ((object)val).GetType().GetProperty("color", BindingFlags.Instance | BindingFlags.Public);
					if (property != null && property.PropertyType == typeof(Color) && property.CanWrite)
					{
						property.SetValue(val, color, null);
						break;
					}
				}
			}
		}

		private static void SetFontSize(GameObject go, int size)
		{
			Text componentInChildren = go.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.fontSize = size;
				return;
			}
			Component[] componentsInChildren = go.GetComponentsInChildren<Component>(true);
			foreach (Component val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && ((object)val).GetType().Name.Contains("Text"))
				{
					PropertyInfo property = ((object)val).GetType().GetProperty("fontSize", BindingFlags.Instance | BindingFlags.Public);
					if (property != null && property.PropertyType == typeof(float) && property.CanWrite)
					{
						property.SetValue(val, (float)size, null);
						break;
					}
				}
			}
		}
	}
}
namespace ValheimLocationRestorer.Safety
{
	internal sealed class SafetyManager
	{
		private readonly ConfigurationManager _config;

		private readonly PrefabAnalyzer _analyzer;

		private readonly List<Vector3> _players = new List<Vector3>();

		private float _averageFrame = 0.016f;

		public bool ServerBusy => _averageFrame > 0.1f;

		public float AverageFrameMs => _averageFrame * 1000f;

		public SafetyManager(ConfigurationManager config, PrefabAnalyzer analyzer)
		{
			_config = config;
			_analyzer = analyzer;
		}

		public void SampleFrame(float unscaledDeltaTime)
		{
			_averageFrame = Mathf.Lerp(_averageFrame, Mathf.Min(unscaledDeltaTime, 1f), 0.05f);
		}

		public bool IsLocationExcluded(LocationAnalysis analysis, out string reason)
		{
			if (analysis == null)
			{
				reason = "Análise indisponível";
				return true;
			}
			reason = analysis.ExclusionReason;
			return analysis.Excluded;
		}

		public bool IsProtectedObject(ZDO zdo, out string reason)
		{
			int prefab = zdo.GetPrefab();
			ObjectInfo objectInfo = _analyzer.GetObjectInfo(prefab);
			if (prefab == GameApi.PrefabPlayer)
			{
				reason = "Jogador";
				return true;
			}
			if (prefab == GameApi.PrefabTombstone || objectInfo.IsTombstone)
			{
				reason = "Lápide de jogador";
				return true;
			}
			if (prefab == GameApi.PrefabLocationProxy || prefab == GameApi.PrefabZoneCtrl || prefab == GameApi.PrefabTerrainCompiler)
			{
				reason = "Objeto de sistema";
				return true;
			}
			if (GameApi.IsPlayerCreated(zdo))
			{
				reason = "Construído/colocado por jogador";
				return true;
			}
			if (GameApi.IsTamed(zdo))
			{
				reason = "Animal domesticado";
				return true;
			}
			if (objectInfo.IsItemDrop)
			{
				reason = "Item solto";
				return true;
			}
			if (objectInfo.IsGuarded)
			{
				reason = "Objeto de progressão de boss";
				return true;
			}
			if (!objectInfo.Known)
			{
				reason = "Prefab desconhecido (mod removido?)";
				return true;
			}
			reason = null;
			return false;
		}

		public bool IsPlayerContent(ZDO zdo)
		{
			int prefab = zdo.GetPrefab();
			if (prefab != GameApi.PrefabTombstone && !_analyzer.GetObjectInfo(prefab).IsTombstone && !GameApi.IsPlayerCreated(zdo))
			{
				return GameApi.IsTamed(zdo);
			}
			return true;
		}

		public bool AnyPlayerOnSurfaceNear(Vector3 center, float radius)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			GameApi.GetPlayerPositions(_players);
			float num = radius * radius;
			foreach (Vector3 player in _players)
			{
				if (!GameApi.IsInterior(player))
				{
					float num2 = player.x - center.x;
					float num3 = player.z - center.z;
					if (num2 * num2 + num3 * num3 <= num)
					{
						return true;
					}
				}
			}
			return false;
		}

		public bool AnyPlayerInsideInterior(Vector2s zone)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			GameApi.GetPlayerPositions(_players);
			foreach (Vector3 player in _players)
			{
				if (GameApi.IsInterior(player))
				{
					Vector2s zone2 = GameApi.GetZone(player);
					if (Mathf.Abs(zone2.x - zone.x) <= 1 && Mathf.Abs(zone2.y - zone.y) <= 1)
					{
						return true;
					}
				}
			}
			return false;
		}

		public int ConnectedPlayerCount()
		{
			GameApi.GetPlayerPositions(_players);
			return _players.Count;
		}
	}
}
namespace ValheimLocationRestorer.Restoration
{
	internal sealed class DungeonResetManager
	{
		private readonly PrefabAnalyzer _analyzer;

		private readonly SafetyManager _safety;

		public DungeonResetManager(PrefabAnalyzer analyzer, SafetyManager safety)
		{
			_analyzer = analyzer;
			_safety = safety;
		}

		public bool IsDungeon(LocationRecord record)
		{
			return _analyzer.Analyze(record?.Location)?.HasInterior ?? false;
		}

		public string Check(LocationRecord record)
		{
			if (record == null)
			{
				return "Local não encontrado.";
			}
			if (!IsDungeon(record))
			{
				return "O local não possui interior de masmorra.";
			}
			return null;
		}

		public bool PlayersInside(LocationRecord record)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (IsDungeon(record))
			{
				return _safety.AnyPlayerInsideInterior(record.Zone);
			}
			return false;
		}

		public RestorationPlan AutomaticPlanFor(LocationRecord record, RestorationMode configuredMode)
		{
			return RestorationPlan.Create(configuredMode);
		}
	}
	internal enum JobPhase
	{
		Validate,
		Prepare,
		Remove,
		Spawn,
		PostFilter,
		Finalize,
		Done,
		Deferred,
		Skipped,
		Failed
	}
	internal sealed class RestorationJob
	{
		public readonly string Id = Guid.NewGuid().ToString("N").Substring(0, 12);

		public LocationRecord Record;

		public RestorationPlan Plan;

		public JobPhase Phase;

		public LocationAnalysis Analysis;

		public LocationArea Area;

		public readonly Queue<ZDO> ToRemove = new Queue<ZDO>();

		public readonly Dictionary<int, List<Vector3>> Kept = new Dictionary<int, List<Vector3>>();

		public readonly Queue<ZDO> NewObjects = new Queue<ZDO>();

		public readonly List<ZDO> ExteriorCandidates = new List<ZDO>();

		public readonly Queue<ZDO> Replaced = new Queue<ZDO>();

		public int Removed;

		public int Spawned;

		public int Discarded;

		public int Duplicates;

		public int Collapsed;

		public int Attempts;

		public int SpawnWaits;

		public bool LoadedZone;

		public string Message = string.Empty;

		public Action ReleasePrefab;

		public bool Finished => Phase >= JobPhase.Done;
	}
	internal sealed class RestorationEngine
	{
		private const float DuplicateDistance = 0.35f;

		private const float DuplicateHeight = 2.5f;

		private const float LooseItemDuplicateDistance = 2f;

		private const float ProxyDuplicateDistance = 6f;

		private const int MaxRecoveryAttempts = 3;

		private const int MaxSpawnWaits = 600;

		private readonly ConfigurationManager _config;

		private readonly LocationScanner _scanner;

		private readonly PrefabAnalyzer _analyzer;

		private readonly SafetyManager _safety;

		private readonly HistoryManager _history;

		private readonly WorldStateStore _store;

		private readonly List<ZDO> _buffer = new List<ZDO>();

		private readonly List<ZDO> _created = new List<ZDO>();

		private readonly List<JournalDto> _journals = new List<JournalDto>();

		public int MaxAttempts => 3;

		public RestorationEngine(ConfigurationManager config, LocationScanner scanner, PrefabAnalyzer analyzer, SafetyManager safety, HistoryManager history, WorldStateStore store)
		{
			_config = config;
			_scanner = scanner;
			_analyzer = analyzer;
			_safety = safety;
			_history = history;
			_store = store;
		}

		public List<JournalDto> LoadJournals()
		{
			_journals.Clear();
			JournalFileDto journalFileDto = WorldStateStore.ReadJson<JournalFileDto>(_store.JournalPath);
			if (journalFileDto?.journals != null)
			{
				_journals.AddRange(journalFileDto.journals);
			}
			return new List<JournalDto>(_journals);
		}

		public void ClearJournals()
		{
			_journals.Clear();
		}

		private void WriteJournal(RestorationJob job, string phase)
		{
			if (_config.EnableRecoverySystem.Value)
			{
				JournalDto journalDto = _journals.Find((JournalDto j) => j.jobId == job.Id);
				if (journalDto == null)
				{
					journalDto = new JournalDto
					{
						jobId = job.Id,
						startedUtcTicks = DateTime.UtcNow.Ticks
					};
					_journals.Add(journalDto);
				}
				journalDto.locationId = job.Record.Id;
				journalDto.mode = (int)job.Plan.Mode;
				journalDto.classes = (int)job.Plan.Classes;
				journalDto.exterior = job.Plan.Exterior;
				journalDto.interior = job.Plan.Interior;
				journalDto.automatic = job.Plan.Automatic;
				journalDto.force = job.Plan.Force;
				journalDto.cycleId = job.Plan.CycleId;
				journalDto.requestedBy = job.Plan.RequestedBy;
				journalDto.attempts = job.Attempts;
				journalDto.phase = phase;
				SaveJournalFile();
			}
		}

		private void ClearJournal(RestorationJob job)
		{
			if (_journals.RemoveAll((JournalDto j) => j.jobId == job.Id) > 0)
			{
				SaveJournalFile();
			}
		}

		public void DropJournal(string jobId)
		{
			if (_journals.RemoveAll((JournalDto j) => j.jobId == jobId) > 0)
			{
				SaveJournalFile();
			}
		}

		private void SaveJournalFile()
		{
			if (_store.JournalPath != null)
			{
				JournalFileDto value = new JournalFileDto
				{
					journals = new List<JournalDto>(_journals)
				};
				WorldStateStore.WriteAtomic(_store.JournalPath, MiniJson.Serialize(value));
			}
		}

		public RestorationJob CreateRecoveryJob(LocationRecord record, JournalDto journal)
		{
			RestorationPlan restorationPlan = RestorationPlan.Create((RestorationMode)journal.mode, (ElementClass)journal.classes, journal.exterior, journal.interior);
			restorationPlan.Automatic = journal.automatic;
			restorationPlan.Force = true;
			restorationPlan.Recovery = true;
			restorationPlan.CycleId = journal.cycleId;
			restorationPlan.RequestedBy = journal.requestedBy;
			RestorationJob restorationJob = new RestorationJob
			{
				Record = record,
				Plan = restorationPlan,
				Attempts = journal.attempts + 1
			};
			journal.jobId = restorationJob.Id;
			journal.attempts = restorationJob.Attempts;
			SaveJournalFile();
			return restorationJob;
		}

		public string QuickCheck(LocationRecord record, RestorationPlan plan)
		{
			if (!_config.EnableMod.Value)
			{
				return "Mod desativado.";
			}
			if (!GameApi.CanSpawnLocations)
			{
				return "SpawnLocation indisponível nesta versão do jogo.";
			}
			if (!_config.IsModeEnabled(plan.Mode))
			{
				return "Modo " + RestorationPlan.ModeName(plan.Mode) + " desativado na configuração.";
			}
			if (!plan.Automatic && !_config.EnableManualRestoration.Value)
			{
				return "Restauração manual desativada.";
			}
			if (record == null)
			{
				return "Local não encontrado.";
			}
			return null;
		}

		public void Step(RestorationJob job)
		{
			int num = Mathf.Max(1, _config.RestorationBatchSize.Value);
			try
			{
				switch (job.Phase)
				{
				case JobPhase.Validate:
					Validate(job);
					break;
				case JobPhase.Prepare:
					Prepare(job);
					break;
				case JobPhase.Remove:
					Remove(job, num);
					break;
				case JobPhase.Spawn:
					Spawn(job);
					break;
				case JobPhase.PostFilter:
					PostFilter(job, job.LoadedZone ? int.MaxValue : num);
					break;
				case JobPhase.Finalize:
					FinalizeJob(job);
					break;
				}
			}
			catch (Exception ex)
			{
				Log.Exception("Restauração de " + job.Record?.Id, ex);
				Fail(job, "Erro: " + ex.Message, job.Phase >= JobPhase.Remove && job.Attempts < 3);
			}
		}

		private void Validate(RestorationJob job)
		{
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			LocationRecord record = job.Record;
			RestorationPlan plan = job.Plan;
			string text = ((!plan.Recovery) ? QuickCheck(record, plan) : ((record == null) ? "Local não encontrado." : ((!GameApi.CanSpawnLocations) ? "SpawnLocation indisponível." : null)));
			if (text != null)
			{
				Skip(job, text);
				return;
			}
			if (plan.Automatic && !plan.Recovery && !_config.EnableAutomaticRestoration.Value)
			{
				Skip(job, "Restauração automática desativada.");
				return;
			}
			_scanner.Scan(record);
			LocationAnalysis locationAnalysis = _analyzer.Analyze(record.Location);
			switch (record.Availability)
			{
			case LocationAvailability.Excluded:
				Skip(job, "Excluído permanentemente: " + record.Reason);
				return;
			case LocationAvailability.NotGenerated:
				Skip(job, "Zona não gerada.");
				return;
			case LocationAvailability.NoOriginalData:
				Skip(job, "Sem dados originais confiáveis (" + record.Reason + "); nenhuma reconstrução aproximada é feita.");
				return;
			case LocationAvailability.PlayerContent:
				Skip(job, "Contém construções/objetos de jogadores (Protect Player Buildings): local inteiro ignorado.");
				return;
			case LocationAvailability.Protected:
				Skip(job, "Área protegida: " + record.Reason);
				return;
			case LocationAvailability.CategoryDisabled:
				if (!plan.Recovery)
				{
					Skip(job, record.Reason);
					return;
				}
				break;
			default:
				Skip(job, "Estado desconhecido.");
				return;
			case LocationAvailability.Eligible:
				break;
			}
			if (plan.Mode == RestorationMode.Dungeon && !locationAnalysis.HasInterior)
			{
				Skip(job, "O local não é uma masmorra (sem interior).");
				return;
			}
			if (!locationAnalysis.HasInterior)
			{
				plan.Interior = false;
			}
			if (!plan.Exterior && !plan.Interior)
			{
				Skip(job, "Nenhuma região selecionada.");
				return;
			}
			if (plan.Classes == ElementClass.None)
			{
				Skip(job, "Nenhum elemento selecionado.");
				return;
			}
			int currentDay = GameApi.GetCurrentDay();
			if (plan.Automatic && !plan.Recovery && plan.CycleId >= 0 && record.LastRestoredCycle == plan.CycleId)
			{
				Skip(job, "Já restaurado neste ciclo.");
				return;
			}
			if (!plan.Force && !CycleMath.CooldownElapsed(record.LastRestoredDay, currentDay, _config.RestorationIntervalDays.Value))
			{
				Skip(job, $"Restaurado no dia {record.LastRestoredDay}; intervalo mínimo de {_config.RestorationIntervalDays.Value} dia(s) (admin pode usar 'force').");
				return;
			}
			if (plan.Automatic && !plan.Recovery && _config.OnlyRestoreModifiedLocations.Value && record.Condition == LocationCondition.Intact)
			{
				Skip(job, "Intacto (sem alterações).");
				return;
			}
			if (_safety.ServerBusy)
			{
				Defer(job, $"Servidor ocupado ({_safety.AverageFrameMs:0} ms/quadro).");
				return;
			}
			LocationArea area = _scanner.AreaOf(record, locationAnalysis);
			if (area.HasInterior && _safety.AnyPlayerInsideInterior(area.Zone))
			{
				Defer(job, "Jogadores dentro da masmorra.");
				return;
			}
			if (plan.Exterior && _config.WaitWhenPlayersInside.Value && _safety.AnyPlayerOnSurfaceNear(area.Center, Mathf.Max(record.FootprintRadius, area.ExteriorRadius) + 16f))
			{
				Defer(job, "Jogadores no local.");
				return;
			}
			job.Analysis = locationAnalysis;
			job.Area = area;
			job.Phase = JobPhase.Prepare;
		}

		private void Prepare(RestorationJob job)
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			LocationRecord record = job.Record;
			Action release;
			GameObject obj = GameApi.LoadLocationPrefab(record.Location, out release);
			job.ReleasePrefab = release;
			if ((Object)(object)obj == (Object)null)
			{
				Fail(job, "Prefab do local não pôde ser carregado; nada foi alterado.", keepJournal: false);
				return;
			}
			HashSet<ZDOID> queued = new HashSet<ZDOID>();
			List<ZDO> list = new List<ZDO>();
			List<ZDO> list2 = new List<ZDO>();
			_scanner.CollectArea(job.Area, 0f, _buffer);
			foreach (ZDO item in _buffer)
			{
				if (item == null || !item.IsValid())
				{
					continue;
				}
				int prefab = item.GetPrefab();
				if (prefab == GameApi.PrefabLocationProxy)
				{
					if (item.GetInt(GameApi.KeyLocation, 0) == record.LocationHash && job.Area.HorizontalDistance(item.GetPosition()) <= 6f)
					{
						list2.Add(item);
					}
					continue;
				}
				AreaRegion areaRegion = job.Area.RegionOf(item.GetPosition());
				if (areaRegion == AreaRegion.Outside || _safety.IsProtectedObject(item, out var _))
				{
					continue;
				}
				ObjectInfo objectInfo = _analyzer.GetObjectInfo(prefab);
				if (IsLocationObject(prefab, areaRegion, objectInfo, job.Analysis))
				{
					if (!((areaRegion == AreaRegion.Exterior) ? job.Plan.Exterior : job.Plan.Interior) || (job.Plan.Classes & objectInfo.Class) == 0)
					{
						list.Add(item);
					}
					else if (areaRegion == AreaRegion.Interior || objectInfo.IsCharacter)
					{
						job.ToRemove.Enqueue(item);
						queued.Add(item.m_uid);
					}
					else
					{
						job.ExteriorCandidates.Add(item);
					}
				}
			}
			for (int i = 1; i < list2.Count; i++)
			{
				job.ToRemove.Enqueue(list2[i]);
				job.Collapsed++;
			}
			if (job.Plan.Recovery)
			{
				List<ZDO> list3 = new List<ZDO>(list);
				list3.AddRange(job.ExteriorCandidates);
				CollapseDuplicates(job, list3, queued);
				job.ExteriorCandidates.RemoveAll((ZDO z) => queued.Contains(z.m_uid));
			}
			record.Activity = LocationActivity.Restoring;
			WriteJournal(job, "Remove");
			Log.Info($"Restaurando {record.Id} — {job.Plan.Describe()}: {job.ToRemove.Count} objeto(s) a remover antes, " + $"{job.ExteriorCandidates.Count} do exterior a substituir pelos recriados" + ((job.Collapsed > 0) ? $" ({job.Collapsed} duplicata(s) de uma execução interrompida)." : "."));
			job.Phase = JobPhase.Remove;
		}

		private static void CollapseDuplicates(RestorationJob job, List<ZDO> objects, HashSet<ZDOID> queued)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, List<ZDO>> dictionary = new Dictionary<int, List<ZDO>>();
			foreach (ZDO @object in objects)
			{
				int prefab = @object.GetPrefab();
				if (!dictionary.TryGetValue(prefab, out var value))
				{
					value = (dictionary[prefab] = new List<ZDO>());
				}
				value.Add(@object);
			}
			foreach (List<ZDO> value2 in dictionary.Values)
			{
				for (int i = 0; i < value2.Count; i++)
				{
					if (queued.Contains(value2[i].m_uid))
					{
						continue;
					}
					Vector3 position = value2[i].GetPosition();
					for (int j = i + 1; j < value2.Count; j++)
					{
						if (!queued.Contains(value2[j].m_uid) && SamePlace(value2[j].GetPosition(), position, 0.35f))
						{
							job.ToRemove.Enqueue(value2[j]);
							queued.Add(value2[j].m_uid);
							job.Collapsed++;
						}
					}
				}
			}
		}

		private static bool IsLocationObject(int prefabHash, AreaRegion region, ObjectInfo info, LocationAnalysis analysis)
		{
			if (region == AreaRegion.Interior)
			{
				return true;
			}
			if (analysis.OwnedPrefabs.Contains(prefabHash))
			{
				return true;
			}
			if (info.IsCharacter)
			{
				return analysis.CreaturePrefabs.Contains(prefabHash);
			}
			return false;
		}

		private void Remove(RestorationJob job, int budget)
		{
			for (int i = 0; i < budget; i++)
			{
				if (job.ToRemove.Count <= 0)
				{
					break;
				}
				ZDO val = job.ToRemove.Dequeue();
				if (val != null && val.IsValid())
				{
					GameApi.DestroyZdo(val);
					job.Removed++;
				}
			}
			if (job.ToRemove.Count == 0)
			{
				job.Phase = JobPhase.Spawn;
			}
		}

		private void Spawn(RestorationJob job)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			LocationRecord record = job.Record;
			if (job.SpawnWaits == 0)
			{
				WriteJournal(job, "Spawn");
			}
			bool flag = !GameApi.IsZoneLoaded(record.Zone);
			string error;
			GameApi.SpawnResult spawnResult = GameApi.SpawnLocation(record.Location, record.Zone, record.Seed, record.ProxyPosition, record.ProxyRotation, flag, _created, out error);
			if (spawnResult == GameApi.SpawnResult.NotReady)
			{
				if (++job.SpawnWaits >= 600)
				{
					Fail(job, "Terreno da zona não ficou pronto para a recriação.", job.Attempts < 3);
				}
				return;
			}
			bool flag2 = spawnResult == GameApi.SpawnResult.Ok;
			job.LoadedZone = !flag;
			ReleasePrefab(job);
			HashSet<ZDOID> hashSet = new HashSet<ZDOID>();
			foreach (ZDO exteriorCandidate in job.ExteriorCandidates)
			{
				hashSet.Add(exteriorCandidate.m_uid);
			}
			float num = job.Area.QueryRadius;
			foreach (ZDO item in _created)
			{
				if (item != null && item.IsValid())
				{
					hashSet.Add(item.m_uid);
					Vector3 position = item.GetPosition();
					if (!GameApi.IsInterior(position))
					{
						num = Mathf.Max(num, job.Area.HorizontalDistance(position) + 2f);
					}
				}
			}
			job.Kept.Clear();
			GameApi.FindObjects(job.Area.Center, num, _buffer);
			IndexKept(job, _buffer, hashSet);
			if (job.Area.HasInterior)
			{
				GameApi.FindZoneObjects(job.Area.Zone, _buffer);
				List<ZDO> list = new List<ZDO>();
				foreach (ZDO item2 in _buffer)
				{
					if (GameApi.IsInterior(item2.GetPosition()))
					{
						list.Add(item2);
					}
				}
				IndexKept(job, list, hashSet);
			}
			foreach (ZDO item3 in _created)
			{
				if (item3 != null && item3.IsValid())
				{
					job.NewObjects.Enqueue(item3);
					job.Spawned++;
				}
			}
			_created.Clear();
			if (!flag2)
			{
				Log.Error("SpawnLocation falhou em " + record.Id + ": " + error);
				job.Message = "SpawnLocation falhou: " + error;
			}
			WriteJournal(job, "PostFilter");
			job.Phase = JobPhase.PostFilter;
		}

		private static void IndexKept(RestorationJob job, List<ZDO> zdos, HashSet<ZDOID> createdIds)
		{
			//IL_001e: 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)
			foreach (ZDO zdo in zdos)
			{
				if (zdo != null && zdo.IsValid() && !createdIds.Contains(zdo.m_uid))
				{
					int prefab = zdo.GetPrefab();
					if (!job.Kept.TryGetValue(prefab, out var value))
					{
						value = (job.Kept[prefab] = new List<Vector3>());
					}
					value.Add(zdo.GetPosition());
				}
			}
		}

		private void PostFilter(RestorationJob job, int budget)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < budget; i++)
			{
				if (job.NewObjects.Count <= 0)
				{
					break;
				}
				ZDO val = job.NewObjects.Dequeue();
				if (val != null && val.IsValid())
				{
					int prefab = val.GetPrefab();
					Vector3 position = val.GetPosition();
					bool flag = GameApi.IsInterior(position);
					ObjectInfo objectInfo = _analyzer.GetObjectInfo(prefab);
					bool flag2;
					if (prefab == GameApi.PrefabLocationProxy || prefab == GameApi.PrefabZoneCtrl)
					{
						flag2 = true;
					}
					else if (flag ? (!job.Plan.Interior) : (!job.Plan.Exterior))
					{
						flag2 = true;
					}
					else if ((job.Plan.Classes & objectInfo.Class) == 0)
					{
						flag2 = true;
					}
					else if (!flag && TakeTwin(job, prefab, position))
					{
						flag2 = false;
					}
					else if (IsDuplicate(job, prefab, position, objectInfo.IsItemDrop ? 2f : 0.35f))
					{
						flag2 = true;
						job.Duplicates++;
					}
					else
					{
						flag2 = false;
					}
					if (flag2)
					{
						GameApi.DestroyZdo(val);
						job.Discarded++;
					}
				}
			}
			if (job.NewObjects.Count > 0)
			{
				return;
			}
			for (int j = 0; j < budget; j++)
			{
				if (job.Replaced.Count <= 0)
				{
					break;
				}
				ZDO val2 = job.Replaced.Dequeue();
				if (val2 != null && val2.IsValid())
				{
					GameApi.DestroyZdo(val2);
					job.Removed++;
				}
			}
			if (job.Replaced.Count <= 0)
			{
				if (!string.IsNullOrEmpty(job.Message) && job.Message.StartsWith("SpawnLocation falhou"))
				{
					Fail(job, job.Message, job.Attempts < 3);
				}
				else
				{
					job.Phase = JobPhase.Finalize;
				}
			}
		}

		private static bool TakeTwin(RestorationJob job, int prefab, Vector3 pos)
		{
			//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)
			for (int i = 0; i < job.ExteriorCandidates.Count; i++)
			{
				ZDO val = job.ExteriorCandidates[i];
				if (val != null && val.IsValid() && val.GetPrefab() == prefab && SamePlace(val.GetPosition(), pos, 0.35f))
				{
					job.ExteriorCandidates.RemoveAt(i);
					job.Replaced.Enqueue(val);
					return true;
				}
			}
			return false;
		}

		private static bool IsDuplicate(RestorationJob job, int prefab, Vector3 pos, float tolerance)
		{
			//IL_001d: 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)
			if (!job.Kept.TryGetValue(prefab, out var value))
			{
				return false;
			}
			foreach (Vector3 item in value)
			{
				if (SamePlace(item, pos, tolerance))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool SamePlace(Vector3 a, Vector3 b, float horizontalTolerance)
		{
			//IL_0000: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			if (num * num + num2 * num2 <= horizontalTolerance * horizontalTolerance)
			{
				return Mathf.Abs(a.y - b.y) <= 2.5f;
			}
			return false;
		}

		private void FinalizeJob(RestorationJob job)
		{
			LocationRecord record = job.Record;
			int num = (record.LastRestoredDay = GameApi.GetCurrentDay());
			if (job.Plan.Automatic)
			{
				record.LastRestoredCycle = job.Plan.CycleId;
			}
			record.BaselineFingerprint = 0L;
			record.Activity = LocationActivity.Idle;
			_scanner.Scan(record);
			int num2 = job.Spawned - job.Discarded;
			job.Message = $"Restaurado: -{job.Removed} objetos antigos, +{num2} recriados, {job.Duplicates} duplicata(s) evitada(s)" + ((job.Collapsed > 0) ? $", {job.Collapsed} duplicata(s) antiga(s) removida(s)." : ".");
			record.LastResult = "OK dia " + num;
			_history.Record(HistoryResult.Success, record.Id, record.PrefabName, job.Plan.Describe(), job.Message, job.Removed, num2, job.Duplicates, job.Plan.RequestedBy);
			ClearJournal(job);
			_store.MarkDirty();
			Log.Info(record.Id + ": " + job.Message);
			job.Phase = JobPhase.Done;
		}

		private void Skip(RestorationJob job, string reason)
		{
			job.Message = reason;
			job.Phase = JobPhase.Skipped;
			if (job.Record != null && job.Record.Activity != LocationActivity.Restoring)
			{
				job.Record.Activity = LocationActivity.Idle;
			}
			if (!job.Plan.Automatic || job.Plan.Recovery)
			{
				_history.Record(HistoryResult.Skipped, job.Record?.Id, job.Record?.PrefabName, job.Plan.Describe(), reason, 0, 0, 0, job.Plan.RequestedBy);
			}
			if (job.Plan.Recovery)
			{
				ClearJournal(job);
			}
			Log.Debug("Ignorado " + job.Record?.Id + ": " + reason);
		}

		private void Defer(RestorationJob job, string reason)
		{
			job.Message = reason;
			job.Phase = JobPhase.Deferred;
			if (job.Record != null)
			{
				job.Record.Activity = LocationActivity.Deferred;
			}
			Log.Debug("Adiado " + job.Record?.Id + ": " + reason);
		}

		private void Fail(RestorationJob job, string reason, bool keepJournal)
		{
			ReleasePrefab(job);
			job.Message = reason;
			job.Phase = JobPhase.Failed;
			if (job.Record != null)
			{
				job.Record.Activity = LocationActivity.Idle;
				job.Record.LastResult = "FALHA: " + reason;
			}
			_history.Record(HistoryResult.Failed, job.Record?.Id, job.Record?.PrefabName, job.Plan.Describe(), reason + (keepJournal ? " (será retomado pelo sistema de recuperação ao reiniciar)" : ""), job.Removed, job.Spawned - job.Discarded, job.Duplicates, job.Plan.RequestedBy);
			if (keepJournal)
			{
				WriteJournal(job, "Failed");
			}
			else
			{
				ClearJournal(job);
			}
			Log.Error("Falha em " + job.Record?.Id + ": " + reason);
		}

		private static void ReleasePrefab(RestorationJob job)
		{
			Action releasePrefab = job.ReleasePrefab;
			job.ReleasePrefab = null;
			releasePrefab?.Invoke();
		}

		public void Abort(RestorationJob job)
		{
			ReleasePrefab(job);
			if (job.Record != null)
			{
				job.Record.Activity = LocationActivity.Idle;
			}
		}
	}
	public enum RestorationMode
	{
		Complete,
		Structural,
		Dungeon,
		Custom
	}
	internal sealed class RestorationPlan
	{
		public RestorationMode Mode;

		public ElementClass Classes = ElementClass.All;

		public bool Exterior = true;

		public bool Interior = true;

		public bool Automatic;

		public bool Force;

		public bool Recovery;

		public int CycleId = -1;

		public string RequestedBy = "-";

		public long RequesterPeer;

		public static RestorationPlan Create(RestorationMode mode, ElementClass customClasses = ElementClass.All, bool customExterior = true, bool customInterior = true)
		{
			RestorationPlan restorationPlan = new RestorationPlan
			{
				Mode = mode
			};
			switch (mode)
			{
			case RestorationMode.Complete:
				restorationPlan.Classes = ElementClass.All;
				break;
			case RestorationMode.Structural:
				restorationPlan.Classes = ElementClass.Structures | ElementClass.Doors;
				break;
			case RestorationMode.Dungeon:
				restorationPlan.Classes = ElementClass.All;
				restorationPlan.Exterior = false;
				restorationPlan.Interior = true;
				break;
			case RestorationMode.Custom:
				restorationPlan.Classes = customClasses;
				restorationPlan.Exterior = customExterior;
				restorationPlan.Interior = customInterior;
				break;
			}
			return restorationPlan;
		}

		public static string ModeName(RestorationMode mode)
		{
			return mode switch
			{
				RestorationMode.Complete => "A-Completa", 
				RestorationMode.Structural => "B-Estrutural", 
				RestorationMode.Dungeon => "C-Masmorra", 
				RestorationMode.Custom => "D-Personalizada", 
				_ => mode.ToString(), 
			};
		}

		public string Describe()
		{
			string text = (Exterior ? "exterior" : "") + ((Exterior && Interior) ? "+" : "") + (Interior ? "interior" : "");
			return ModeName(Mode) + " [" + Classes.ToString() + "] " + text + (Automatic ? " (automática)" : "") + (Recovery ? " (recuperação)" : "");
		}
	}
	internal sealed class CycleSummary
	{
		public int CycleId;

		public int Total;

		public int Restored;

		public int Skipped;

		public int Deferred;

		public int Failed;

		public override string ToString()
		{
			return $"ciclo {CycleId}: {Restored} restaurado(s), {Skipped} ignorado(s), {Deferred} adiado(s), {Failed} falha(s) de {Total}";
		}
	}
	internal sealed class RestorationScheduler
	{
		private sealed class Pending
		{
			public LocationRecord Record;

			public RestorationPlan Plan;

			public float NotBefore;

			public RestorationJob PreparedJob;
		}

		private const float DeferRetrySeconds = 60f;

		private const int MaxValidationsPerTick = 25;

		private readonly ConfigurationManager _config;

		private readonly LocationDatabase _database;

		private readonly RestorationEngine _engine;

		private readonly DungeonResetManager _dungeons;

		private readonly HistoryManager _history;

		private readonly List<Pending> _queue = new List<Pending>();

		private readonly List<RestorationJob> _active = new List<RestorationJob>();

		private readonly HashSet<string> _busyIds = new HashSet<string>();

		private readonly HashSet<string> _manualDeferNotified = new HashSet<string>();

		private CycleSummary _summary;

		private int _outstanding;

		private Action<CycleSummary> _onCycleFinished;

		private readonly HashSet<string> _evaluated = new HashSet<string>();

		private readonly HashSet<string> _deferredInSummary = new HashSet<string>();

		private float _timer;

		public int QueueCount => _queue.Count;

		public int ActiveCount => _active.Count;

		public bool CycleRunning => _summary != null;

		public IReadOnlyList<RestorationJob> ActiveJobs => _active;

		public event Action<RestorationJob> JobFinished;

		public event Action<RestorationJob> JobDeferred;

		public RestorationScheduler(ConfigurationManager config, LocationDatabase database, RestorationEngine engine, DungeonResetManager dungeons, HistoryManager history)
		{
			_config = config;
			_database = database;
			_engine = engine;
			_dungeons = dungeons;
			_history = history;
		}

		public void Reset()
		{
			foreach (RestorationJob item in _active)
			{
				_engine.Abort(item);
			}
			_active.Clear();
			_queue.Clear();
			_busyIds.Clear();
			_manualDeferNotified.Clear();
			_evaluated.Clear();
			_deferredInSummary.Clear();
			_summary = null;
			_outstanding = 0;
			_onCycleFinished = null;
		}

		public bool IsBusy(string locationId)
		{
			return _busyIds.Contains(locationId);
		}

		public bool Enqueue(LocationRecord record, RestorationPlan plan, out string error)
		{
			error = null;
			if (record == null)
			{
				error = "Local não encontrado.";
				return false;
			}
			if (_busyIds.Contains(record.Id))
			{
				error = "Já existe uma operação pendente para este local.";
				return false;
			}
			_busyIds.Add(record.Id);
			_queue.Add(new Pending
			{
				Record = record,
				Plan = plan
			});
			record.Activity = LocationActivity.Queued;
			return true;
		}

		public void EnqueueRecovery(LocationRecord record, RestorationJob job)
		{
			if (record != null && !_busyIds.Contains(record.Id))
			{
				_busyIds.Add(record.Id);
				_queue.Insert(0, new Pending
				{
					Record = record,
					Plan = job.Plan,
					PreparedJob = job
				});
				record.Activity = LocationActivity.Queued;
			}
		}

		public int BeginAutomaticCycle(int cycleId, Action<CycleSummary> onFinished)
		{
			_queue.RemoveAll(delegate(Pending p)
			{
				int num;
				if (p.Plan.Automatic && !p.Plan.Recovery)
				{
					num = ((p.Plan.CycleId != cycleId) ? 1 : 0);
					if (num != 0)
					{
						_busyIds.Remove(p.Record.Id);
						p.Record.Activity = LocationActivity.Idle;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)num != 0;
			});
			_summary = new CycleSummary
			{
				CycleId = cycleId
			};
			_onCycleFinished = onFinished;
			_evaluated.Clear();
			_deferredInSummary.Clear();
			_outstanding = 0;
			RestorationMode automaticMode = _config.AutomaticMode;
			foreach (LocationRecord item in _database.All)
			{
				if (item.Placed && item.Availability != LocationAvailability.Excluded && item.LastRestoredCycle != cycleId && (!item.Scanned || _config.IsCategoryEnabled(item.Category)))
				{
					RestorationPlan restorationPlan = _dungeons.AutomaticPlanFor(item, automaticMode);
					restorationPlan.Automatic = true;
					restorationPlan.CycleId = cycleId;
					restorationPlan.RequestedBy = "ciclo automático";
					if (Enqueue(item, restorationPlan, out var _))
					{
						_outstanding++;
					}
				}
			}
			int outstanding = _outstanding;
			_summary.Total = outstanding;
			Log.Info($"Ciclo {cycleId}: {outstanding} local(is) candidato(s) na fila.");
			if (_outstanding == 0)
			{
				CompleteCycle();
			}
			return outstanding;
		}

		public void Tick(float deltaTime)
		{
			_timer += deltaTime;
			if (_timer < _config.ProcessingInterval.Value)
			{
				return;
			}
			_timer = 0f;
			StartJobs();
			for (int num = _active.Count - 1; num >= 0; num--)
			{
				RestorationJob restorationJob = _active[num];
				_engine.Step(restorationJob);
				if (restorationJob.Finished)
				{
					_active.RemoveAt(num);
					HandleFinished(restorationJob);
				}
			}
		}

		private void StartJobs()
		{
			int num = Mathf.Max(1, _config.MaximumSimultaneousOperations.Value);
			int num2 = 0;
			float time = Time.time;
			int num3 = 0;
			while (num3 < _queue.Count && _active.Count < num && num2 < 25)
			{
				Pending pending = _queue[num3];
				if (pending.NotBefore > time)
				{
					num3++;
					continue;
				}
				_queue.RemoveAt(num3);
				RestorationJob restorationJob = pending.PreparedJob ?? new RestorationJob
				{
					Record = pending.Record,
					Plan = pending.Plan
				};
				restorationJob.Phase = JobPhase.Validate;
				_engine.Step(restorationJob);
				num2++;
				if (restorationJob.Finished)
				{
					HandleFinished(restorationJob);
				}
				else
				{
					_active.Add(restorationJob);
				}
			}
		}

		private void HandleFinished(RestorationJob job)
		{
			string id = job.Record.Id;
			bool flag = _summary != null && job.Plan.Automatic && job.Plan.CycleId == _summary.CycleId;
			bool flag2 = flag && _evaluated.Add(id);
			if (job.Phase == JobPhase.Deferred)
			{
				if (flag2)
				{
					_summary.Deferred++;
					_deferredInSummary.Add(id);
				}
				try
				{
					this.JobDeferred?.Invoke(job);
				}
				catch (Exception ex)
				{
					Log.Exception("JobDeferred", ex);
				}
				if (!job.Plan.Automatic && _manualDeferNotified.Add(id))
				{
					Notify(job);
				}
				_queue.Add(new Pending
				{
					Record = job.Record,
					Plan = job.Plan,
					NotBefore = Time.time + 60f
				});
				if (flag2)
				{
					DecrementOutstanding();
				}
				return;
			}
			_busyIds.Remove(id);
			_manualDeferNotified.Remove(id);
			if (flag)
			{
				if (_deferredInSummary.Remove(id))
				{
					_summary.Deferred--;
				}
				switch (job.Phase)
				{
				case JobPhase.Done:
					_summary.Restored++;
					break;
				case JobPhase.Skipped:
					_summary.Skipped++;
					break;
				case JobPhase.Failed:
					_summary.Failed++;
					break;
				}
				if (flag2)
				{
					DecrementOutstanding();
				}
			}
			Notify(job);
		}

		private void DecrementOutstanding()
		{
			_outstanding--;
			if (_outstanding <= 0)
			{
				CompleteCycle();
			}
		}

		private void CompleteCycle()
		{
			CycleSummary summary = _summary;
			Action<CycleSummary> onCycleFinished = _onCycleFinished;
			_summary = null;
			_onCycleFinished = null;
			_outstanding = 0;
			_evaluated.Clear();
			_deferredInSummary.Clear();
			if (summary == null)
			{
				return;
			}
			_history.Record(HistoryResult.Info, "-", "Ciclo " + summary.CycleId, "Automático", summary.ToString());
			Log.Info("Ciclo concluído: " + summary);
			try
			{
				onCycleFinished?.Invoke(summary);
			}
			catch (Exception ex)
			{
				Log.Exception("Cycle callback", ex);
			}
		}

		private void Notify(RestorationJob job)
		{
			try
			{
				this.JobFinished?.Invoke(job);
			}
			catch (Exception ex)
			{
				Log.Exception("JobFinished", ex);
			}
		}
	}
}
namespace ValheimLocationRestorer.Protection
{
	internal sealed class BannerEntry
	{
		public string Prefab;

		public Vector3 Position;

		public long Creator;

		public int FirstSeenDay;

		public int MissingScans;

		public bool SeenThisScan;

		public string Key => MakeKey(Prefab, Position);

		public static string MakeKey(string prefab, Vector3 p)
		{
			//IL_0014: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			return prefab + "@" + Mathf.RoundToInt(p.x) + "," + Mathf.RoundToInt(p.y) + "," + Mathf.RoundToInt(p.z);
		}
	}
	internal sealed class BannerProtectionManager
	{
		private const int ScansBeforeRemoval = 2;

		private const float RescanSeconds = 120f;

		private readonly ConfigurationManager _config;

		private readonly Dictionary<string, BannerEntry> _registry = new Dictionary<string, BannerEntry>();

		private readonly HashSet<int> _bannerHashes = new HashSet<int>();

		private readonly List<string> _bannerNames = new List<string>();

		private readonly List<ZDO> _query = new List<ZDO>();

		private bool _typesResolved;

		private float _resolveRetry;

		private bool _scanning;

		private int _scanPrefab;

		private int _scanIndex;

		private readonly List<ZDO> _scanFound = new List<ZDO>();

		private float _rescanTimer = 5f;

		public bool Changed;

		public bool InitialScanComplete { get; private set; }

		public bool TypesResolved => _typesResolved;

		public IReadOnlyList<string> BannerPrefabNames => _bannerNames;

		public IEnumerable<BannerEntry> Banners => _registry.Values;

		public int Count => _registry.Count;

		public BannerProtectionManager(ConfigurationManager config)
		{
			_config = config;
		}

		public void Reset()
		{
			_registry.Clear();
			_bannerHashes.Clear();
			_bannerNames.Clear();
			_typesResolved = false;
			_scanning = false;
			InitialScanComplete = false;
			_rescanTimer = 5f;
		}

		public void Load(List<BannerDto> saved)
		{
			//IL_0051: 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)
			_registry.Clear();
			if (saved == null)
			{
				return;
			}
			foreach (BannerDto item in saved)
			{
				if (!string.IsNullOrEmpty(item.prefab))
				{
					BannerEntry bannerEntry = new BannerEntry
					{
						Prefab = item.prefab,
						Position = new Vector3(item.x, item.y, item.z),
						Creator = item.creator,
						FirstSeenDay = item.firstSeenDay,
						MissingScans = item.missingScans
					};
					_registry[bannerEntry.Key] = bannerEntry;
				}
			}
			Log.Info(_registry.Count + " bandeira(s) protegida(s) restaurada(s) do registro.");
		}

		public void Export(List<BannerDto> target)
		{
			target.Clear();
			foreach (BannerEntry value in _registry.Values)
			{
				target.Add(new BannerDto
				{
					prefab = value.Prefab,
					x = value.Position.x,
					y = value.Position.y,
					z = value.Position.z,
					creator = value.Creator,
					firstSeenDay = value.FirstSeenDay,
					missingScans = value.MissingScans
				});
			}
		}

		private bool ResolveTypes()
		{
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return false;
			}
			_bannerHashes.Clear();
			_bannerNames.Clear();
			List<GameObject> hammerPieces = GameApi.GetHammerPieces();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (GameObject item in hammerPieces)
			{
				if ((Object)(object)item != (Object)null)
				{
					hashSet.Add(GameApi.CleanPrefabName(((Object)item).name));
				}
			}
			bool flag = hashSet.Count > 0;
			if (!flag)
			{
				Log.Warn("Lista de peças do Martelo indisponível; bandeiras validadas só por prefab + componente Piece.");
			}
			string[] array = (_config.SupportedBannerPrefabs.Value ?? string.Empty).Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(text);
					if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<Piece>() == (Object)null)
					{
						Log.Warn("Bandeira '" + text + "' ignorada: não existe no jogo ou não é uma peça.");
					}
					else if (flag && !hashSet.Contains(text))
					{
						Log.Warn("Bandeira '" + text + "' ignorada: não é construível com o Martelo.");
					}
					else
					{
						AddBannerType(text);
					}
				}
			}
			if (_config.DetectAllSupportedBanners.Value)
			{
				foreach (GameObject item2 in hammerPieces)
				{
					if (!((Object)(object)item2 == (Object)null))
					{
						Piece component = item2.GetComponent<Piece>();
						if (!((Object)(object)component == (Object)null) && !string.IsNullOrEmpty(component.m_name) && component.m_name.StartsWith("$piece_banner", StringComparison.OrdinalIgnoreCase))
						{
							AddBannerType(GameApi.CleanPrefabName(((Object)item2).name));
						}
					}
				}
			}
			if (_bannerNames.Count == 0)
			{
				Log.Error("Nenhum tipo de bandeira válido foi encontrado. Até corrigir 'Supported Banner Prefabs', TODOS os locais serão tratados como protegidos (nada será restaurado).");
				return false;
			}
			Log.Info("Bandeiras reconhecidas (" + _bannerNames.Count + "): " + string.Join(", ", _bannerNames.ToArray()));
			return true;
		}

		private void AddBannerType(string name)
		{
			int stableHashCode = StringExtensionMethods.GetStableHashCode(name);
			if (_bannerHashes.Add(stableHashCode))
			{
				_bannerNames.Add(name);
			}
		}

		public bool IsBannerPrefab(int prefabHash)
		{
			return _bannerHashes.Contains(prefabHash);
		}

		public void Tick(float deltaTime, int currentDay)
		{
			if (!_config.EnableBannerProtection.Value)
			{
				return;
			}
			if (!_typesResolved)
			{
				_resolveRetry -= deltaTime;
				if (_resolveRetry > 0f)
				{
					return;
				}
				_resolveRetry = 60f;
				_typesResolved = ResolveTypes();
				if (!_typesResolved)
				{
					return;
				}
			}
			if (!_scanning)
			{
				_rescanTimer -= deltaTime;
				if (_rescanTimer > 0f)
				{
					return;
				}
				StartScan();
			}
			StepScan(currentDay);
		}

		public void RequestRescan()
		{
			_rescanTimer = 0f;
		}

		private void StartScan()
		{
			_scanning = true;
			_scanPrefab = 0;
			_scanIndex = 0;
			_scanFound.Clear();
			foreach (BannerEntry value in _registry.Values)
			{
				value.SeenThisScan = false;
			}
		}

		private void StepScan(int currentDay)
		{
			if (ZDOMan.instance != null)
			{
				if (_scanPrefab >= _bannerNames.Count)
				{
					Reconcile(currentDay);
				}
				else if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(_bannerNames[_scanPrefab], _scanFound, ref _scanIndex))
				{
					_scanPrefab++;
					_scanIndex = 0;
				}
			}
		}

		private void Reconcile(int currentDay)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			_scanning = false;
			_rescanTimer = 120f;
			int num = 0;
			int num2 = 0;
			foreach (ZDO item in _scanFound)
			{
				if (item == null || !item.IsValid())
				{
					continue;
				}
				long num3 = item.GetLong(GameApi.KeyCreator, 0L);
				if (num3 != 0L)
				{
					GameObject prefab = GameApi.GetPrefab(item.GetPrefab());
					string prefab2 = (((Object)(object)prefab != (Object)null) ? ((Object)prefab).name : item.GetPrefab().ToString());
					string key = BannerEntry.MakeKey(prefab2, item.GetPosition());
					if (!_registry.TryGetValue(key, out var value))
					{
						value = new BannerEntry
						{
							Prefab = prefab2,
							Position = item.GetPosition(),
							Creator = num3,
							FirstSeenDay = currentDay
						};
						_registry[key] = value;
						num++;
					}
					value.SeenThisScan = true;
					value.MissingScans = 0;
				}
			}
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, BannerEntry> item2 in _registry)
			{
				if (!item2.Value.SeenThisScan)
				{
					item2.Value.MissingScans++;
					if (item2.Value.MissingScans >= 2)
					{
						list.Add(item2.Key);
					}
				}
			}
			foreach (string item3 in list)
			{
				_registry.Remove(item3);
				num2++;
			}
			_scanFound.Clear();
			if (!InitialScanComplete || num > 0 || num2 > 0)
			{
				Log.Info($"Varredura de bandeiras: {_registry.Count} ativa(s), +{num}, -{num2} (remoção só após {2} varreduras sem a bandeira).");
			}
			InitialScanComplete = true;
			Changed = Changed || num > 0 || num2 > 0;
		}

		public bool IsProtected(Vector3 center, float footprintRadius, out string reason)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: 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)
			reason = null;
			if (!_config.EnableBannerProtection.Value)
			{
				return false;
			}
			if (!_typesResolved)
			{
				reason = "Tipos de bandeira ainda não identificados (proteção preventiva)";
				return true;
			}
			float value = _config.ProtectionRadius.Value;
			GameApi.FindObjects(center, value + footprintRadius + 1f, _query);
			foreach (ZDO item in _query)
			{
				if (_bannerHashes.Contains(item.GetPrefab()) && GameApi.IsPlayerCreated(item))
				{
					Vector3 position = item.GetPosition();
					if (ProtectionGeometry.IsLocationProtected(center.x, center.z, footprintRadius, position.x, position.z, value, partialOverlapProtects: true))
					{
						reason = $"Bandeira a {ProtectionGeometry.HorizontalDistance(center.x, center.z, position.x, position.z):0} m";
						return true;
					}
				}
			}
			foreach (BannerEntry value2 in _registry.Values)
			{
				if (ProtectionGeometry.IsLocationProtected(center.x, center.z, footprintRadius, value2.Position.x, value2.Position.z, value, partialOverlapProtects: true))
				{
					reason = $"Bandeira registrada a {ProtectionGeometry.HorizontalDistance(center.x, center.z, value2.Position.x, value2.Position.z):0} m";
					return true;
				}
			}
			return false;
		}
	}
}
namespace ValheimLocationRestorer.Persistence
{
	[Serializable]
	public class WorldStateDto
	{
		public int version = 1;

		public string worldName;

		public long worldUid;

		public long savedUtcTicks;

		public CycleStateDto cycle = new CycleStateDto();

		public List<LocationStateDto> locations = new List<LocationStateDto>();

		public List<BannerDto> banners = new List<BannerDto>();
	}
	[Serializable]
	public class CycleStateDto
	{
		public bool initialized;

		public int cycleId = 1;

		public int cycleStartDay = -1;

		public int lastSeenDay = -1;

		public int warningSentCycle = -1;

		public int executingCycle = -1;

		public int executionDay = -1;

		public int lastCompletedCycle = -1;

		public int pendingDueSinceDay = -1;
	}
	[Serializable]
	public class LocationStateDto
	{
		public string id;

		public long baselineFingerprint;

		public int baselineCount;

		public int lastRestoredDay = -1;

		public int lastRestoredCycle = -1;

		public string lastResult;
	}
	[Serializable]
	public class BannerDto
	{
		public string prefab;

		public float x;

		public float y;

		public float z;

		public long creator;

		public int firstSeenDay;

		public int missingScans;
	}
	[Serializable]
	public class JournalDto
	{
		public string jobId;

		public string locationId;

		public int mode;

		public int classes;

		public bool exterior;

		public bool interior;

		public bool automatic;

		public bool force;

		public int cycleId;

		public string requestedBy;

		public string phase;

		public int attempts;

		public long startedUtcTicks;
	}
	[Serializable]
	public class JournalFileDto
	{
		public List<JournalDto> journals = new List<JournalDto>();
	}
	[Serializable]
	public class HistoryFileDto
	{
		public List<HistoryEntryDto> entries = new List<HistoryEntryDto>();
	}
	[Serializable]
	public class HistoryEntryDto
	{
		public long utcTicks;

		public int day;

		public string locationId;

		public string locationName;

		public string mode;

		public string result;

		public string detail;

		public int removed;

		public int spawned;

		public int duplicates;

		public string requestedBy;
	}
	internal sealed class WorldStateStore
	{
		private const float AutoSaveSeconds = 30f;

		private bool _dirty;

		private float _timer;

		public string Folder { get; private set; }

		public WorldStateDto State { get; private set; }

		public string StatePath
		{
			get
			{
				if (Folder != null)
				{
					return Path.Combine(Folder, "state.json");
				}
				return null;
			}
		}

		public string HistoryPath
		{
			get
			{
				if (Folder != null)
				{
					return Path.Combine(Folder, "history.json");
				}
				return null;
			}
		}

		public string JournalPath
		{
			get
			{
				if (Folder != null)
				{
					return Path.Combine(Folder, "journal.json");
				}
				return null;
			}
		}

		public bool IsOpen => State != null;

		public event Action BeforeSave;

		public void Open(string worldName, long worldUid)
		{
			Folder = Path.Combine(Paths.ConfigPath, "Braian.ValheimLocationRestorer", "worlds", Sanitize(worldName) + "_" + worldUid);
			Directory.CreateDirectory(Folder);
			State = ReadJson<WorldStateDto>(StatePath) ?? new WorldStateDto();
			State.worldName = worldName;
			State.worldUid = worldUid;
			if (State.cycle == null)
			{
				State.cycle = new CycleStateDto();
			}
			if (State.locations == null)
			{
				State.locations = new List<LocationStateDto>();
			}
			if (State.banners == null)
			{
				State.banners = new List<BannerDto>();
			}
			Log.Info("Estado do mundo carregado de " + Folder);
		}

		public void Close()
		{
			if (State != null)
			{
				SaveNow();
				State = null;
				Folder = null;
			}
		}

		public void MarkDirty()
		{
			_dirty = true;
		}

		public void Tick(float deltaTime)
		{
			if (State != null && _dirty)
			{
				_timer += deltaTime;
				if (_timer >= 30f)
				{
					SaveNow();
				}
			}
		}

		public bool SaveNow()
		{
			if (State == null)
			{
				return false;
			}
			try
			{
				this.BeforeSave?.Invoke();
			}
			catch (Exception ex)
			{
				Log.Exception("BeforeSave", ex);
			}
			State.savedUtcTicks = DateTime.UtcNow.Ticks;
			bool num = WriteAtomic(StatePath, MiniJson.Serialize(State));
			if (num)
			{
				_dirty = false;
				_timer = 0f;
			}
			return num;
		}

		public static T ReadJson<T>(string path) where T : class, new()
		{
			string[] array = new string[2]
			{
				path,
				path + ".bak"
			};
			foreach (string text in array)
			{
				try
				{
					if (text == null || !File.Exists(text))
					{
						continue;
					}
					string text2 = File.ReadAllText(text, Encoding.UTF8);
					if (string.IsNullOrWhiteSpace(text2))
					{
						continue;
					}
					T val = MiniJson.Deserialize<T>(text2);
					if (val == null)
					{
						continue;
					}
					if (text.EndsWith(".bak"))
					{
						Log.Warn("Arquivo principal ilegível; usando backup " + text);
					}
					return val;
				}
				catch (Exception ex)
				{
					Log.Warn("Falha ao ler " + text + ": " + ex.Message);
				}
			}
			return null;
		}

		public static bool WriteAtomic(string path, string content)
		{
			if (string.IsNullOrEmpty(path))
			{
				return false;
			}
			string text = path + ".tmp";
			string text2 = path + ".bak";
			try
			{
				File.WriteAllText(text, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				if (File.Exists(path))
				{
					if (File.Exists(text2))
					{
						File.Delete(text2);
					}
					File.Move(path, text2);
				}
				File.Move(text, path);
				return true;
			}
			catch (Exception ex)
			{
				Log.Error("Falha ao gravar " + path + ": " + ex.Message);
				return false;
			}
		}

		private static string Sanitize(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return "world";
			}
			StringBuilder stringBuilder = new StringBuilder(name.Length);
			foreach (char c in name)
			{
				stringBuilder.Append((char.IsLetterOrDigit(c) || c == '-' || c == '_') ? c : '_');
			}
			return stringBuilder.ToString();
		}
	}
}
namespace ValheimLocationRestorer.Patches
{
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	internal static class ZNetOnNewConnectionPatch
	{
		private static void Postfix(ZNetPeer peer)
		{
			ModContext.Current?.Network.OnNewConnection(peer);
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	internal static class ZNetDisconnectPatch
	{
		private static void Prefix(ZNetPeer peer)
		{
			ModContext.Current?.Network.OnDisconnect(peer);
		}
	}
	[HarmonyPatch(typeof(ZDOMan), "CreateNewZDO", new Type[]
	{
		typeof(Vector3),
		typeof(int)
	})]
	internal static class ZdoCreatePatch
	{
		private static void Postfix(ZDO __result)
		{
			if (ZdoCapture.Active)
			{
				ZdoCapture.OnCreated(__result);
			}
		}
	}
	[HarmonyPatch(typeof(EnvMan), "SkipToMorning")]
	internal static class SkipToMorningPatch
	{
		private static void Postfix()
		{
			ModContext.Current?.Cycle.OnSleepSkip();
		}
	}
	internal static class OptionalPatches
	{
		public static void Apply(Harmony harmony, ModContext context)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (GameApi.PatchAllNamed(harmony, typeof(ZNet), "Save", null, new HarmonyMethod(typeof(OptionalPatches), "WorldSavePostfix", (Type[])null)) == 0)
			{
				Log.Warn("ZNet.Save não encontrado: o estado do mod será salvo a cada 30 s e ao sair.");
			}
		}

		private static void WorldSavePostfix()
		{
			ModContext.Current?.OnWorldSaved();
		}
	}
}
namespace ValheimLocationRestorer.Network
{
	internal sealed class NetworkManager
	{
		private sealed class Requester
		{
			public ZNetPeer Peer;

			public long PeerId;

			public string Name;

			public bool Admin;
		}

		public const string RpcHello = "VLR_Hello";

		public const string RpcRequest = "VLR_Request";

		public const string RpcResponse = "VLR_Response";

		public const string RpcNotify = "VLR_Notify";

		public const int PageSize = 12;

		private readonly ConfigurationManager _config;

		private readonly HashSet<long> _moddedPeers = new HashSet<long>();

		private bool _helloSent;

		public LocationPage LastLocationPage { get; private set; }

		public event Action<LocationPage> LocationPageReceived;

		public event Action<HistoryPage> HistoryPageReceived;

		public event Action<string> TextReceived;

		public NetworkManager(ConfigurationManager config)
		{
			_config = config;
		}

		public void OnNewConnection(ZNetPeer peer)
		{
			if (peer?.m_rpc == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			if (ZNet.instance.IsServer())
			{
				peer.m_rpc.Register<ZPackage>("VLR_Hello", (Action<ZRpc, ZPackage>)delegate
				{
					OnHello(peer);
				});
				peer.m_rpc.Register<ZPackage>("VLR_Request", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					OnRequest(ResolveRemote(peer), pkg);
				});
				return;
			}
			peer.m_rpc.Register<ZPackage>("VLR_Response", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
			{
				OnResponse(pkg);
			});
			peer.m_rpc.Register<string>("VLR_Notify", (Action<ZRpc, string>)delegate(ZRpc rpc, string text)
			{
				ShowNotification(text);
			});
			_helloSent = false;
		}

		public void OnDisconnect(ZNetPeer peer)
		{
			if (peer != null)
			{
				_moddedPeers.Remove(peer.m_uid);
			}
		}

		public void Tick()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				_helloSent = false;
				_moddedPeers.Clear();
			}
			else if (!_helloSent && !ZNet.instance.IsServer())
			{
				ZRpc serverRPC = ZNet.instance.GetServerRPC();
				if (serverRPC != null)
				{
					serverRPC.Invoke("VLR_Hello", new object[1] { (object)new ZPackage() });
					_helloSent = true;
				}
			}
		}

		private static Requester ResolveRemote(ZNetPeer peer)
		{
			return new Requester
			{
				Peer = peer,
				PeerId = peer.m_uid,
				Name = (string.IsNullOrEmpty(peer.m_playerName) ? peer.m_uid.ToString() : peer.m_playerName),
				Admin = GameApi.IsPeerAdmin(peer)
			};
		}

		private static Requester LocalHost()
		{
			return new Requester
			{
				Peer = null,
				PeerId = GameApi.GetLocalPeerId(),
				Name = GameApi.LocalPlayerName(),
				Admin = true
			};
		}

		private void SendRequest(ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				GameApi.PrintConsole(Texts.Get("not.connected"));
				return;
			}
			i