Decompiled source of RepoGrowth v0.1.0

RepoGrowth.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("RepoGrowth")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RepoGrowth")]
[assembly: AssemblyTitle("RepoGrowth")]
[assembly: AssemblyVersion("1.0.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 RepoGrowth
{
	[BepInPlugin("den.repo.growth", "REPO Growth", "0.6.0")]
	[DefaultExecutionOrder(10000)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class Profile
		{
			public int XP;

			public int Unspent;

			public int Level = 1;

			public int Progress;

			public readonly int[] Permanent = new int[4];
		}

		private sealed class Applied
		{
			public IDictionary<string, int> Dict;

			public string Id;

			public int Count;
		}

		private sealed class SaveState
		{
			public bool Owner;

			public bool Reset;

			public readonly List<Tuple<Applied, int, int>> Values = new List<Tuple<Applied, int, int>>();
		}

		private const string ProfileKey = "den.growth.personal.v5";

		private const string Protocol = "den.repo.growth.award.v5";

		private const byte AwardEvent = 174;

		private static Plugin self;

		private readonly Dictionary<string, Profile> profiles = new Dictionary<string, Profile>();

		private readonly Dictionary<string, Applied> applied = new Dictionary<string, Applied>();

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

		private readonly string[] labels = new string[4] { "Strength", "Max HP", "Stamina", "Sprint Speed" };

		private readonly string[] methods = new string[4] { "UpgradePlayerGrabStrength", "UpgradePlayerHealth", "UpgradePlayerEnergy", "UpgradePlayerSprintSpeed" };

		private readonly string[] fields = new string[4] { "playerUpgradeStrength", "playerUpgradeHealth", "playerUpgradeStamina", "playerUpgradeSpeed" };

		private readonly MethodInfo[] upgrades = new MethodInfo[4];

		private readonly FieldInfo[] dictionaries = new FieldInfo[4];

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

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

		private int killRewards;

		private FieldInfo extractionStart;

		private CursorLockMode savedLock;

		private bool savedVisible;

		private ConfigEntry<int> perExtraction;

		private ConfigEntry<int> perKill;

		private ConfigEntry<int> killLimit;

		private Harmony harmony;

		private ConfigEntry<bool> growthEnabled;

		private ConfigEntry<int> perClear;

		private ConfigEntry<int> perLevel;

		private ConfigEntry<int> cap;

		private ConfigEntry<int> xpIncrease;

		private bool ready;

		private bool show = true;

		private bool menu;

		private bool saving;

		private bool blocked;

		private int handledScene = int.MinValue;

		private float lastTick;

		private float nextSpend;

		private string file;

		private string room = "";

		private string localId = "";

		private string published = "";

		private int originalMaster;

		private readonly int[] lastGrowth = new int[4] { -1, -1, -1, -1 };

		private float nextGrowthCheck;

		private static bool Host
		{
			get
			{
				if (SemiFunc.IsMultiplayer())
				{
					return PhotonNetwork.IsMasterClient;
				}
				return true;
			}
		}

		private int Step => Mathf.Clamp(perLevel.Value, 50, 10000);

		private int Gain => Mathf.Clamp(perClear.Value, 1, Step);

		private int Cap => Mathf.Clamp(cap.Value, 1, 100);

		private bool ActiveHost
		{
			get
			{
				if (ready && growthEnabled.Value && Host && !blocked)
				{
					return !saving;
				}
				return false;
			}
		}

		private int NeedXP(int level)
		{
			return (int)Math.Min(1000000L, Step + (long)Mathf.Clamp(xpIncrease.Value, 0, 10000) * (long)Math.Max(0, level - 1));
		}

		private void Awake()
		{
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Expected O, but got Unknown
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Expected O, but got Unknown
			//IL_036d: Expected O, but got Unknown
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Expected O, but got Unknown
			//IL_03c4: Expected O, but got Unknown
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Expected O, but got Unknown
			//IL_04f8: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_046a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0477: Expected O, but got Unknown
			//IL_0477: Expected O, but got Unknown
			self = this;
			growthEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Host progression growthEnabled");
			perClear = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "XPPerClear", 100, "XP per successful stage");
			perLevel = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "XPPerLevel", 200, "Starting XP per level");
			xpIncrease = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "XPPerLevelIncrease", 50, "Extra XP needed per next level");
			cap = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "MaxPerSkill", 20, "Maximum allocated points per skill");
			perExtraction = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "XPPerExtraction", 40, "XP per completed extraction point (team)");
			perKill = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "XPPerEnemyKill", 25, "XP per distinct enemy defeated (team)");
			killLimit = ((BaseUnityPlugin)this).Config.Bind<int>("Balance", "MaxRewardedKillsPerStage", 10, "Limit rewarded unique enemies per stage");
			file = Path.Combine(Paths.ConfigPath, "den.repo.growth.personal.tsv");
			Load();
			for (int i = 0; i < 4; i++)
			{
				upgrades[i] = AccessTools.Method(typeof(PunManager), methods[i], new Type[2]
				{
					typeof(string),
					typeof(int)
				}, (Type[])null) ?? AccessTools.Method(typeof(PunManager), methods[i], new Type[1] { typeof(string) }, (Type[])null);
				dictionaries[i] = AccessTools.Field(typeof(StatsManager), fields[i]);
			}
			MethodInfo[] array = (from m in typeof(RunManager).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "ChangeLevel" && m.GetParameters().Any((ParameterInfo p) => p.Name == "_completedLevel" && p.ParameterType == typeof(bool)) && m.GetParameters().Any((ParameterInfo p) => p.Name == "_levelFailed" && p.ParameterType == typeof(bool))
				select m).ToArray();
			MethodInfo methodInfo = AccessTools.Method(typeof(StatsManager), "SaveGame", new Type[1] { typeof(string) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(StatsManager), "LoadGame", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(StatsManager), "ResetAllStats", Type.EmptyTypes, (Type[])null);
			if (array.Length != 1 || methodInfo == null || methodInfo2 == null || methodInfo3 == null || upgrades.Any((MethodInfo x) => x == null) || dictionaries.Any((FieldInfo x) => x == null))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Unsupported REPO API; no changes made.");
				return;
			}
			harmony = new Harmony("den.repo.growth");
			try
			{
				harmony.Patch((MethodBase)array[0], new HarmonyMethod(typeof(Plugin), "BeforeChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "BeforeSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterOperation", (Type[])null), (HarmonyMethod)null);
				MethodInfo[] array2 = new MethodInfo[2] { methodInfo2, methodInfo3 };
				foreach (MethodInfo methodInfo4 in array2)
				{
					harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(Plugin), "BeforeReset", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterOperation", (Type[])null), (HarmonyMethod)null);
				}
				extractionStart = AccessTools.Field(typeof(ExtractionPoint), "stateStart");
				MethodInfo methodInfo5 = AccessTools.Method(typeof(ExtractionPoint), "StateComplete", Type.EmptyTypes, (Type[])null);
				if (methodInfo5 != null && extractionStart != null && extractionStart.FieldType == typeof(bool))
				{
					harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(Plugin), "ExtractBefore", (Type[])null), new HarmonyMethod(typeof(Plugin), "ExtractAfter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Extraction XP unavailable: API not found.");
				}
				MethodInfo methodInfo6 = AccessTools.Method(typeof(EnemyHealth), "Death", new Type[1] { typeof(Vector3) }, (Type[])null);
				if (methodInfo6 != null)
				{
					harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(typeof(Plugin), "DeathBefore", (Type[])null), new HarmonyMethod(typeof(Plugin), "DeathAfter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Enemy XP unavailable: API not found.");
				}
				PhotonNetwork.NetworkingClient.EventReceived += OnNetworkEvent;
				SceneManager.sceneLoaded += OnScene;
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"REPO Growth v0.6 initialized");
			}
			catch (Exception ex)
			{
				harmony.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
			}
		}

		private void OnDestroy()
		{
			if (ready)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= OnNetworkEvent;
				SceneManager.sceneLoaded -= OnScene;
			}
			SetMenu(open: false);
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if ((Object)(object)self == (Object)(object)this)
			{
				self = null;
			}
		}

		private void OnScene(Scene s, LoadSceneMode mode)
		{
			for (int i = 0; i < 4; i++)
			{
				lastGrowth[i] = -1;
			}
			handledScene = int.MinValue;
			extracted.Clear();
			killed.Clear();
			killRewards = 0;
			SetMenu(open: false);
		}

		private void OnApplicationFocus(bool focus)
		{
			if (!focus)
			{
				SetMenu(open: false);
			}
		}

		private void OnDisable()
		{
			SetMenu(open: false);
		}

		private static bool SkillArea()
		{
			if ((Object)(object)RunManager.instance != (Object)null)
			{
				if (!SemiFunc.RunIsLevel() && !SemiFunc.RunIsShop() && !SemiFunc.RunIsLobby())
				{
					return SemiFunc.RunIsLobbyMenu();
				}
				return true;
			}
			return false;
		}

		private void SetMenu(bool open)
		{
			//IL_0050: 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)
			if (menu == open)
			{
				return;
			}
			if (open)
			{
				if (ready && SkillArea())
				{
					savedLock = Cursor.lockState;
					savedVisible = Cursor.visible;
					menu = true;
					show = true;
					HoldMenuInput();
				}
			}
			else
			{
				menu = false;
				Cursor.lockState = savedLock;
				Cursor.visible = savedVisible;
			}
		}

		private void HoldMenuInput()
		{
			if (menu)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
				if ((Object)(object)GameDirector.instance != (Object)null)
				{
					GameDirector.instance.SetDisableInput(0.1f);
				}
				if ((Object)(object)PlayerController.instance != (Object)null)
				{
					PlayerController.instance.InputDisable(0.1f);
				}
				if ((Object)(object)InputManager.instance != (Object)null)
				{
					SemiFunc.InputDisableMovement();
					SemiFunc.InputDisableAiming();
				}
			}
		}

		private void LateUpdate()
		{
			if (menu)
			{
				HoldMenuInput();
			}
			CheckLocalGrowth();
		}

		private static bool ValidId(string id)
		{
			if (!string.IsNullOrWhiteSpace(id) && id.Length <= 64)
			{
				return id.All(char.IsDigit);
			}
			return false;
		}

		private Profile Get(string id)
		{
			if (!profiles.TryGetValue(id, out var value))
			{
				value = (profiles[id] = new Profile());
			}
			return value;
		}

		private static void BeforeChange(bool _completedLevel, bool _levelFailed)
		{
			try
			{
				if ((Object)(object)self != (Object)null && _completedLevel && !_levelFailed)
				{
					self.Reward();
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogError((object)ex);
				}
			}
		}

		private void Reward()
		{
			//IL_0010: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			if (ActiveHost && SemiFunc.RunIsLevel())
			{
				Scene activeScene = SceneManager.GetActiveScene();
				int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
				if (handledScene != num)
				{
					handledScene = num;
					AwardTeam(Gain, "Stage clear");
				}
			}
		}

		private static void ExtractBefore(ExtractionPoint __instance, out int __state)
		{
			__state = 0;
			try
			{
				bool flag = default(bool);
				int num;
				if ((Object)(object)self != (Object)null && self.ActiveHost && SemiFunc.RunIsLevel() && (Object)(object)__instance != (Object)null)
				{
					object value = self.extractionStart.GetValue(__instance);
					if (value is bool)
					{
						flag = (bool)value;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				if (((uint)num & (flag ? 1u : 0u)) != 0)
				{
					__state = ((Object)__instance).GetInstanceID();
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogWarning((object)ex);
				}
			}
		}

		private static void ExtractAfter(int __state)
		{
			try
			{
				if ((Object)(object)self != (Object)null && __state != 0 && self.ActiveHost && self.extracted.Add(__state))
				{
					self.AwardTeam(Mathf.Clamp(self.perExtraction.Value, 0, 10000), "Extraction");
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogWarning((object)ex);
				}
			}
		}

		private static void DeathBefore(EnemyHealth __instance, out int __state)
		{
			__state = 0;
			try
			{
				if (!((Object)(object)self == (Object)null) && self.ActiveHost && SemiFunc.RunIsLevel() && !((Object)(object)__instance == (Object)null))
				{
					EnemyParent componentInParent = ((Component)__instance).GetComponentInParent<EnemyParent>();
					__state = (((Object)(object)componentInParent != (Object)null) ? ((Object)componentInParent).GetInstanceID() : ((Object)__instance).GetInstanceID());
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogWarning((object)ex);
				}
			}
		}

		private static void DeathAfter(int __state)
		{
			try
			{
				if (!((Object)(object)self == (Object)null) && __state != 0 && self.ActiveHost && self.killed.Add(__state) && self.killRewards < Mathf.Clamp(self.killLimit.Value, 0, 100))
				{
					self.killRewards++;
					self.AwardTeam(Mathf.Clamp(self.perKill.Value, 0, 10000), "Enemy defeated");
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogWarning((object)ex);
				}
			}
		}

		private void AwardTeam(int amount, string reason)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			if (!ActiveHost || !SemiFunc.RunIsLevel() || amount <= 0)
			{
				return;
			}
			HashSet<string> hashSet = new HashSet<string>();
			string text = LocalId();
			foreach (PlayerAvatar item in SemiFunc.PlayerGetAll())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				string text2 = SemiFunc.PlayerGetSteamID(item);
				if (!ValidId(text2) || !hashSet.Add(text2))
				{
					continue;
				}
				if (text2 == text)
				{
					Credit(text2, amount, reason);
				}
				else if (PhotonNetwork.InRoom)
				{
					PhotonView component = ((Component)item).GetComponent<PhotonView>();
					if (!((Object)(object)component == (Object)null) && component.Owner != null && TryRemote(item, text2, out var _))
					{
						object[] obj = new object[5]
						{
							"den.repo.growth.award.v5",
							text2,
							amount,
							Guid.NewGuid().ToString("N"),
							reason
						};
						RaiseEventOptions val = new RaiseEventOptions();
						val.TargetActors = new int[1] { component.OwnerActorNr };
						PhotonNetwork.RaiseEvent((byte)174, (object)obj, val, SendOptions.SendReliable);
					}
				}
			}
		}

		private string LocalId()
		{
			if ((Object)(object)PlayerAvatar.instance != (Object)null)
			{
				string id = SemiFunc.PlayerGetSteamID(PlayerAvatar.instance);
				if (ValidId(id))
				{
					localId = id;
				}
			}
			return localId;
		}

		private void Credit(string id, int amount, string reason)
		{
			if (ValidId(id) && !(id != LocalId()) && amount > 0 && amount <= 10000)
			{
				Profile profile = Get(id);
				int xP = profile.XP;
				int unspent = profile.Unspent;
				int level = profile.Level;
				int progress = profile.Progress;
				profile.XP = Math.Min(100000000, xP + amount);
				profile.Progress += profile.XP - xP;
				while (profile.Progress >= NeedXP(profile.Level))
				{
					profile.Progress -= NeedXP(profile.Level);
					profile.Level++;
					profile.Unspent++;
				}
				if (!Save())
				{
					profile.XP = xP;
					profile.Unspent = unspent;
					profile.Level = level;
					profile.Progress = progress;
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)(reason + " +" + amount + " XP"));
					PublishLocal();
				}
			}
		}

		private bool TryRemote(PlayerAvatar avatar, string id, out Profile p)
		{
			p = null;
			PhotonView component = ((Component)avatar).GetComponent<PhotonView>();
			if ((Object)(object)component == (Object)null || component.Owner == null || !((Dictionary<object, object>)(object)component.Owner.CustomProperties).TryGetValue((object)"den.growth.personal.v5", out object value) || !(value is string text))
			{
				return false;
			}
			string[] array = text.Split(',');
			if (array.Length != 7 || array[0] != id || !ValidId(id) || !int.TryParse(array[1], out var result) || result < 0 || result > 100000000 || !int.TryParse(array[2], out var result2) || result2 < 0 || result2 > 2000000)
			{
				return false;
			}
			Profile profile = new Profile
			{
				XP = result,
				Unspent = result2
			};
			for (int i = 0; i < 4; i++)
			{
				if (!int.TryParse(array[i + 3], out profile.Permanent[i]) || profile.Permanent[i] < 0 || profile.Permanent[i] > 1000)
				{
					return false;
				}
			}
			p = profile;
			return true;
		}

		private void PublishLocal()
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00aa: Expected O, but got Unknown
			if (!PhotonNetwork.InRoom || PhotonNetwork.LocalPlayer == null)
			{
				return;
			}
			string text = LocalId();
			if (!ValidId(text))
			{
				return;
			}
			Profile profile = Get(text);
			string text2 = text + "," + profile.XP + "," + profile.Unspent + "," + string.Join(",", profile.Permanent);
			if (!(text2 == published))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"den.growth.personal.v5", (object)text2);
				if (localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null))
				{
					published = text2;
				}
			}
		}

		private IDictionary<string, int> Dict(int b)
		{
			if (!((Object)(object)StatsManager.instance == (Object)null))
			{
				return dictionaries[b].GetValue(StatsManager.instance) as IDictionary<string, int>;
			}
			return null;
		}

		private void Reconcile(string id, Profile p)
		{
			if (!ActiveHost || (Object)(object)PunManager.instance == (Object)null || p == null)
			{
				return;
			}
			for (int i = 0; i < 4; i++)
			{
				IDictionary<string, int> dictionary = Dict(i);
				if (dictionary == null)
				{
					continue;
				}
				if (!dictionary.TryGetValue(id, out var value))
				{
					if (p.Permanent[i] <= 0 || !SemiFunc.LevelGenDone())
					{
						continue;
					}
					dictionary[id] = 0;
					value = 0;
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Growth: initialized missing stat " + labels[i]));
				}
				if (value < 0)
				{
					continue;
				}
				string key = id + ":" + i;
				if (!applied.TryGetValue(key, out var value2) || value2.Dict != dictionary)
				{
					Dictionary<string, Applied> dictionary2 = applied;
					Applied obj = new Applied
					{
						Dict = dictionary,
						Id = id,
						Count = 0
					};
					value2 = obj;
					dictionary2[key] = obj;
				}
				if (value < value2.Count)
				{
					blocked = true;
					((BaseUnityPlugin)this).Logger.LogError((object)"Upgrade ledger mismatch; progression suspended until next game reset.");
					break;
				}
				int num = Math.Min(20, p.Permanent[i] - value2.Count);
				for (int j = 0; j < num; j++)
				{
					int num2 = dictionary[id];
					value2.Count++;
					try
					{
						MethodInfo methodInfo = upgrades[i];
						methodInfo.Invoke(PunManager.instance, (methodInfo.GetParameters().Length != 2) ? new object[1] { id } : new object[2] { id, 1 });
					}
					catch (Exception ex)
					{
						if (dictionary[id] == num2)
						{
							value2.Count--;
						}
						blocked = true;
						((BaseUnityPlugin)this).Logger.LogError((object)ex);
						return;
					}
					if (dictionary[id] != num2 + 1)
					{
						value2.Count--;
						blocked = true;
						((BaseUnityPlugin)this).Logger.LogError((object)"Unexpected upgrade change; progression suspended.");
						return;
					}
				}
			}
		}

		private static void BeforeSave(ref SaveState __state)
		{
			__state = self?.Strip(reset: false);
		}

		private static void BeforeReset(ref SaveState __state)
		{
			__state = self?.Strip(reset: true);
		}

		private SaveState Strip(bool reset)
		{
			SaveState saveState = new SaveState
			{
				Reset = reset
			};
			if (!ready || !Host || saving)
			{
				return saveState;
			}
			saving = true;
			saveState.Owner = true;
			try
			{
				foreach (Applied value2 in applied.Values)
				{
					if (value2.Count > 0 && value2.Dict.TryGetValue(value2.Id, out var value) && value >= value2.Count)
					{
						value2.Dict[value2.Id] = value - value2.Count;
						saveState.Values.Add(Tuple.Create(value2, value, value - value2.Count));
					}
				}
				return saveState;
			}
			catch
			{
				foreach (Tuple<Applied, int, int> value3 in saveState.Values)
				{
					value3.Item1.Dict[value3.Item1.Id] = value3.Item2;
				}
				saving = false;
				throw;
			}
		}

		private static Exception AfterOperation(Exception __exception, SaveState __state)
		{
			if ((Object)(object)self == (Object)null || __state == null || !__state.Owner)
			{
				return __exception;
			}
			try
			{
				if (__state.Reset && __exception == null)
				{
					self.applied.Clear();
					self.blocked = false;
				}
				else
				{
					foreach (Tuple<Applied, int, int> value2 in __state.Values)
					{
						if (value2.Item1.Dict.TryGetValue(value2.Item1.Id, out var value) && value == value2.Item3)
						{
							value2.Item1.Dict[value2.Item1.Id] = value2.Item2;
						}
						else
						{
							self.blocked = true;
						}
					}
				}
			}
			finally
			{
				self.saving = false;
			}
			return __exception;
		}

		private void RequestSpend(int branch)
		{
			if (!ready || !growthEnabled.Value || blocked || !SkillArea() || branch < 0 || branch >= 4 || Time.unscaledTime < nextSpend)
			{
				return;
			}
			nextSpend = Time.unscaledTime + 0.35f;
			string id = LocalId();
			if (!ValidId(id))
			{
				return;
			}
			Profile profile = Get(id);
			if (profile.Unspent <= 0 || profile.Permanent[branch] >= Cap)
			{
				return;
			}
			profile.Unspent--;
			profile.Permanent[branch]++;
			if (!Save())
			{
				profile.Unspent++;
				profile.Permanent[branch]--;
				return;
			}
			PublishLocal();
			if (Host)
			{
				Reconcile(id, profile);
			}
		}

		private void OnNetworkEvent(EventData e)
		{
			if (e.Code != 174 || !ready || blocked || !PhotonNetwork.InRoom || PhotonNetwork.MasterClient == null || e.Sender != PhotonNetwork.MasterClient.ActorNumber || !(e.CustomData is object[] array) || array.Length != 5 || !object.Equals(array[0], "den.repo.growth.award.v5") || !(array[1] is string text) || text != LocalId() || !(array[2] is int num) || num <= 0 || num > 10000 || !(array[3] is string { Length: 32 } text2) || !(array[4] is string { Length: <=80 } text3) || requests.Count >= 100000 || !requests.Add(e.Sender + ":" + text2))
			{
				return;
			}
			try
			{
				Credit(text, num, text3);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
			}
		}

		private void Update()
		{
			if (!ready)
			{
				return;
			}
			string text = (PhotonNetwork.InRoom ? PhotonNetwork.CurrentRoom.Name : "");
			if (room != text)
			{
				room = text;
				requests.Clear();
				published = "";
				originalMaster = ((PhotonNetwork.InRoom && PhotonNetwork.MasterClient != null) ? PhotonNetwork.MasterClient.ActorNumber : 0);
			}
			if (PhotonNetwork.InRoom && PhotonNetwork.MasterClient != null && PhotonNetwork.MasterClient.ActorNumber != originalMaster)
			{
				blocked = true;
			}
			if (menu && !SkillArea())
			{
				SetMenu(open: false);
			}
			if (Input.GetKeyDown((KeyCode)287))
			{
				SetMenu(!menu);
			}
			if (menu && Input.GetKeyDown((KeyCode)27))
			{
				SetMenu(open: false);
			}
			if (menu)
			{
				HoldMenuInput();
			}
			if (Time.unscaledTime - lastTick < 1f)
			{
				return;
			}
			lastTick = Time.unscaledTime;
			if (growthEnabled.Value && !blocked)
			{
				PublishLocal();
			}
			RefreshLocalGrowth();
			if (!ActiveHost || !SkillArea())
			{
				return;
			}
			try
			{
				foreach (PlayerAvatar item in SemiFunc.PlayerGetAll())
				{
					if ((Object)(object)item == (Object)null)
					{
						continue;
					}
					string text2 = SemiFunc.PlayerGetSteamID(item);
					if (ValidId(text2))
					{
						Profile p;
						if (text2 == LocalId())
						{
							Reconcile(text2, Get(text2));
						}
						else if (PhotonNetwork.InRoom && TryRemote(item, text2, out p))
						{
							Reconcile(text2, p);
						}
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex);
			}
		}

		private void RefreshLocalGrowth()
		{
			if (!SkillArea() || (Object)(object)PunManager.instance == (Object)null)
			{
				return;
			}
			string text = LocalId();
			if (!ValidId(text))
			{
				return;
			}
			Profile profile = Get(text);
			string[] array = new string[4] { "UpdateGrabStrengthRightAway", "UpdateHealthRightAway", "UpdateEnergyRightAway", "UpdateSprintSpeedRightAway" };
			for (int i = 0; i < 4; i++)
			{
				if (profile.Permanent[i] <= 0)
				{
					continue;
				}
				IDictionary<string, int> dictionary = Dict(i);
				if (dictionary == null || !dictionary.TryGetValue(text, out var value) || lastGrowth[i] == value)
				{
					continue;
				}
				lastGrowth[i] = value;
				((BaseUnityPlugin)this).Logger.LogInfo((object)(labels[i] + " Permanent=" + profile.Permanent[i] + " Total=" + value));
				if (value >= profile.Permanent[i])
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(PunManager), array[i], new Type[2]
					{
						typeof(string),
						typeof(int)
					}, (Type[])null);
					if (methodInfo != null)
					{
						methodInfo.Invoke(PunManager.instance, new object[2] { text, value });
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Growth refresh: " + labels[i] + " +" + value));
					}
				}
			}
		}

		private void CheckLocalGrowth()
		{
			if (!ready || !SkillArea() || Time.unscaledTime < nextGrowthCheck)
			{
				return;
			}
			nextGrowthCheck = Time.unscaledTime + 5f;
			string text = LocalId();
			if (!ValidId(text))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Growth debug: No local ID");
				return;
			}
			Profile profile = Get(text);
			IDictionary<string, int> dictionary = Dict(1);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Growth debug: HP permanent=" + profile.Permanent[1] + " Host=" + Host + " ActiveHost=" + ActiveHost + " Dictionary=" + (dictionary != null) + " PlayerFound=" + (dictionary?.ContainsKey(text) ?? false)));
			if (ActiveHost && (Object)(object)PlayerAvatar.instance != (Object)null)
			{
				Reconcile(text, profile);
			}
			RefreshLocalGrowth();
			if (dictionary != null && dictionary.ContainsKey(text))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Growth debug: HP total=" + dictionary[text]));
			}
		}

		private bool ReadLocal(out int[] v)
		{
			v = new int[9];
			string id = LocalId();
			if (!ready || !growthEnabled.Value || !ValidId(id) || blocked)
			{
				return false;
			}
			Profile profile = Get(id);
			v[0] = profile.Progress;
			v[1] = profile.Unspent;
			Array.Copy(profile.Permanent, 0, v, 2, 4);
			v[6] = NeedXP(profile.Level);
			v[7] = Cap;
			v[8] = profile.Level;
			return true;
		}

		private void OnGUI()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || !show || !SkillArea())
			{
				return;
			}
			int[] v;
			bool flag = ReadLocal(out v) && !blocked;
			if (!menu)
			{
				GUI.Box(new Rect(18f, 75f, 300f, 74f), "");
				GUI.Label(new Rect(28f, 80f, 280f, 22f), flag ? ("GROWTH LV " + v[8] + "  EXP " + v[0] + "/" + v[6]) : "GROWTH waiting / suspended");
				GUI.Label(new Rect(28f, 103f, 280f, 22f), flag ? ("Skill points: " + v[1] + "  | F6: Skill Menu") : "F6: Skill Menu");
				return;
			}
			int depth = GUI.depth;
			GUI.depth = -100;
			try
			{
				float num = Mathf.Min(480, Screen.width - 24);
				float num2 = 300f;
				float num3 = ((float)Screen.width - num) / 2f;
				float num4 = ((float)Screen.height - num2) / 2f;
				GUI.Box(new Rect(num3, num4, num, num2), "REPO GROWTH / Permanent skills");
				GUI.Label(new Rect(num3 + 18f, num4 + 28f, num - 36f, 24f), flag ? ("Level " + v[8] + "     XP " + v[0] + "/" + v[6]) : "Waiting for host / suspended");
				GUI.Label(new Rect(num3 + 18f, num4 + 54f, num - 36f, 24f), flag ? ("Available skill points: " + v[1]) : "");
				if (flag)
				{
					for (int i = 0; i < 4; i++)
					{
						float num5 = num4 + 87f + (float)(i * 42);
						GUI.Label(new Rect(num3 + 18f, num5, num - 130f, 30f), labels[i] + "   +" + v[i + 2] + " / " + v[7]);
						bool enabled = GUI.enabled;
						GUI.enabled = enabled && v[1] > 0 && v[i + 2] < v[7] && Time.unscaledTime >= nextSpend;
						if (GUI.Button(new Rect(num3 + num - 100f, num5, 82f, 32f), "+1 SP"))
						{
							RequestSpend(i);
						}
						GUI.enabled = enabled;
					}
				}
				if (GUI.Button(new Rect(num3 + num - 128f, num4 + num2 - 36f, 110f, 26f), "Close (F6)"))
				{
					SetMenu(open: false);
				}
			}
			finally
			{
				GUI.depth = depth;
			}
		}

		private bool Save()
		{
			try
			{
				string text = file + ".tmp";
				string text2 = LocalId();
				if (!ValidId(text2))
				{
					return false;
				}
				Profile profile = Get(text2);
				File.WriteAllLines(text, new string[1] { text2 + "\t" + profile.XP + "\t" + string.Join("\t", profile.Permanent) + "\t" + profile.Unspent + "\t" + profile.Level + "\t" + profile.Progress });
				if (File.Exists(file))
				{
					File.Replace(text, file, file + ".bak");
				}
				else
				{
					File.Move(text, file);
				}
				return true;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
				return false;
			}
		}

		private void Load()
		{
			try
			{
				string path = (File.Exists(file) ? file : Path.Combine(Paths.ConfigPath, "den.repo.growth.progress.tsv"));
				if (!File.Exists(path))
				{
					return;
				}
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string[] array2 = array[i].Split('\t');
					if ((array2.Length != 2 && array2.Length != 6 && array2.Length != 7 && array2.Length != 9) || !ValidId(array2[0]) || !int.TryParse(array2[1], out var result) || result < 0 || result > 100000000)
					{
						continue;
					}
					Profile profile = new Profile
					{
						XP = result
					};
					bool flag = true;
					if (array2.Length >= 6)
					{
						for (int j = 0; j < 4; j++)
						{
							if (!int.TryParse(array2[j + 2], out profile.Permanent[j]) || profile.Permanent[j] < 0 || profile.Permanent[j] > 1000)
							{
								flag = false;
							}
						}
					}
					if (array2.Length >= 7)
					{
						if (!int.TryParse(array2[6], out profile.Unspent) || profile.Unspent < 0 || profile.Unspent > 2000000)
						{
							flag = false;
						}
					}
					else
					{
						profile.Unspent = Math.Max(0, result / Step - profile.Permanent.Sum());
					}
					if (array2.Length == 9)
					{
						if (!int.TryParse(array2[7], out profile.Level) || profile.Level < 1 || profile.Level > 2000002 || !int.TryParse(array2[8], out profile.Progress) || profile.Progress < 0 || profile.Progress > 1000000)
						{
							flag = false;
						}
					}
					else
					{
						profile.Level = 1 + result / Step;
						profile.Progress = result % Step;
					}
					if (flag)
					{
						profiles[array2[0]] = profile;
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
				blocked = true;
			}
		}
	}
}