Decompiled source of NajLobby v1.1.1

NajLobby.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using MenuLib;
using MenuLib.MonoBehaviors;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("NajLobby")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+9fa49c3fc7b0a2a6373f25089cb0fa1d0964bc3f")]
[assembly: AssemblyProduct("NajLobby")]
[assembly: AssemblyTitle("NajLobby")]
[assembly: AssemblyVersion("1.1.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 NajLobby
{
	internal static class LobbyMenus
	{
		[HarmonyPatch(typeof(MenuPageRegions), "PickRegion")]
		private static class HostBeforeChoosingSave
		{
			private static readonly FieldInfo PageType = AccessTools.Field(typeof(MenuPageRegions), "type");

			private static readonly object HostType = Enum.Parse(PageType.FieldType, "HostGame");

			private static bool Prefix(MenuPageRegions __instance, string _region)
			{
				if (!HostType.Equals(PageType.GetValue(__instance)))
				{
					return true;
				}
				LobbyRecreation.Region.Invoke(DataDirector.instance) = _region;
				SemiFunc.MainMenuSetMultiplayer();
				MenuManager.instance.PageCloseAll();
				SemiFunc.MenuActionHostGame((string)null, (List<string>)null);
				return false;
			}
		}

		[HarmonyPatch(typeof(MenuPageSaves), "UpdateGameModeHeader")]
		private static class PickerHeader
		{
			private static void Postfix(MenuPageSaves __instance)
			{
				if ((Object)(object)_picker == (Object)(object)__instance)
				{
					TextMeshProUGUI gameModeHeader = __instance.gameModeHeader;
					LocalizedAsset localizedMultiplayerMode = __instance.localizedMultiplayerMode;
					((TMP_Text)gameModeHeader).text = ((localizedMultiplayerMode != null) ? localizedMultiplayerMode.GetLocalizedString((Locale)null) : null) ?? "Multiplayer Mode";
				}
			}
		}

		[HarmonyPatch(typeof(MenuPageSaves), "OnGoBack")]
		private static class PickerBack
		{
			private static bool Prefix(MenuPageSaves __instance)
			{
				if ((Object)(object)_picker != (Object)(object)__instance)
				{
					return true;
				}
				CloseSavePicker(__instance);
				return false;
			}
		}

		[HarmonyPatch(typeof(MenuPageSaves), "OnNewGame")]
		private static class PickerNewGame
		{
			private static bool Prefix(MenuPageSaves __instance)
			{
				if ((Object)(object)_picker != (Object)(object)__instance)
				{
					return true;
				}
				if (CanChooseSave)
				{
					SavedRuns.StartNew();
					CloseSavePicker(__instance);
					Plugin.Log("Selected a new run in the current lobby.");
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(MenuPageSaves), "OnLoadGame")]
		private static class PickerLoadGame
		{
			private static bool Prefix(MenuPageSaves __instance, bool ___currentSaveFileValid, string ___currentSaveFileName, List<string> ___currentSaveFileBackups)
			{
				if ((Object)(object)_picker != (Object)(object)__instance)
				{
					return true;
				}
				if (!CanChooseSave || !___currentSaveFileValid)
				{
					return false;
				}
				string current = SavedRuns.Current;
				if ((!SavedRuns.Ready || current != ___currentSaveFileName) && !SavedRuns.TryLoad(___currentSaveFileName, ___currentSaveFileBackups))
				{
					if ((!SavedRuns.Ready || SavedRuns.Current != current) && !SavedRuns.TryLoad(current))
					{
						SavedRuns.StartNew((string.IsNullOrEmpty(current) || SavedRuns.Exists(current)) ? null : current);
					}
					Plugin.Notice("Save unavailable", "The selected save could not be loaded.");
					return false;
				}
				CloseSavePicker(__instance);
				Plugin.Log("Selected save '" + ___currentSaveFileName + "' in the current lobby.");
				return false;
			}
		}

		[HarmonyPatch]
		private static class ProtectSelectedSave
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				yield return AccessTools.Method(typeof(MenuPageSaves), "OnDeleteGame", (Type[])null, (Type[])null);
				yield return AccessTools.Method(typeof(MenuPageSaves), "OnRenameGame", (Type[])null, (Type[])null);
				yield return AccessTools.Method(typeof(MenuPageSaves), "OnRestoreSave", (Type[])null, (Type[])null);
			}

			private static bool Prefix(MenuPageSaves __instance, string ___currentSaveFileName)
			{
				if ((Object)(object)_picker != (Object)(object)__instance)
				{
					return true;
				}
				if (!CanChooseSave)
				{
					return false;
				}
				if (___currentSaveFileName != SavedRuns.Current)
				{
					return true;
				}
				Plugin.Notice("Save in use", "Choose another save before editing this one.");
				return false;
			}
		}

		private static MenuPageSaves? _picker;

		internal static bool CanChooseSave
		{
			get
			{
				if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && Object.op_Implicit((Object)(object)RunManager.instance) && SemiFunc.RunIsLobbyMenu() && SavedRuns.CanSave && !LobbyRecreation.Busy)
				{
					return !LobbyRecreation.Restarting.Invoke(RunManager.instance);
				}
				return false;
			}
		}

		internal static void AddButtons(Transform parent)
		{
			if (!CanChooseSave && !LobbyRecreation.TryGetOwnedLobby(out var lobby))
			{
				return;
			}
			if (SavedRuns.CanSave)
			{
				AddLobbyButton("Change Save", "Выбрать сейв", OpenSavePicker, parent, 22f, 134f);
			}
			if (LobbyRecreation.TryGetOwnedLobby(out lobby))
			{
				MenuPageLobby page = ((Component)parent).GetComponent<MenuPageLobby>();
				AddLobbyButton("Recreate Lobby", "Пересоздать лобби", delegate
				{
					LobbyRecreation.Begin(page);
				}, parent, 164f, 173f);
			}
		}

		internal static string Text(string english, string russian)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Locale selectedLocale = LocalizationSettings.SelectedLocale;
			if (selectedLocale != null)
			{
				LocaleIdentifier identifier = selectedLocale.Identifier;
				if (((LocaleIdentifier)(ref identifier)).Code.StartsWith("ru", StringComparison.OrdinalIgnoreCase))
				{
					return russian;
				}
			}
			return english;
		}

		private static void AddLobbyButton(string english, string russian, Action click, Transform parent, float x, float width)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			REPOButton obj = MenuAPI.CreateREPOButton(Text(english, russian), click, parent, new Vector2(x, 100f));
			((Object)obj).name = "NajLobby - " + english;
			((TMP_Text)obj.labelTMP).fontSize = 23f;
			obj.overrideButtonSize = new Vector2(width, 29f);
		}

		private static void OpenSavePicker()
		{
			if (CanChooseSave)
			{
				_picker = ((Component)MenuManager.instance.PageOpenOnTop((MenuPageIndex)11)).GetComponent<MenuPageSaves>();
			}
		}

		private static void CloseSavePicker(MenuPageSaves picker)
		{
			MenuManager instance = MenuManager.instance;
			instance.PageReactivatePageUnderThisPage(((Component)picker).GetComponent<MenuPage>());
			instance.PageClose((MenuPageIndex)11);
		}
	}
	internal static class LobbyReadiness
	{
		[HarmonyPatch(typeof(MenuPlayerListed), "Start")]
		private static class AddReadinessToLobbyRow
		{
			private static void Postfix(MenuPlayerListed __instance, Player? ___playerPhoton)
			{
				MenuPageLobby instance = MenuPageLobby.instance;
				if (___playerPhoton != null && PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)instance) && !((Object)(object)((Component)__instance).transform.parent != (Object)(object)instance.playerListTransform))
				{
					Transform transform = ((Component)__instance.playerHead).transform;
					RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
					if (val != null)
					{
						Transform obj = ((Component)__instance).transform.Find("Panel");
						RectTransform panel = (RectTransform)(object)((obj is RectTransform) ? obj : null);
						((Component)__instance).gameObject.AddComponent<LobbyReadyRow>().Initialize(__instance, ___playerPhoton, val, panel);
					}
				}
			}
		}

		private const string ReadyProperty = "najvlad.najlobby.ready";

		private static bool _needsReset;

		internal static bool IsReady(Player player)
		{
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom != null && !player.IsInactive && ((Dictionary<object, object>)(object)player.CustomProperties).TryGetValue((object)"najvlad.najlobby.ready", out object value) && value is string text)
			{
				return text == currentRoom.Name;
			}
			return false;
		}

		internal static bool TrySetReady(Player player, bool ready)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom == null || !currentRoom.IsOpen || player != PhotonNetwork.LocalPlayer || LobbyRecreation.Busy)
			{
				return false;
			}
			if (!player.SetCustomProperties(new Hashtable { [(object)"najvlad.najlobby.ready"] = (ready ? currentRoom.Name : null) }, (Hashtable)null, (WebFlags)null))
			{
				return false;
			}
			_needsReset = ready;
			return true;
		}

		internal static void ResetOnSceneChange(Scene previous, Scene current)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (_needsReset)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				if (localPlayer != null && localPlayer.SetCustomProperties(new Hashtable { [(object)"najvlad.najlobby.ready"] = null }, (Hashtable)null, (WebFlags)null))
				{
					_needsReset = false;
				}
			}
		}
	}
	internal sealed class LobbyReadyRow : MonoBehaviour
	{
		private static readonly Color ReadyGreen = new Color(0.48f, 0.93f, 0.6f);

		private static readonly Color IdleBorder = new Color(0.68f, 0.71f, 0.68f, 0.76f);

		private static readonly Color BadgeFill = new Color(0.035f, 0.1f, 0.06f, 0.94f);

		private static readonly Func<MenuPage, bool> CanInteract = AccessTools.MethodDelegate<Func<MenuPage, bool>>(AccessTools.PropertyGetter(typeof(MenuPage), "isInteractable"), (object)null, true);

		private static readonly Func<MenuElementHover, bool> IsHovering = AccessTools.MethodDelegate<Func<MenuElementHover, bool>>(AccessTools.PropertyGetter(typeof(MenuElementHover), "isHovering"), (object)null, true);

		private static readonly FieldRef<MenuManager, bool> SelectionChanged = AccessTools.FieldRefAccess<MenuManager, bool>("currentTargetChangedThisFrame");

		private MenuPlayerListed _row;

		private Player _player;

		private Image? _highlight;

		private Image _badge;

		private RectTransform _checkmark;

		private MenuElementHover? _hover;

		private bool? _displayedReady;

		private bool _previousBrightName;

		private bool _requestedReady;

		private float _requestDeadline;

		internal void Initialize(MenuPlayerListed row, Player player, RectTransform avatar, RectTransform? panel)
		{
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			_row = row;
			_player = player;
			if (Object.op_Implicit((Object)(object)panel))
			{
				_highlight = AddImage("NajLobby - Ready highlight", (Transform)(object)panel, new Color(0.08f, 0.34f, 0.18f, 0.72f));
				Stretch(((Graphic)_highlight).rectTransform);
				Image obj = AddImage("Edge", ((Component)_highlight).transform, ReadyGreen);
				Stretch(((Graphic)obj).rectTransform);
				((Graphic)obj).rectTransform.anchorMax = Vector2.up;
				((Graphic)obj).rectTransform.offsetMax = new Vector2(1.4f, 0f);
			}
			RectTransform val = AddRect("NajLobby - Ready avatar", (Transform)(object)avatar);
			val.pivot = Vector2.zero;
			Stretch(val);
			_badge = AddImage("Badge", (Transform)(object)val, IdleBorder);
			RectTransform rectTransform = ((Graphic)_badge).rectTransform;
			Vector2 val2 = (rectTransform.pivot = Vector2.right);
			Vector2 anchorMin = (rectTransform.anchorMax = val2);
			rectTransform.anchorMin = anchorMin;
			rectTransform.anchoredPosition = new Vector2(-3f, 3f);
			rectTransform.sizeDelta = Vector2.one * 42f;
			Stretch(((Graphic)AddImage("Face", (Transform)(object)rectTransform, BadgeFill)).rectTransform, 3f);
			_checkmark = AddRect("Checkmark", (Transform)(object)rectTransform);
			Stretch(_checkmark);
			AddCheckStroke(_checkmark, new Vector2(10f, 22f), new Vector2(18f, 14f));
			AddCheckStroke(_checkmark, new Vector2(18f, 14f), new Vector2(32f, 29f));
			if (player.IsLocal)
			{
				((Selectable)((Component)val).gameObject.AddComponent<MenuSelectableElement>()).transition = (Transition)0;
				_hover = ((Component)val).gameObject.AddComponent<MenuElementHover>();
			}
			ShowReady(LobbyReadiness.IsReady(player));
		}

		private void LateUpdate()
		{
			bool flag = LobbyReadiness.IsReady(_player);
			if (_displayedReady != flag)
			{
				ShowReady(flag);
			}
			if (flag == _requestedReady)
			{
				_requestDeadline = 0f;
			}
			MenuManager instance = MenuManager.instance;
			if (Object.op_Implicit((Object)(object)_hover) && Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)_hover.parentPage) && CanInteract(_hover.parentPage) && IsHovering(_hover) && !SelectionChanged.Invoke(instance) && SemiFunc.InputUIClick())
			{
				ToggleReady(flag);
			}
		}

		private void ToggleReady(bool ready)
		{
			if (!(Time.unscaledTime < _requestDeadline) && LobbyReadiness.TrySetReady(_player, !ready))
			{
				_requestedReady = !ready;
				_requestDeadline = Time.unscaledTime + 2f;
				MenuManager instance = MenuManager.instance;
				MenuElementHover? hover = _hover;
				instance.MenuEffectClick((MenuClickEffectType)4, (hover != null) ? hover.parentPage : null, -1f, -1f, false, true);
			}
		}

		private void ShowReady(bool ready)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (ready)
			{
				_previousBrightName = _row.brightName;
				_row.brightName = true;
			}
			else if (_displayedReady == true)
			{
				_row.brightName = _previousBrightName;
			}
			_displayedReady = ready;
			if (Object.op_Implicit((Object)(object)_highlight))
			{
				((Component)_highlight).gameObject.SetActive(ready);
			}
			((Component)_badge).gameObject.SetActive(ready || _player.IsLocal);
			((Graphic)_badge).color = (ready ? ReadyGreen : IdleBorder);
			((Component)_checkmark).gameObject.SetActive(ready);
		}

		private static RectTransform AddRect(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val).SetParent(parent, false);
			return val;
		}

		private static Image AddImage(string name, Transform parent, Color color)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)AddRect(name, parent)).gameObject.AddComponent<Image>();
			((Graphic)obj).raycastTarget = false;
			((Graphic)obj).color = color;
			return obj;
		}

		private static void Stretch(RectTransform rect, float inset = 0f)
		{
			//IL_0001: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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)
			rect.anchorMin = Vector2.zero;
			rect.anchorMax = Vector2.one;
			rect.offsetMin = Vector2.one * inset;
			rect.offsetMax = Vector2.one * (0f - inset);
		}

		private static void AddCheckStroke(RectTransform checkmark, Vector2 start, Vector2 end)
		{
			//IL_0006: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_002b: 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)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform rectTransform = ((Graphic)AddImage("Stroke", (Transform)(object)checkmark, ReadyGreen)).rectTransform;
			Vector2 anchorMin = (rectTransform.anchorMax = Vector2.zero);
			rectTransform.anchorMin = anchorMin;
			rectTransform.anchoredPosition = (start + end) * 0.5f;
			rectTransform.sizeDelta = new Vector2(Vector2.Distance(start, end) + 2f, 5f);
			((Transform)rectTransform).localEulerAngles = new Vector3(0f, 0f, Mathf.Atan2(end.y - start.y, end.x - start.x) * 57.29578f);
		}
	}
	internal static class LobbyRecreation
	{
		private sealed class Snapshot
		{
			internal SteamId LobbyId;

			internal string SaveId = "";

			internal bool Saved;

			internal string Region = "";

			internal string Password = "";

			internal int MaxPlayers;

			internal SteamId[] Guests = Array.Empty<SteamId>();

			internal bool Hosting;
		}

		[HarmonyPatch(typeof(MenuPagePassword), "Start")]
		private static class RestoreHostPassword
		{
			private static void Postfix(MenuPagePassword __instance)
			{
				//IL_0020: 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)
				Snapshot pending = _pending;
				if (pending != null && pending.Hosting)
				{
					SteamId id = ((Lobby)(ref SteamLobby.Invoke(SteamLobbyManager.instance))).Id;
					if (!((SteamId)(ref id)).IsValid)
					{
						((MonoBehaviour)Plugin.Instance).StartCoroutine(ConfirmExistingPassword(__instance, pending));
					}
				}
			}

			private static IEnumerator ConfirmExistingPassword(MenuPagePassword page, Snapshot snapshot)
			{
				yield return null;
				if (Object.op_Implicit((Object)(object)page) && _pending == snapshot)
				{
					SteamId id = ((Lobby)(ref SteamLobby.Invoke(SteamLobbyManager.instance))).Id;
					if (!((SteamId)(ref id)).IsValid)
					{
						PasswordInput.Invoke(page.passwordInput) = snapshot.Password;
						page.ConfirmButton();
					}
				}
			}
		}

		[HarmonyPatch(typeof(MenuPageLobby), "ButtonInvite")]
		private static class InviteMenu
		{
			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static Func<Friend, SteamId> <>9__1_0;

				public static Func<Friend, (SteamId Id, string Name, bool IsOnline)> <>9__1_2;

				public static Func<(SteamId Id, string Name, bool IsOnline), bool> <>9__1_3;

				public static Func<(SteamId Id, string Name, bool IsOnline), string> <>9__1_4;

				public static ScrollViewBuilderDelegate <>9__1_5;

				public static Action <>9__1_7;

				internal SteamId <Prefix>b__1_0(Friend member)
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					return member.Id;
				}

				internal (SteamId Id, string Name, bool IsOnline) <Prefix>b__1_2(Friend friend)
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					return (Id: friend.Id, Name: ((Friend)(ref friend)).Name, IsOnline: ((Friend)(ref friend)).IsOnline);
				}

				internal bool <Prefix>b__1_3((SteamId Id, string Name, bool IsOnline) friend)
				{
					return friend.IsOnline;
				}

				internal string <Prefix>b__1_4((SteamId Id, string Name, bool IsOnline) friend)
				{
					return friend.Name;
				}

				internal RectTransform <Prefix>b__1_5(Transform parent)
				{
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					return ((REPOElement)MenuAPI.CreateREPOLabel(LobbyMenus.Text("No friends to invite", "Список друзей пуст"), parent, default(Vector2))).rectTransform;
				}

				internal void <Prefix>b__1_7()
				{
				}
			}

			private static readonly Vector2 FriendRowSize = new Vector2(235f, 32f);

			private static bool Prefix()
			{
				//IL_0115: 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: Expected O, but got Unknown
				//IL_015a: Unknown result type (might be due to invalid IL or missing references)
				//IL_016e: Expected O, but got Unknown
				if (!TryGetOwnedLobby(out var lobby))
				{
					return true;
				}
				if (Busy)
				{
					return false;
				}
				HashSet<SteamId> members = new HashSet<SteamId>(((Lobby)(ref lobby)).Members.Select((Friend member) => member.Id));
				(SteamId Id, string Name, bool IsOnline)[] array = (from val3 in SteamFriends.GetFriends()
					where !members.Contains(val3.Id)
					select (Id: val3.Id, Name: ((Friend)(ref val3)).Name, IsOnline: ((Friend)(ref val3)).IsOnline) into tuple
					orderby tuple.IsOnline descending, tuple.Name
					select tuple).ToArray();
				REPOPopupPage val = MenuAPI.CreateREPOPopupPage(LobbyMenus.Text("Invite Steam Friends", "Пригласить друзей Steam"), (PresetSide)1, false, true, 2f);
				if (array.Length == 0)
				{
					object obj = <>c.<>9__1_5;
					if (obj == null)
					{
						ScrollViewBuilderDelegate val2 = (Transform parent) => ((REPOElement)MenuAPI.CreateREPOLabel(LobbyMenus.Text("No friends to invite", "Список друзей пуст"), parent, default(Vector2))).rectTransform;
						<>c.<>9__1_5 = val2;
						obj = (object)val2;
					}
					val.AddElementToScrollView((ScrollViewBuilderDelegate)obj, 0f, 0f);
				}
				(SteamId, string, bool)[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					(SteamId Id, string Name, bool IsOnline) friend = array2[num];
					val.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform parent)
					{
						//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)
						//IL_0057: Unknown result type (might be due to invalid IL or missing references)
						//IL_0067: Unknown result type (might be due to invalid IL or missing references)
						//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
						REPOButton button = MenuAPI.CreateREPOButton(friend.Name, (Action)delegate
						{
						}, parent, default(Vector2));
						((REPOElement)button).rectTransform.sizeDelta = FriendRowSize;
						button.overrideButtonSize = FriendRowSize;
						((TMP_Text)button.labelTMP).enableAutoSizing = false;
						((TMP_Text)button.labelTMP).fontSize = 20f;
						((TMP_Text)button.labelTMP).richText = false;
						((TMP_Text)button.labelTMP).textWrappingMode = (TextWrappingModes)0;
						((TMP_Text)button.labelTMP).overflowMode = (TextOverflowModes)1;
						((TMP_Text)button.labelTMP).margin = new Vector4(6f, 0f, 6f, 0f);
						button.onClick = delegate
						{
							//IL_000b: 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_0046: Unknown result type (might be due to invalid IL or missing references)
							if (TryGetOwnedLobby(out var lobby2) && SteamId.op_Implicit(((Lobby)(ref lobby2)).Id) == SteamId.op_Implicit(((Lobby)(ref lobby)).Id) && !Busy)
							{
								string text = (((Lobby)(ref lobby2)).InviteFriend(friend.Id) ? LobbyMenus.Text("Invited", "Приглашён") : LobbyMenus.Text("Invite failed", "Ошибка приглашения"));
								((TMP_Text)button.labelTMP).text = text + "  " + friend.Name;
							}
						};
						return ((REPOElement)button).rectTransform;
					}, 0f, 0f);
				}
				val.OpenPage(true);
				return false;
			}
		}

		[HarmonyPatch(typeof(Lobby), "InviteFriend")]
		private static class RememberInvite
		{
			private static void Postfix(ref Lobby __instance, SteamId steamid, bool __result)
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: 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)
				if (__result && TryGetOwnedSteamRoom(out var lobby) && SteamId.op_Implicit(((Lobby)(ref lobby)).Id) == SteamId.op_Implicit(((Lobby)(ref __instance)).Id))
				{
					Remember(lobby, steamid);
				}
			}
		}

		[HarmonyPatch(typeof(SteamLobbyManager), "OnLobbyMemberJoined")]
		private static class RememberJoin
		{
			private static void Postfix(Lobby _lobby, Friend _friend)
			{
				//IL_000b: 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_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				if (TryGetOwnedSteamRoom(out var lobby) && SteamId.op_Implicit(((Lobby)(ref lobby)).Id) == SteamId.op_Implicit(((Lobby)(ref _lobby)).Id))
				{
					Remember(lobby, _friend.Id);
				}
			}
		}

		internal static readonly FieldRef<DataDirector, string> Region = AccessTools.FieldRefAccess<DataDirector, string>("networkRegion");

		internal static readonly FieldRef<RunManager, bool> Restarting = AccessTools.FieldRefAccess<RunManager, bool>("restarting");

		private static readonly FieldRef<DataDirector, string> Password = AccessTools.FieldRefAccess<DataDirector, string>("networkPassword");

		private static readonly FieldRef<MenuTextInput, string> PasswordInput = AccessTools.FieldRefAccess<MenuTextInput, string>("textCurrent");

		private static readonly FieldRef<SteamLobbyManager, Lobby> SteamLobby = AccessTools.FieldRefAccess<SteamLobbyManager, Lobby>("currentLobby");

		private static readonly HashSet<SteamId> Guests = new HashSet<SteamId>();

		private static SteamId _trackedLobby;

		private static Snapshot? _pending;

		internal static bool Busy => _pending != null;

		internal static bool KeepsSave(string id)
		{
			return _pending?.SaveId == id;
		}

		internal static bool TryGetOwnedLobby(out Lobby lobby)
		{
			if (TryGetOwnedSteamRoom(out lobby) && Object.op_Implicit((Object)(object)RunManager.instance))
			{
				return SemiFunc.RunIsLobbyMenu();
			}
			return false;
		}

		private static bool TryGetOwnedSteamRoom(out Lobby lobby)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_004a: 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)
			lobby = default(Lobby);
			if (!SteamClient.IsValid || !Object.op_Implicit((Object)(object)SteamLobbyManager.instance) || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
			{
				return false;
			}
			lobby = SteamLobby.Invoke(SteamLobbyManager.instance);
			SteamId id = ((Lobby)(ref lobby)).Id;
			if (((SteamId)(ref id)).IsValid)
			{
				return ((Lobby)(ref lobby)).IsOwnedBy(SteamClient.SteamId);
			}
			return false;
		}

		internal static void Begin(MenuPageLobby page)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (Busy || !Object.op_Implicit((Object)(object)page) || !TryGetOwnedLobby(out var lobby) || Restarting.Invoke(RunManager.instance))
			{
				return;
			}
			TrackLobby(lobby);
			foreach (Friend member in ((Lobby)(ref lobby)).Members)
			{
				Remember(lobby, member.Id);
			}
			foreach (PlayerAvatar item in SemiFunc.PlayerGetList())
			{
				if (Object.op_Implicit((Object)(object)item) && ulong.TryParse(SemiFunc.PlayerGetSteamID(item), out var result) && result >> 52 == 17)
				{
					Remember(lobby, SteamId.op_Implicit(result));
				}
			}
			string current3 = SavedRuns.Current;
			string text = Region.Invoke(DataDirector.instance);
			_pending = new Snapshot
			{
				LobbyId = ((Lobby)(ref lobby)).Id,
				SaveId = current3,
				Saved = SavedRuns.Exists(current3),
				Region = (string.IsNullOrEmpty(text) ? PhotonNetwork.CloudRegion : text),
				Password = (Password.Invoke(DataDirector.instance) ?? ""),
				MaxPlayers = PhotonNetwork.CurrentRoom.MaxPlayers,
				Guests = Guests.ToArray()
			};
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Recreate(page, _pending));
		}

		private static IEnumerator Recreate(MenuPageLobby page, Snapshot snapshot)
		{
			try
			{
				page.ButtonLeave();
				double deadline = Time.realtimeSinceStartupAsDouble + 40.0;
				while (true)
				{
					bool flag = !Object.op_Implicit((Object)(object)MainMenuOpen.instance) || !SemiFunc.IsMainMenu();
					if (!flag)
					{
						ClientState state = PhotonNetwork.NetworkingClient.State;
						bool flag2 = (((int)state == 0 || (int)state == 14) ? true : false);
						flag = !flag2;
					}
					if (!flag)
					{
						break;
					}
					if (Time.realtimeSinceStartupAsDouble >= deadline)
					{
						Fail("The original lobby could not close.");
						yield break;
					}
					yield return null;
				}
				if (!Host(snapshot))
				{
					yield break;
				}
				deadline = Time.realtimeSinceStartupAsDouble + 50.0;
				Lobby lobby = default(Lobby);
				while (true)
				{
					if (Object.op_Implicit((Object)(object)MenuPageLobby.instance))
					{
						Room currentRoom = PhotonNetwork.CurrentRoom;
						if (currentRoom != null && currentRoom.IsOpen && TryGetOwnedLobby(out lobby) && SteamId.op_Implicit(((Lobby)(ref lobby)).Id) != SteamId.op_Implicit(snapshot.LobbyId))
						{
							break;
						}
					}
					if (Time.realtimeSinceStartupAsDouble >= deadline)
					{
						Fail("The new lobby could not open.");
						yield break;
					}
					yield return null;
				}
				TrackLobby(lobby);
				int num = 0;
				HashSet<SteamId> hashSet = new HashSet<SteamId>(((Lobby)(ref lobby)).Members.Select((Friend member) => member.Id));
				SteamId[] guests = snapshot.Guests;
				foreach (SteamId val in guests)
				{
					Remember(lobby, val);
					if (hashSet.Contains(val) || ((Lobby)(ref lobby)).InviteFriend(val))
					{
						num++;
					}
				}
				Plugin.Log($"Recreated lobby with the same save and settings. Reached {num}/{snapshot.Guests.Length} guests.");
				if (num < snapshot.Guests.Length)
				{
					Plugin.Notice("Lobby recreated", $"Reached {num} of {snapshot.Guests.Length} players through Steam.");
				}
			}
			finally
			{
				_pending = null;
			}
		}

		private static bool Host(Snapshot snapshot)
		{
			if (snapshot.Saved && !SavedRuns.Exists(snapshot.SaveId))
			{
				Fail("The selected save is unavailable.");
				return false;
			}
			try
			{
				Region.Invoke(DataDirector.instance) = snapshot.Region;
				Password.Invoke(DataDirector.instance) = snapshot.Password;
				GameManager.instance.SetMaxPlayers(snapshot.MaxPlayers);
				SemiFunc.MainMenuSetMultiplayer();
				MenuManager.instance.PageCloseAll();
				snapshot.Hosting = true;
				SemiFunc.MenuActionHostGame(snapshot.Saved ? snapshot.SaveId : null, (List<string>)null);
				if (!snapshot.Saved && !string.IsNullOrEmpty(snapshot.SaveId) && !SavedRuns.Exists(snapshot.SaveId))
				{
					StatsManager.instance.SaveFileCreate(snapshot.SaveId, false);
				}
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Warn("Could not restore the lobby: " + ex.Message);
				MenuManager.instance.PageOpen((MenuPageIndex)0, false);
				Fail("The selected save or lobby settings could not be restored.");
				return false;
			}
		}

		private static void Fail(string message)
		{
			Plugin.Warn(message);
			Plugin.Notice("Lobby recreation failed", message);
		}

		private static void TrackLobby(Lobby lobby)
		{
			//IL_0000: 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_0025: 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)
			if (SteamId.op_Implicit(_trackedLobby) != SteamId.op_Implicit(((Lobby)(ref lobby)).Id))
			{
				Guests.Clear();
				_trackedLobby = ((Lobby)(ref lobby)).Id;
			}
		}

		private static void Remember(Lobby lobby, SteamId guest)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			TrackLobby(lobby);
			if (((SteamId)(ref guest)).IsValid && SteamId.op_Implicit(guest) != SteamId.op_Implicit(SteamClient.SteamId))
			{
				Guests.Add(guest);
			}
		}
	}
	[BepInPlugin("najvlad.najlobby", "NajLobby", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class Plugin : BaseUnityPlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static BuilderDelegate <0>__AddButtons;

			public static UnityAction<Scene, Scene> <1>__ResetOnSceneChange;
		}

		internal const string Id = "najvlad.najlobby";

		internal const string Version = "1.1.1";

		private Harmony? _harmony;

		internal static Plugin Instance { get; private set; }

		internal ConfigEntry<bool> KeepSaveOnWipe { get; private set; }

		internal ConfigEntry<bool> OneHealthOnRetry { get; private set; }

		private void Awake()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			Instance = this;
			KeepSaveOnWipe = ((BaseUnityPlugin)this).Config.Bind<bool>("Recovery", "KeepSaveOnWipe", true, "Keep the checkpoint when the entire team dies.");
			OneHealthOnRetry = ((BaseUnityPlugin)this).Config.Bind<bool>("Recovery", "OneHealthOnRetry", true, "Start every player at 1 HP when resuming a level after a team wipe.");
			_harmony = new Harmony("najvlad.najlobby");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			object obj = <>O.<0>__AddButtons;
			if (obj == null)
			{
				BuilderDelegate val = LobbyMenus.AddButtons;
				<>O.<0>__AddButtons = val;
				obj = (object)val;
			}
			MenuAPI.AddElementToLobbyMenu((BuilderDelegate)obj);
			SceneManager.activeSceneChanged += LobbyReadiness.ResetOnSceneChange;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"NajLobby loaded.");
		}

		private void OnDestroy()
		{
			SceneManager.activeSceneChanged -= LobbyReadiness.ResetOnSceneChange;
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		internal static void Log(string message)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)message);
		}

		internal static void Warn(string message)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)message);
		}

		internal static void Notice(string title, string message)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)MenuManager.instance))
			{
				MenuManager.instance.PagePopUp(title, new Color(1f, 0.55f, 0f), message, "OK", false);
			}
		}
	}
	internal static class RunRecovery
	{
		private sealed class Retry
		{
			internal readonly int LevelsCompleted;

			internal readonly string LevelName;

			internal Retry(int levelsCompleted, string levelName)
			{
				LevelsCompleted = levelsCompleted;
				LevelName = levelName;
			}
		}

		[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
		private static class RecordFailure
		{
			private static void Prefix(RunManager __instance, bool _levelFailed, bool ___restarting)
			{
				if (_levelFailed && !___restarting && AllDead.Invoke(__instance) && SavedRuns.CanSave && SemiFunc.IsMasterClientOrSingleplayer() && IsRunLevel(__instance, __instance.levelCurrent) && Plugin.Instance.KeepSaveOnWipe.Value)
				{
					MarkWipe(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(DataDirector), "SaveDeleteCheck")]
		private static class KeepCheckpoint
		{
			private static bool Prefix(bool _leaveGame)
			{
				string current = SavedRuns.Current;
				if (!SemiFunc.IsMasterClientOrSingleplayer() || string.IsNullOrEmpty(current))
				{
					return true;
				}
				if (LobbyRecreation.KeepsSave(current) || RetainingWipe)
				{
					return false;
				}
				RunManager instance = RunManager.instance;
				if (!Object.op_Implicit((Object)(object)instance) || !SavedRuns.CanSave || !Plugin.Instance.KeepSaveOnWipe.Value)
				{
					return true;
				}
				if (_leaveGame && AllDead.Invoke(instance) && IsRunLevel(instance, instance.levelCurrent))
				{
					MarkWipe(instance);
					return false;
				}
				if (_leaveGame)
				{
					return !IsRetryLevel(instance);
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(StatsManager), "SaveFileSave")]
		private static class SkipFailedRunSave
		{
			private static bool Prefix()
			{
				if (!LobbyRecreation.KeepsSave(SavedRuns.Current))
				{
					if (RetainingWipe)
					{
						return !SemiFunc.RunIsArena();
					}
					return true;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(StatsManager), "SaveFileCreate")]
		private static class ClearRetryForNewRun
		{
			private static void Postfix()
			{
				_checkedSave = null;
				_retry = null;
				_wipedSave = null;
			}
		}

		[HarmonyPatch(typeof(RunManager), "SetRunLevel")]
		private static class ChooseRetryMap
		{
			private static bool Prefix(RunManager __instance)
			{
				if (RetainingWipe && !SemiFunc.IsMultiplayer() && SemiFunc.RunIsArena())
				{
					SavedRuns.TryLoad(SavedRuns.Current, null, reset: false);
				}
				if (!IsRetryLevel(__instance))
				{
					return true;
				}
				Level val = __instance.levels.Find((Level candidate) => Object.op_Implicit((Object)(object)candidate) && ((Object)candidate).name == _retry.LevelName);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return true;
				}
				__instance.levelCurrent = val;
				return false;
			}
		}

		[HarmonyPatch(typeof(MenuPageLobby), "Start")]
		private static class RestoreCheckpointInLobby
		{
			private static void Postfix()
			{
				if (LobbyMenus.CanChooseSave && RetainingWipe)
				{
					RestoreLobbySave();
				}
			}
		}

		[HarmonyPatch(typeof(MenuPageLobby), "ButtonStart")]
		private static class GuardStart
		{
			private static bool Prefix()
			{
				if (LobbyRecreation.Busy)
				{
					return false;
				}
				if (!RetainingWipe || RestoreLobbySave())
				{
					return true;
				}
				Plugin.Notice("Checkpoint unavailable", "Choose a different save to start the run.");
				return false;
			}
		}

		[HarmonyPatch(typeof(SemiFunc), "OnLevelGenDone")]
		private static class StoreFirstCheckpoint
		{
			private static void Prefix()
			{
				RunManager instance = RunManager.instance;
				if (!SemiFunc.IsMasterClientOrSingleplayer() || !IsRunLevel(instance, instance.levelCurrent) || !SavedRuns.CanSave)
				{
					return;
				}
				_wipedSave = null;
				string current = SavedRuns.Current;
				if (string.IsNullOrEmpty(current) || SavedRuns.Exists(current) || !SavedRuns.Ready || !Plugin.Instance.KeepSaveOnWipe.Value)
				{
					return;
				}
				try
				{
					StatsManager.instance.SaveGame(current);
				}
				catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0)
				{
					Plugin.Warn("Could not write the first checkpoint: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(LevelGenerator), "PlayerSpawn")]
		private static class RetrySpawnHealth
		{
			private static void Prefix(LevelGenerator __instance)
			{
				if (!ShouldSeedHealth(__instance))
				{
					return;
				}
				bool flag = false;
				foreach (PlayerAvatar item in SemiFunc.PlayerGetList())
				{
					flag |= SeedHealth(item);
				}
				if (flag && SemiFunc.IsMultiplayer())
				{
					PunManager.instance.SyncAllDictionaries();
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAvatar), "AddToStatsManagerForced")]
		private static class RetryJoiningHealth
		{
			private static void Postfix(PlayerAvatar __instance)
			{
				LevelGenerator instance = LevelGenerator.Instance;
				if (Object.op_Implicit((Object)(object)instance) && (Object)(object)_spawnScene == (Object)(object)instance && ShouldSeedHealth(instance) && SeedHealth(__instance) && SemiFunc.IsMultiplayer())
				{
					PunManager.instance.SyncAllDictionaries();
				}
			}
		}

		private const string RetryFileName = "najlobby-retry.txt";

		private static readonly FieldRef<RunManager, bool> AllDead = AccessTools.FieldRefAccess<RunManager, bool>("allPlayersDead");

		private static readonly HashSet<PlayerAvatar> SpawnedForRetry = new HashSet<PlayerAvatar>();

		private static LevelGenerator? _spawnScene;

		private static string? _checkedSave;

		private static Retry? _retry;

		private static string? _wipedSave;

		private static bool RetainingWipe
		{
			get
			{
				if (_wipedSave != null)
				{
					return _wipedSave == SavedRuns.Current;
				}
				return false;
			}
		}

		private static bool IsRunLevel(RunManager run, Level level)
		{
			if (Object.op_Implicit((Object)(object)level) && (Object)(object)level != (Object)(object)run.levelRecording)
			{
				return SemiFunc.RunIsLevel(level);
			}
			return false;
		}

		private static bool IsRetryLevel(RunManager run)
		{
			string current = SavedRuns.Current;
			if (_checkedSave != current)
			{
				_checkedSave = current;
				_retry = (string.IsNullOrEmpty(current) ? null : ReadRetry(current));
				if (_wipedSave != current)
				{
					_wipedSave = null;
				}
			}
			if (_retry != null)
			{
				return run.levelsCompleted == _retry.LevelsCompleted;
			}
			return false;
		}

		private static void MarkWipe(RunManager run)
		{
			string current = SavedRuns.Current;
			if (string.IsNullOrEmpty(current) || RetainingWipe)
			{
				return;
			}
			_wipedSave = current;
			_checkedSave = current;
			_retry = new Retry(run.levelsCompleted, ((Object)run.levelCurrent).name);
			if (!SavedRuns.Exists(current))
			{
				Plugin.Warn("The team wiped before a checkpoint reached disk.");
				return;
			}
			string text = Path.Combine(SavedRuns.Root, current, "najlobby-retry.txt");
			string text2 = text + ".tmp";
			try
			{
				File.WriteAllLines(text2, new string[2]
				{
					run.levelsCompleted.ToString(CultureInfo.InvariantCulture),
					((Object)run.levelCurrent).name
				});
				if (File.Exists(text))
				{
					File.Replace(text2, text, null);
				}
				else
				{
					File.Move(text2, text);
				}
				Plugin.Log($"Kept the checkpoint for level {run.levelsCompleted + 1} after a team wipe.");
			}
			catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0)
			{
				Plugin.Warn("Could not record the retry level: " + ex.Message);
			}
		}

		private static Retry? ReadRetry(string id)
		{
			string path = Path.Combine(SavedRuns.Root, id, "najlobby-retry.txt");
			try
			{
				if (File.Exists(path))
				{
					string[] array = File.ReadAllLines(path);
					if (array.Length == 2 && int.TryParse(array[0], NumberStyles.None, CultureInfo.InvariantCulture, out var result) && !string.IsNullOrWhiteSpace(array[1]))
					{
						return new Retry(result, array[1]);
					}
				}
			}
			catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0)
			{
				Plugin.Warn("Could not read the retry level: " + ex.Message);
			}
			return null;
		}

		private static bool RestoreLobbySave()
		{
			if (!SavedRuns.Ready && !SavedRuns.TryLoad(SavedRuns.Current))
			{
				return false;
			}
			_wipedSave = null;
			return true;
		}

		private static bool ShouldSeedHealth(LevelGenerator scene)
		{
			RunManager instance = RunManager.instance;
			if (!Object.op_Implicit((Object)(object)scene) || !Object.op_Implicit((Object)(object)instance) || !SemiFunc.IsMasterClientOrSingleplayer() || !SavedRuns.CanSave || !Plugin.Instance.OneHealthOnRetry.Value || !IsRetryLevel(instance) || (Object)(object)scene.Level != (Object)(object)instance.levelCurrent || !IsRunLevel(instance, scene.Level))
			{
				return false;
			}
			if ((Object)(object)_spawnScene != (Object)(object)scene)
			{
				_spawnScene = scene;
				SpawnedForRetry.Clear();
			}
			return true;
		}

		private static bool SeedHealth(PlayerAvatar avatar)
		{
			if (!Object.op_Implicit((Object)(object)avatar))
			{
				return false;
			}
			string text = SemiFunc.PlayerGetSteamID(avatar);
			if (string.IsNullOrEmpty(text) || !SpawnedForRetry.Add(avatar))
			{
				return false;
			}
			StatsManager.instance.SetPlayerHealth(text, 1, false);
			return true;
		}
	}
	internal static class SavedRuns
	{
		[HarmonyPatch(typeof(StatsManager), "SaveFileCreate")]
		private static class UniqueSaveId
		{
			private static void Prefix(ref string saveFileName, bool saveIsDebug)
			{
				if (string.IsNullOrEmpty(saveFileName) && !saveIsDebug)
				{
					saveFileName = NewId();
				}
			}
		}

		private static readonly FieldRef<StatsManager, string> SaveId = AccessTools.FieldRefAccess<StatsManager, string>("saveFileCurrent");

		private static readonly FieldRef<StatsManager, bool> SaveReady = AccessTools.FieldRefAccess<StatsManager, bool>("saveFileReady");

		private static readonly FieldRef<GameManager, LobbyTypes> LobbyType = AccessTools.FieldRefAccess<GameManager, LobbyTypes>("lobbyType");

		internal static string Current
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)StatsManager.instance))
				{
					return "";
				}
				return SaveId.Invoke(StatsManager.instance) ?? "";
			}
		}

		internal static bool Ready
		{
			get
			{
				if (Object.op_Implicit((Object)(object)StatsManager.instance))
				{
					return SaveReady.Invoke(StatsManager.instance);
				}
				return false;
			}
		}

		internal static bool CanSave
		{
			get
			{
				if (Object.op_Implicit((Object)(object)StatsManager.instance) && Object.op_Implicit((Object)(object)GameManager.instance))
				{
					return StatsManager.instance.savedLobbyTypes.Contains(LobbyType.Invoke(GameManager.instance));
				}
				return false;
			}
		}

		internal static string Root => Path.Combine(Application.persistentDataPath, "saves");

		internal static bool Exists(string id)
		{
			if (!string.IsNullOrEmpty(id))
			{
				return File.Exists(Path.Combine(Root, id, id + ".es3"));
			}
			return false;
		}

		internal static void StartNew(string? id = null)
		{
			RunManager.instance.ResetProgress();
			StatsManager.instance.SaveFileCreate(id ?? NewId(), false);
		}

		internal static string NewId()
		{
			string text = "REPO_SAVE_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss", CultureInfo.InvariantCulture);
			if (!Directory.Exists(Path.Combine(Root, text)))
			{
				return text;
			}
			return text + "_" + Guid.NewGuid().ToString("N").Substring(0, 8);
		}

		internal static bool TryLoad(string id, List<string>? backups = null, bool reset = true)
		{
			if (!Exists(id))
			{
				return false;
			}
			StatsManager instance = StatsManager.instance;
			try
			{
				if (!int.TryParse(instance.SaveFileGetRunLevel(id, (string)null), out var result) || !int.TryParse(instance.SaveFileGetRunCurrency(id, (string)null), out result) || !int.TryParse(instance.SaveFileGetTotalHaul(id, (string)null), out result))
				{
					return false;
				}
				if (reset)
				{
					RunManager.instance.ResetProgress();
				}
				SemiFunc.SaveFileLoad(id, backups ?? instance.SaveFileGetBackups(id, Root));
				RunManager.instance.UpdateMoonLevel();
				return Ready && Current == id;
			}
			catch (Exception ex)
			{
				Plugin.Warn("Could not load save '" + id + "': " + ex.Message);
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(MenuPageSaves), "OnNewGame")]
	internal static class UnlimitedSaves
	{
		[HarmonyPrefix]
		private static void RemoveSaveLimit(MenuPageSaves __instance)
		{
			__instance.maxSaveFiles = 0;
		}
	}
}