Decompiled source of TootTallyLeaderboard v1.1.0

plugins/TootTallyLeaderboard.dll

Decompiled a week ago
using System;
using System.Collections;
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 System.Security;
using System.Security.Permissions;
using BaboonAPI.Hooks.Initializer;
using BaboonAPI.Hooks.Tracks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TMPro;
using TootTallyAccounts;
using TootTallyCore;
using TootTallyCore.APIServices;
using TootTallyCore.Graphics;
using TootTallyCore.Graphics.Animations;
using TootTallyCore.Utils.Assets;
using TootTallyCore.Utils.Helpers;
using TootTallyCore.Utils.TootTallyGlobals;
using TootTallyCore.Utils.TootTallyModules;
using TootTallyCore.Utils.TootTallyNotifs;
using TootTallyGameModifiers;
using TootTallyLeaderboard.Compatibility;
using TootTallyLeaderboard.Replays;
using TootTallySettings;
using TrombLoader;
using TrombLoader.CustomTracks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Localization.Components;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("TootTallyLeaderboard")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("TootTally Leaderboard and Replay module")]
[assembly: AssemblyFileVersion("1.0.11.0")]
[assembly: AssemblyInformationalVersion("1.0.11")]
[assembly: AssemblyProduct("TootTallyLeaderboard")]
[assembly: AssemblyTitle("TootTallyLeaderboard")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.11.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 TootTallyLeaderboard
{
	public static class BetterScrollSpeedSliderPatcher
	{
		private const string CONFIG_NAME = "BetterScrollSpeed.cfg";

		private const string CONFIG_FIELD = "SliderValues";

		private const uint DEFAULT_MAX = 250u;

		private const uint DEFAULT_MIN = 5u;

		private const float DEFAULT_VALUE = 100f;

		public static Options options;

		public static void PatchScrollSpeedSlider()
		{
			//IL_0030: 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_0060: 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_00af: 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_0186: Unknown result type (might be due to invalid IL or missing references)
			SetSliderOption();
			Text component = GameObject.Find("MainCanvas/FullScreenPanel/ScrollSpeed-lbl").GetComponent<Text>();
			Slider component2 = GameObject.Find("MainCanvas/FullScreenPanel/Slider").GetComponent<Slider>();
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)component2).navigation = navigation;
			((Graphic)((Component)component2.fillRect).gameObject.GetComponent<Image>()).color = Theme.colors.scrollSpeedSlider.fill;
			((Graphic)((Component)((Component)component2).transform.Find("Background")).GetComponent<Image>()).color = Theme.colors.scrollSpeedSlider.background;
			((Graphic)((Component)component2.handleRect).gameObject.GetComponent<Image>()).color = Theme.colors.scrollSpeedSlider.handle;
			component2.minValue = (float)options.Min.Value / 100f;
			component2.maxValue = (float)options.Max.Value / 100f;
			component2.value = options.LastValue.Value / 100f;
			Text scrollSpeedSliderText = Object.Instantiate<Text>(component, (Transform)(object)component2.handleRect);
			((Component)scrollSpeedSliderText).GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
			scrollSpeedSliderText.alignment = (TextAnchor)4;
			scrollSpeedSliderText.fontSize = 12;
			scrollSpeedSliderText.text = ((int)(GlobalVariables.gamescrollspeed * 100f)).ToString();
			((Graphic)scrollSpeedSliderText).color = Theme.colors.scrollSpeedSlider.text;
			scrollSpeedSliderText.text = SliderValueToText(component2.value);
			((UnityEvent<float>)(object)component2.onValueChanged).AddListener((UnityAction<float>)delegate(float _value)
			{
				options.LastValue.Value = _value * 100f;
				scrollSpeedSliderText.text = SliderValueToText(_value);
			});
			GameObject.Find("MainCanvas/FullScreenPanel/ScrollSpeed-lbl").gameObject.SetActive(false);
		}

		public static void SetSliderOption()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			if (options == null)
			{
				string text = Path.Combine(Paths.BepInExRootPath, "config/");
				ConfigFile val = new ConfigFile(text + "BetterScrollSpeed.cfg", true);
				options = new Options
				{
					Max = val.Bind<uint>("SliderValues", "Max", 250u, (ConfigDescription)null),
					Min = val.Bind<uint>("SliderValues", "Min", 5u, (ConfigDescription)null),
					LastValue = val.Bind<float>("SliderValues", "LastValue", 100f, (ConfigDescription)null)
				};
				if (options.Min.Value >= options.Max.Value)
				{
					Plugin.LogError("Slider MAX has to be greater than Slider MIN");
				}
				else if (options.Min.Value <= 4)
				{
					Plugin.LogError("Slider MIN has to be greater or equal to 5");
				}
				else if (options.Max.Value >= 1000)
				{
					Plugin.LogError("Buddy. What are you trying to do?? You're never gonna play with 1k+ scrollspeed...");
				}
				if (options.Max.Value >= options.Min.Value || options.Min.Value <= 4 || options.Max.Value >= 1000)
				{
					options.Min.Value = 5u;
					options.Max.Value = 250u;
				}
				if (options.LastValue.Value < (float)options.Min.Value || options.LastValue.Value > (float)options.Max.Value)
				{
					options.LastValue.Value = 100f;
				}
				GlobalVariables.gamescrollspeed = options.LastValue.Value / 100f;
			}
		}

		public static string SliderValueToText(float value)
		{
			if (value >= 1f)
			{
				return Mathf.FloorToInt(value * 100f).ToString();
			}
			return Mathf.CeilToInt(value * 100f).ToString();
		}
	}
	public class Options
	{
		public ConfigEntry<uint> Max { get; set; }

		public ConfigEntry<uint> Min { get; set; }

		public ConfigEntry<float> LastValue { get; set; }
	}
	public class GlobalLeaderboard
	{
		public enum LeaderboardState
		{
			None,
			ErrorNoSongHashFound,
			ErrorNoLeaderboardFound,
			ErrorUnexpected,
			ReadyToRefresh,
			SongDataLoaded,
			SongDataMissing
		}

		private const string ERROR_NO_LEADERBOARD_FOUND_TEXT = "Could not find a leaderboard for this track.\n <size=15>Be the first one to set a score on the track!</size>";

		private const string ERROR_NO_SONGHASH_FOUND_TEXT = "This chart is not uploaded to TootTally...\n <size=15>Please upload the chart to TootTally.com\n or use TootBender on discord to create the leaderboard.</size>";

		private static Dictionary<string, Color> gradeToColorDict = new Dictionary<string, Color>
		{
			{
				"SSS",
				Color.yellow
			},
			{
				"SS",
				Color.yellow
			},
			{
				"S",
				Color.yellow
			},
			{
				"A",
				Color.green
			},
			{
				"B",
				new Color(0f, 0.4f, 1f)
			},
			{
				"C",
				Color.magenta
			},
			{
				"D",
				Color.red
			},
			{
				"F",
				Color.grey
			}
		};

		private static string[] tabsImageNames = new string[3] { "profile64.png", "global64.png", "local64.png" };

		private static float[] _starSizeDeltaPositions = new float[11]
		{
			0f, 20f, 58f, 96f, 134f, 172f, 210f, 248f, 285f, 324f,
			361f
		};

		private static GameObject _fullScreenPanelCanvas;

		private List<IEnumerator<UnityWebRequestAsyncOperation>> _currentLeaderboardCoroutines;

		private LevelSelectController _levelSelectControllerInstance;

		private List<ScoreDataFromDB> _scoreDataList;

		private GameObject _leaderboard;

		private GameObject _globalLeaderboard;

		private GameObject _scoreboard;

		private GameObject _errorsHolder;

		private GameObject _tabs;

		private GameObject _profilePopup;

		private GameObject _ratedIcon;

		private LoadingIcon _loadingSwirly;

		private LoadingIcon _profilePopupLoadingSwirly;

		private Text _errorText;

		private TMP_Text _diffRating;

		private Vector2 _starRatingMaskSizeTarget;

		private RectTransform _diffRatingMaskRectangle;

		private List<LeaderboardRowEntry> _scoreGameObjectList;

		private SongDataFromDB _songData;

		private Slider _slider;

		private Slider _gameSpeedSlider;

		private ScrollableSliderHandler _scrollableSliderHandler;

		private GameObject _sliderHandle;

		private Dictionary<int, float> _speedToDiffDict;

		private int _currentSelectedSongHash;

		private int _localScoreId;

		public bool IsMouseOver;

		private SecondDegreeDynamicsAnimation _starMaskAnimation;

		public bool HasLeaderboard => (Object)(object)_leaderboard != (Object)null;

		public void Initialize(LevelSelectController __instance)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: 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_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0435: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ff: Expected O, but got Unknown
			//IL_0515: Unknown result type (might be due to invalid IL or missing references)
			//IL_051a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0524: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			_fullScreenPanelCanvas = GameObject.Find("MainCanvas/FullScreenPanel");
			_levelSelectControllerInstance = __instance;
			_currentLeaderboardCoroutines = new List<IEnumerator<UnityWebRequestAsyncOperation>>();
			_scoreGameObjectList = new List<LeaderboardRowEntry>();
			ClearBaseLeaderboard();
			CustomizeGameMenuUI(__instance);
			_leaderboard.transform.SetAsLastSibling();
			_globalLeaderboard = LeaderboardFactory.CreateSteamLeaderboardFromPrefab(_leaderboard.transform, "GlobalLeaderboard");
			_globalLeaderboard.SetActive(true);
			EventTrigger val = _globalLeaderboard.AddComponent<EventTrigger>();
			Entry val2 = new Entry();
			val2.eventID = (EventTriggerType)0;
			((UnityEvent<BaseEventData>)(object)val2.callback).AddListener((UnityAction<BaseEventData>)delegate
			{
				OnPointerEnter();
			});
			val.triggers.Add(val2);
			Entry val3 = new Entry();
			val3.eventID = (EventTriggerType)1;
			((UnityEvent<BaseEventData>)(object)val3.callback).AddListener((UnityAction<BaseEventData>)delegate
			{
				OnPointerExit();
			});
			val.triggers.Add(val3);
			GameObject gameObject = ((Component)_globalLeaderboard.transform.Find("PanelBody")).gameObject;
			gameObject.SetActive(true);
			_scoreboard = ((Component)gameObject.transform.Find("scoreboard")).gameObject;
			_scoreboard.SetActive(true);
			_errorsHolder = ((Component)gameObject.transform.Find("errors")).gameObject;
			_errorText = ((Component)_errorsHolder.transform.Find("error_noleaderboard")).GetComponent<Text>();
			((Component)_errorText).gameObject.SetActive(true);
			_tabs = ((Component)gameObject.transform.Find("tabs")).gameObject;
			SetTabsImages();
			_loadingSwirly = GameObjectFactory.CreateLoadingIcon(gameObject.transform, new Vector2(-20f, 0f), new Vector2(128f, 128f), AssetManager.GetSprite("icon.png"), true, "LeaderboardLoadingSwirly");
			_loadingSwirly.StartRecursiveAnimation();
			_loadingSwirly.Show();
			_slider = ((Component)gameObject.transform.Find("LeaderboardVerticalSlider")).gameObject.GetComponent<Slider>();
			((Graphic)((Component)((Component)_slider).transform.Find("Fill Area/Fill")).GetComponent<Image>()).color = Theme.colors.leaderboard.slider.fill;
			((Graphic)((Component)((Component)_slider).transform.Find("Background")).GetComponent<Image>()).color = Theme.colors.leaderboard.slider.background;
			_scrollableSliderHandler = ((Component)_slider).gameObject.AddComponent<ScrollableSliderHandler>();
			_sliderHandle = ((Component)((Component)_slider).transform.Find("Handle")).gameObject;
			((Graphic)_sliderHandle.GetComponent<Image>()).color = Theme.colors.leaderboard.slider.handle;
			SetOnSliderValueChangeEvent();
			GameObject gameObject2 = ((Component)_fullScreenPanelCanvas.transform.Find("diff bar")).gameObject;
			Object.DestroyImmediate((Object)(object)((Component)_fullScreenPanelCanvas.transform.Find("difficulty text")).gameObject);
			TMP_Text val4 = GameObjectFactory.CreateSingleText(gameObject2.transform, "Difficulty Text", "Difficulty:", (TextFont)1);
			val4.alignment = (TextAlignmentOptions)513;
			val4.margin = Vector4.op_Implicit(new Vector2(80f, 4f));
			val4.fontSize = 16f;
			GameObject gameObject3 = ((Component)_fullScreenPanelCanvas.transform.Find("difficulty stars")).gameObject;
			_diffRatingMaskRectangle = gameObject3.GetComponent<RectTransform>();
			_diffRatingMaskRectangle.anchoredPosition = new Vector2(-284f, -48f);
			_diffRatingMaskRectangle.sizeDelta = new Vector2(0f, 30f);
			Mask val5 = gameObject3.AddComponent<Mask>();
			val5.showMaskGraphic = false;
			gameObject3.AddComponent<Image>();
			RectTransform component = gameObject2.GetComponent<RectTransform>();
			component.sizeDelta += new Vector2(41.5f, 0f);
			_diffRating = GameObjectFactory.CreateSingleText(gameObject2.transform, "diffRating", "", (TextFont)1);
			_diffRating.outlineColor = Color32.op_Implicit(Theme.colors.leaderboard.textOutline);
			_diffRating.outlineWidth = 0.2f;
			_diffRating.fontSize = 20f;
			_diffRating.alignment = (TextAlignmentOptions)4100;
			_diffRating.rectTransform.sizeDelta = new Vector2(450f, 30f);
			RectTransform rectTransform = _diffRating.rectTransform;
			RectTransform rectTransform2 = _diffRating.rectTransform;
			Vector2 val6 = default(Vector2);
			((Vector2)(ref val6))..ctor(0f, 0.5f);
			rectTransform2.anchorMax = val6;
			rectTransform.anchorMin = val6;
			_diffRating.rectTransform.offsetMin = Vector2.zero;
			_starMaskAnimation = new SecondDegreeDynamicsAnimation(1.23f, 1f, 1.2f);
			_ratedIcon = GameObjectFactory.CreateImageHolder(_globalLeaderboard.transform, new Vector2(350f, 180f), Vector2.one * 42f, AssetManager.GetSprite("rated64.png"), "RatedChartIcon");
			BubblePopupHandler val7 = _ratedIcon.AddComponent<BubblePopupHandler>();
			val7.Initialize(GameObjectFactory.CreateBubble(new Vector2(300f, 40f), "RatedIconBubble", "This chart is rated.", 6, true, 12), true);
			_levelSelectControllerInstance.sortdrop.transform.SetAsLastSibling();
		}

		public void OnPointerEnter()
		{
			((Behaviour)_scrollableSliderHandler).enabled = (IsMouseOver = true);
		}

		public void OnPointerExit()
		{
			((Behaviour)_scrollableSliderHandler).enabled = (IsMouseOver = false);
		}

		public void ClearBaseLeaderboard()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			_leaderboard = ((Component)_fullScreenPanelCanvas.transform.Find("Leaderboard")).gameObject;
			foreach (Transform item in _leaderboard.transform)
			{
				Transform val = item;
				((Component)val).gameObject.SetActive(false);
			}
			DestroyFromParent(_leaderboard, ".......");
			DestroyFromParent(_leaderboard, "\"HIGH SCORES\"");
			for (int i = 1; i <= 5; i++)
			{
				((Component)_leaderboard.transform.Find(i.ToString())).gameObject.SetActive(false);
			}
		}

		public void CustomizeGameMenuUI(LevelSelectController __instance)
		{
			//IL_0066: 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)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Expected O, but got Unknown
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_0420: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_044f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c5: Expected O, but got Unknown
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_051d: Expected O, but got Unknown
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_0585: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				((Component)_fullScreenPanelCanvas.transform.Find("Dial")).gameObject.SetActive(false);
				((Component)_fullScreenPanelCanvas.transform.Find("capsules")).GetComponent<RectTransform>().anchoredPosition = new Vector2(-275f, 32f);
				((Component)_fullScreenPanelCanvas.transform.Find("btn_RANDOM")).GetComponent<RectTransform>().anchoredPosition = new Vector2(-123f, -7f);
				((Component)_fullScreenPanelCanvas.transform.Find("btn_TURBO")).GetComponent<RectTransform>().anchoredPosition = new Vector2(-110f, 65f);
				BetterScrollSpeedSliderPatcher.PatchScrollSpeedSlider();
				((Component)_fullScreenPanelCanvas.transform.Find("Slider")).GetComponent<RectTransform>().anchoredPosition = new Vector2(-115f, 23f);
				((Component)_fullScreenPanelCanvas.transform.Find("txt_scrollspeed")).GetComponent<RectTransform>().anchoredPosition = new Vector2(-112f, 36f);
				((Component)_fullScreenPanelCanvas.transform.Find("btn_TURBO")).gameObject.SetActive(false);
				((Component)_fullScreenPanelCanvas.transform.Find("btn_PRACTICE")).gameObject.SetActive(false);
				_gameSpeedSlider = Object.Instantiate<Slider>(((Component)_fullScreenPanelCanvas.transform.Find("Slider")).GetComponent<Slider>(), _fullScreenPanelCanvas.transform);
				((Component)_gameSpeedSlider).gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(-110f, 65f);
				_gameSpeedSlider.wholeNumbers = true;
				_gameSpeedSlider.minValue = 0f;
				_gameSpeedSlider.maxValue = 30f;
				_gameSpeedSlider.value = (ReplaySystemManager.gameSpeedMultiplier - 0.5f) / 0.05f;
				GameObject val = Object.Instantiate<GameObject>(((Component)_fullScreenPanelCanvas.transform.Find("txt_scrollspeed")).gameObject, _fullScreenPanelCanvas.transform);
				((Object)val).name = "GameSpeedShad";
				val.GetComponent<Text>().text = "Game Speed";
				val.GetComponent<RectTransform>().anchoredPosition = new Vector2(-108f, 78f);
				GameObject gameObject = ((Component)val.transform.Find("txt_scrollspeed-top")).gameObject;
				((Object)gameObject).name = "GameSpeed";
				gameObject.GetComponent<Text>().text = "Game Speed";
				Text scrollSpeedSliderText = ((Component)((Component)_gameSpeedSlider).transform.Find("Handle Slide Area/Handle/ScrollSpeed-lbl(Clone)")).GetComponent<Text>();
				scrollSpeedSliderText.text = (_gameSpeedSlider.value * 0.05f + 0.5f).ToString("0.00");
				_gameSpeedSlider.onValueChanged = new SliderEvent();
				((UnityEvent<float>)(object)_gameSpeedSlider.onValueChanged).AddListener((UnityAction<float>)delegate(float _value)
				{
					_gameSpeedSlider.value = Mathf.Round(_value * 20f) / 20f;
					TootTallyGlobalVariables.gameSpeedMultiplier = _gameSpeedSlider.value * 0.05f + 0.5f;
					scrollSpeedSliderText.text = ReplaySystemManager.gameSpeedMultiplier.ToString("0.00");
					UpdateStarRating(__instance);
				});
				GameObject val2 = Object.Instantiate<GameObject>(_levelSelectControllerInstance.songtitlebar);
				((Object)val2).name = "titlebarPrefab";
				((Transform)val2.GetComponent<RectTransform>()).eulerAngles = Vector3.zero;
				((Transform)val2.GetComponent<RectTransform>()).localScale = Vector3.one;
				((Graphic)val2.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.001f);
				GameObject val3 = LeaderboardFactory.CreateDefaultPanel(_fullScreenPanelCanvas.transform, new Vector2(381f, -207f), new Vector2(72f, 72f), "ProfilePopupHitbox");
				GameObjectFactory.CreateSingleText(val3.transform, "ProfilePopupHitboxText", "P", (TextFont)1);
				if (TootTallyUser.userInfo.id == 0)
				{
					return;
				}
				_profilePopup = LeaderboardFactory.CreateDefaultPanel(_fullScreenPanelCanvas.transform, new Vector2(525f, -300f), new Vector2(450f, 270f), "TootTallyScorePanel");
				_profilePopupLoadingSwirly = GameObjectFactory.CreateLoadingIcon(_profilePopup.transform, Vector2.zero, new Vector2(96f, 96f), AssetManager.GetSprite("icon.png"), true, "ProfilePopupLoadingSwirly");
				_profilePopupLoadingSwirly.Show();
				_profilePopupLoadingSwirly.StartRecursiveAnimation();
				GameObject scoresbody = ((Component)_profilePopup.transform.Find("scoresbody")).gameObject;
				HorizontalLayoutGroup val4 = scoresbody.AddComponent<HorizontalLayoutGroup>();
				((LayoutGroup)val4).padding = new RectOffset(2, 2, 2, 2);
				((LayoutGroup)val4).childAlignment = (TextAnchor)4;
				bool childForceExpandHeight = (((HorizontalOrVerticalLayoutGroup)val4).childForceExpandWidth = true);
				((HorizontalOrVerticalLayoutGroup)val4).childForceExpandHeight = childForceExpandHeight;
				GameObject mainPanel = Object.Instantiate<GameObject>(val2, scoresbody.transform);
				VerticalLayoutGroup val5 = mainPanel.AddComponent<VerticalLayoutGroup>();
				((LayoutGroup)val5).padding = new RectOffset(2, 2, 2, 2);
				((LayoutGroup)val5).childAlignment = (TextAnchor)4;
				childForceExpandHeight = (((HorizontalOrVerticalLayoutGroup)val5).childForceExpandWidth = true);
				((HorizontalOrVerticalLayoutGroup)val5).childForceExpandHeight = childForceExpandHeight;
				((MonoBehaviour)Plugin.Instance).StartCoroutine((IEnumerator)TootTallyAPIService.GetUserFromID(TootTallyUser.userInfo.id, (Action<User>)delegate(User user)
				{
					AssetManager.GetProfilePictureByID(user.id, (Action<Sprite>)delegate(Sprite sprite)
					{
						//IL_000c: Unknown result type (might be due to invalid IL or missing references)
						//IL_0012: 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_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)
						//IL_002d: Unknown result type (might be due to invalid IL or missing references)
						Transform transform = scoresbody.transform;
						Vector2 zero = Vector2.zero;
						Rect rect = sprite.rect;
						float width = ((Rect)(ref rect)).width;
						rect = sprite.rect;
						CustomButton val8 = GameObjectFactory.CreateCustomButton(transform, zero, new Vector2(width, ((Rect)(ref rect)).height), sprite, false, "Pfp", (Action)OpenUserProfile);
						((Component)val8).transform.SetSiblingIndex(0);
					});
					if (Plugin.Instance.option.SessionStartTT.Value == 0f || Plugin.Instance.ShouldUpdateSession)
					{
						Plugin.Instance.ShouldUpdateSession = false;
						Plugin.Instance.option.SessionDate.Value = DateTime.Now.AddDays(1.0).ToString();
						Plugin.Instance.option.SessionStartTT.Value = user.tt;
					}
					float num = user.tt - Plugin.Instance.option.SessionStartTT.Value;
					TMP_Text val6 = GameObjectFactory.CreateSingleText(mainPanel.transform, "NameLabel", $"{user.username} #{user.rank}", (TextFont)0);
					TMP_Text val7 = GameObjectFactory.CreateSingleText(mainPanel.transform, "TTLabel", string.Format("{0}tt (<color=\"green\">{1}{2:0.00}tt</color>)", user.tt, (num > 0f) ? "+" : "", num), (TextFont)0);
					_profilePopupLoadingSwirly.Dispose();
				}));
				new SlideTooltip(val3, _profilePopup, new Vector2(525f, -300f), new Vector2(282f, -155f));
			}
			catch (Exception ex)
			{
				Plugin.LogError(ex.Message);
			}
		}

		private void UpdateStarRating(LevelSelectController __instance)
		{
			//IL_0204: 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)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: 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_0065: 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_0081: 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)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: 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)
			for (int i = 0; i < 10 && (Plugin.Instance.option.ShowLeaderboard.Value || i < __instance.alltrackslist[__instance.songindex].difficulty); i++)
			{
				if (!Theme.isDefault)
				{
					((Graphic)__instance.diffstars[i]).color = Color.Lerp(Theme.colors.diffStar.gradientStart, Theme.colors.diffStar.gradientEnd, (float)i / 9f);
				}
				else
				{
					((Graphic)__instance.diffstars[i]).color = Color.white;
				}
				if (Plugin.Instance.option.ShowLeaderboard.Value)
				{
					((Component)__instance.diffstars[i]).gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2((float)(i * 19), 0f);
					((MaskableGraphic)__instance.diffstars[i]).maskable = true;
				}
			}
			if (_songData != null && _speedToDiffDict != null)
			{
				float num = (_songData.is_rated ? _speedToDiffDict[(int)_gameSpeedSlider.value] : _speedToDiffDict[1]);
				_diffRating.text = num.ToString("0.0");
				int num2 = (int)Mathf.Clamp(num + 1f, 1f, 10f);
				int num3 = (int)Mathf.Clamp(num, 0f, 9f);
				_starMaskAnimation.SetStartVector(Vector2.op_Implicit(_diffRatingMaskRectangle.sizeDelta));
				_starRatingMaskSizeTarget = new Vector2(EasingHelper.Lerp(_starSizeDeltaPositions[num2], _starSizeDeltaPositions[num3], (float)num2 - num), 30f);
			}
			else
			{
				_diffRating.text = "NA";
				_starMaskAnimation.SetStartVector(Vector2.op_Implicit(_diffRatingMaskRectangle.sizeDelta));
				_starRatingMaskSizeTarget = new Vector2(_starSizeDeltaPositions[0], 30f);
			}
		}

		public void UpdateLeaderboard(LevelSelectController __instance, List<SingleTrackData> ___alltrackslist, Action<LeaderboardState> callback)
		{
			_globalLeaderboard.SetActive(true);
			_ratedIcon.SetActive(false);
			_scrollableSliderHandler.ResetAcceleration();
			string trackref = ___alltrackslist[_levelSelectControllerInstance.songindex].trackref;
			TromboneTrack val = TrackLookup.lookup(trackref);
			string songHash = SongDataHelper.GetSongHash(val);
			if (_currentLeaderboardCoroutines.Count != 0)
			{
				CancelAndClearAllCoroutineInList();
			}
			_currentLeaderboardCoroutines.Add(TootTallyAPIService.GetHashInDB(songHash, val is CustomTrack, (Action<int>)delegate(int songHashInDB)
			{
				//IL_005c: 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)
				//IL_007e: 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)
				if (songHashInDB == 0)
				{
					_errorText.text = "This chart is not uploaded to TootTally...\n <size=15>Please upload the chart to TootTally.com\n or use TootBender on discord to create the leaderboard.</size>";
					callback(LeaderboardState.ErrorNoSongHashFound);
					_diffRating.text = "NA";
					_starMaskAnimation.SetStartVector(Vector2.op_Implicit(_diffRatingMaskRectangle.sizeDelta));
					_starRatingMaskSizeTarget = new Vector2(_starSizeDeltaPositions[0], 30f);
				}
				else
				{
					_currentSelectedSongHash = songHashInDB;
					_songData = null;
					_scoreDataList = null;
					_speedToDiffDict = null;
					_currentLeaderboardCoroutines.Add(TootTallyAPIService.GetSongDataFromDB(songHashInDB, (Action<SongDataFromDB>)delegate(SongDataFromDB songData)
					{
						if (songData != null)
						{
							OnSongInfoReceived(songData);
						}
						else
						{
							_speedToDiffDict = null;
						}
						UpdateStarRating(__instance);
						if (_scoreDataList != null)
						{
							CancelAndClearAllCoroutineInList();
						}
					}));
					((MonoBehaviour)Plugin.Instance).StartCoroutine((IEnumerator)_currentLeaderboardCoroutines.Last());
					_currentLeaderboardCoroutines.Add(TootTallyAPIService.GetLeaderboardScoresFromDB(songHashInDB, (Action<List<ScoreDataFromDB>>)delegate(List<ScoreDataFromDB> scoreDataList)
					{
						if (scoreDataList != null)
						{
							_scoreDataList = scoreDataList;
							_scrollableSliderHandler.accelerationMult = 8f / (float)_scoreDataList.Count;
							callback(LeaderboardState.ReadyToRefresh);
						}
						else
						{
							_errorText.text = "Could not find a leaderboard for this track.\n <size=15>Be the first one to set a score on the track!</size>";
							callback(LeaderboardState.ErrorNoLeaderboardFound);
						}
						if (_songData != null)
						{
							CancelAndClearAllCoroutineInList();
						}
					}));
					((MonoBehaviour)Plugin.Instance).StartCoroutine((IEnumerator)_currentLeaderboardCoroutines.Last());
				}
			}));
			((MonoBehaviour)Plugin.Instance).StartCoroutine((IEnumerator)_currentLeaderboardCoroutines.Last());
		}

		public void OnSongInfoReceived(SongDataFromDB songData)
		{
			_songData = songData;
			_speedToDiffDict = new Dictionary<int, float>();
			if (songData.is_rated)
			{
				_ratedIcon.SetActive(true);
				for (int i = 0; i <= 29; i++)
				{
					float num = (int)((float)i / 5f);
					float num2 = num * 0.25f + 0.5f;
					float num3 = (num + 1f) * 0.25f + 0.5f;
					float num4 = (float)i * 0.05f + 0.5f;
					float num5 = (num4 - num2) / (num3 - num2);
					float value = EasingHelper.Lerp(_songData.speed_diffs[(int)num], _songData.speed_diffs[(int)num + 1], num5);
					_speedToDiffDict.Add(i, value);
				}
				_speedToDiffDict.Add(30, _songData.speed_diffs.Last());
			}
			else
			{
				_speedToDiffDict.Add(1, _songData.difficulty);
			}
		}

		public void ShowLoadingSwirly()
		{
			_loadingSwirly.Show();
		}

		public void HideLoadingSwirly()
		{
			_loadingSwirly.Hide();
		}

		public void RefreshLeaderboard()
		{
			//IL_004d: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			int num = 1;
			_localScoreId = -1;
			foreach (ScoreDataFromDB scoreData in _scoreDataList)
			{
				LeaderboardRowEntry leaderboardRowEntry = LeaderboardFactory.CreateLeaderboardRowEntryFromScore(_scoreboard.transform, "RowEntry" + scoreData.player, scoreData, num, gradeToColorDict[scoreData.grade], _levelSelectControllerInstance);
				_scoreGameObjectList.Add(leaderboardRowEntry);
				if (scoreData.player == TootTallyUser.userInfo.username)
				{
					((Graphic)leaderboardRowEntry.imageStrip).color = Theme.colors.leaderboard.yourRowEntry;
					((Component)leaderboardRowEntry.imageStrip).gameObject.SetActive(true);
					_localScoreId = num - 1;
				}
				num++;
			}
			if (_scoreGameObjectList.Count > 8)
			{
				_slider.value = 0f;
				_sliderHandle.GetComponent<RectTransform>().anchoredPosition = new Vector2(-12f, 522f);
				ShowSlider();
			}
			else
			{
				HideSlider();
			}
		}

		public void SetOnSliderValueChangeEvent()
		{
			((UnityEvent<float>)(object)_slider.onValueChanged).AddListener((UnityAction<float>)delegate(float _value)
			{
				//IL_004e: 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_0085: 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_0093: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: 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_011b: Unknown result type (might be due to invalid IL or missing references)
				//IL_016c: Unknown result type (might be due to invalid IL or missing references)
				_slider.value = Mathf.Clamp(_value, 0f, 1f);
				foreach (LeaderboardRowEntry scoreGameObject in _scoreGameObjectList)
				{
					RectTransform component = _sliderHandle.GetComponent<RectTransform>();
					float num = (0f - ((Component)_slider).GetComponent<RectTransform>().sizeDelta.x) / 2f;
					float num2 = ((Component)_slider).GetComponent<RectTransform>().sizeDelta.y / 1.38f;
					Rect rect = _slider.fillRect.rect;
					component.anchoredPosition = new Vector2(num, num2 - ((Rect)(ref rect)).height);
					RectTransform component2 = scoreGameObject.singleScore.GetComponent<RectTransform>();
					component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, (float)((scoreGameObject.rowId - 1) * -35) + _slider.value * 35f * (float)(_scoreGameObjectList.Count - 8) - 17f);
					if (component2.anchoredPosition.y >= -15f)
					{
						((Component)scoreGameObject).GetComponent<CanvasGroup>().alpha = Math.Max(1f - (component2.anchoredPosition.y + 15f) / 35f, 0f);
					}
					else if (component2.anchoredPosition.y - 35f <= 295f)
					{
						((Component)scoreGameObject).GetComponent<CanvasGroup>().alpha = Math.Max((component2.anchoredPosition.y + 280f + 15f) / 35f, 0f);
					}
					else
					{
						((Component)scoreGameObject).GetComponent<CanvasGroup>().alpha = 1f;
					}
				}
			});
		}

		public void UpdateStarRatingAnimation()
		{
			//IL_000e: 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_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)
			_diffRatingMaskRectangle.sizeDelta = Vector2.op_Implicit(_starMaskAnimation.GetNewVector(Vector2.op_Implicit(_starRatingMaskSizeTarget), Time.deltaTime));
		}

		public bool IsScrollingEnabled()
		{
			return ((Behaviour)_scrollableSliderHandler).enabled;
		}

		public void ClearLeaderboard()
		{
			_scoreGameObjectList.ForEach(delegate(LeaderboardRowEntry score)
			{
				Object.DestroyImmediate((Object)(object)score.singleScore);
			});
			_scoreGameObjectList.Clear();
		}

		public void CancelAndClearAllCoroutineInList()
		{
			_currentLeaderboardCoroutines.ForEach(delegate(IEnumerator<UnityWebRequestAsyncOperation> routine)
			{
				((MonoBehaviour)Plugin.Instance).StopCoroutine((IEnumerator)routine);
			});
			_currentLeaderboardCoroutines.Clear();
		}

		public void ShowSlider()
		{
			((Component)_slider).gameObject.SetActive(true);
		}

		public void HideSlider()
		{
			((Component)_slider).gameObject.SetActive(false);
		}

		public void ShowErrorText()
		{
			_errorsHolder.SetActive(true);
		}

		public void HideErrorText()
		{
			_errorsHolder.SetActive(false);
		}

		public void OpenUserProfile()
		{
			Application.OpenURL("https://toottally.com/profile/" + TootTallyUser.userInfo.id);
		}

		public void OpenLoginPage()
		{
			Application.OpenURL("https://toottally.com/login");
		}

		public void OpenSongLeaderboard()
		{
			Application.OpenURL("https://toottally.com/song/" + _currentSelectedSongHash);
		}

		public void OpenSongFolder()
		{
			TromboneTrack val = TrackLookup.lookup(_songData.track_ref);
			CustomTrack val2 = (CustomTrack)(object)((val is CustomTrack) ? val : null);
			string text = ((val2 == null) ? (Application.streamingAssetsPath + "/trackassets/" + val.trackref) : val2.folderPath);
			if (Directory.Exists(text))
			{
				Process.Start(text);
			}
			else
			{
				TootTallyNotifManager.DisplayNotif("Folder couldn't be found.", 6f);
			}
		}

		public void ScrollToLocalScore()
		{
			if (_localScoreId == -1)
			{
				TootTallyNotifManager.DisplayNotif("You don't have a score on that leaderboard yet", 6f);
			}
			else if (_scoreGameObjectList.Count > 8)
			{
				_slider.value = (float)_localScoreId / ((float)_scoreGameObjectList.Count - 8f);
				((UnityEvent<float>)(object)_slider.onValueChanged).Invoke(_slider.value);
			}
		}

		private void SetTabsImages()
		{
			//IL_0041: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: 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_00f7: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < 3; i++)
			{
				GameObject val = _globalLeaderboard.GetComponent<LeaderboardManager>().tabs[i];
				Button componentInChildren = val.GetComponentInChildren<Button>();
				((Selectable)componentInChildren).image.sprite = AssetManager.GetSprite(tabsImageNames[i]);
				((Graphic)((Selectable)componentInChildren).image).color = Color.white;
				ColorBlock colors = default(ColorBlock);
				((ColorBlock)(ref colors)).normalColor = ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).normalColor;
				((ColorBlock)(ref colors)).pressedColor = ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).pressedColor;
				((ColorBlock)(ref colors)).highlightedColor = ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).highlightedColor;
				((ColorBlock)(ref colors)).fadeDuration = 0.1f;
				((ColorBlock)(ref colors)).colorMultiplier = 1f;
				((Selectable)componentInChildren).colors = colors;
			}
			GameObject val2 = GameObjectFactory.CreateClickableImageHolder(_tabs.transform, Vector2.zero, Vector2.one * 40f, AssetManager.GetSprite("folder64.png"), "Open Folder Button", ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).normalColor, ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).highlightedColor, (Action)OpenSongFolder);
			((Graphic)val2.GetComponent<Image>()).color = ((ColorBlock)(ref Theme.colors.leaderboard.tabs)).normalColor;
			_tabs.SetActive(true);
		}

		private void DestroyFromParent(GameObject parent, string objectName)
		{
			Object.DestroyImmediate((Object)(object)((Component)parent.transform.Find(objectName)).gameObject);
		}
	}
	public static class GlobalLeaderboardManager
	{
		private static bool _hasLeaderboardFinishedLoading;

		private static GlobalLeaderboard globalLeaderboard;

		[HarmonyPatch(typeof(LevelSelectController), "Start")]
		[HarmonyPostfix]
		public static void OnLevelSelectControllerStartPostfix(List<SingleTrackData> ___alltrackslist, LevelSelectController __instance)
		{
			_hasLeaderboardFinishedLoading = false;
			if (!Plugin.Instance.option.ShowLeaderboard.Value)
			{
				BetterScrollSpeedSliderPatcher.PatchScrollSpeedSlider();
				return;
			}
			globalLeaderboard = new GlobalLeaderboard();
			globalLeaderboard.Initialize(__instance);
			globalLeaderboard.UpdateLeaderboard(__instance, ___alltrackslist, OnUpdateLeaderboardCallback);
		}

		[HarmonyPatch(typeof(LevelSelectController), "populateScores")]
		[HarmonyPrefix]
		private static bool DontPopulateBaseGameLeaderboard()
		{
			return !Plugin.Instance.option.ShowLeaderboard.Value;
		}

		[HarmonyPatch(typeof(LevelSelectController), "Update")]
		[HarmonyPostfix]
		private static void UpdateLoadingSwirlyAnimationOnLevelSelectControllerUpdatePostfix()
		{
			if (globalLeaderboard != null && _hasLeaderboardFinishedLoading)
			{
				globalLeaderboard.UpdateStarRatingAnimation();
			}
		}

		[HarmonyPatch(typeof(LevelSelectController), "sortTracks")]
		[HarmonyPostfix]
		private static void OnTrackSortReloadLeaderboard(List<SingleTrackData> ___alltrackslist, LevelSelectController __instance)
		{
			if (globalLeaderboard != null && globalLeaderboard.HasLeaderboard)
			{
				UpdateLeaderboardOnAdvanceSongsPostfix(___alltrackslist, __instance);
			}
		}

		[HarmonyPatch(typeof(LevelSelectController), "clickPlay")]
		[HarmonyPostfix]
		private static void OnLevelSelectControllerClickPlayDeleteLeaderboard(LevelSelectController __instance)
		{
			if (globalLeaderboard != null)
			{
				globalLeaderboard.CancelAndClearAllCoroutineInList();
				globalLeaderboard = null;
			}
		}

		[HarmonyPatch(typeof(LevelSelectController), "clickBack")]
		[HarmonyPostfix]
		private static void OnLevelSelectControllerClickBackDeleteLeaderboard(LevelSelectController __instance)
		{
			if (globalLeaderboard != null)
			{
				globalLeaderboard.CancelAndClearAllCoroutineInList();
				globalLeaderboard = null;
			}
		}

		[HarmonyPatch(typeof(LeaderboardManager), "clickTab")]
		[HarmonyPrefix]
		private static bool OverwriteClickLeaderboardTabs(int tabindex)
		{
			if (globalLeaderboard != null && globalLeaderboard.HasLeaderboard)
			{
				switch (tabindex)
				{
				case 0:
					if (TootTallyUser.userInfo.id != 0)
					{
						globalLeaderboard.OpenUserProfile();
					}
					else
					{
						globalLeaderboard.OpenLoginPage();
					}
					break;
				case 1:
					globalLeaderboard.OpenSongLeaderboard();
					break;
				case 2:
					globalLeaderboard.ScrollToLocalScore();
					break;
				default:
					return true;
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(LevelSelectController), "clickNext")]
		[HarmonyPrefix]
		private static bool OnClickNextSkipIfScrollWheelUsed()
		{
			return ShouldScrollSongs();
		}

		[HarmonyPatch(typeof(LevelSelectController), "clickPrev")]
		[HarmonyPrefix]
		private static bool OnClickBackSkipIfScrollWheelUsed()
		{
			return ShouldScrollSongs();
		}

		private static bool ShouldScrollSongs()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return globalLeaderboard == null || !globalLeaderboard.IsMouseOver || Input.mouseScrollDelta.y == 0f;
		}

		[HarmonyPatch(typeof(LevelSelectController), "showButtonsAfterRandomizing")]
		[HarmonyPostfix]
		private static void HideTurboButtonAfterRandomizing(LevelSelectController __instance)
		{
			if (globalLeaderboard != null)
			{
				__instance.btnturbo.SetActive(false);
				__instance.btnpractice.SetActive(false);
				__instance.btn_steamleaderboard.SetActive(false);
			}
		}

		[HarmonyPatch(typeof(LevelSelectController), "doneRandomizing")]
		[HarmonyPostfix]
		private static void OnDoneRandomizingUpdateLeaderboard(List<SingleTrackData> ___alltrackslist, LevelSelectController __instance)
		{
			if (__instance.randomizing)
			{
				if (_hasLeaderboardFinishedLoading)
				{
					_hasLeaderboardFinishedLoading = false;
					globalLeaderboard?.ShowLoadingSwirly();
					globalLeaderboard?.HideSlider();
					globalLeaderboard?.HideErrorText();
					globalLeaderboard?.ClearLeaderboard();
				}
				globalLeaderboard?.UpdateLeaderboard(__instance, ___alltrackslist, OnUpdateLeaderboardCallback);
			}
		}

		[HarmonyPatch(typeof(LevelSelectController), "advanceSongs")]
		[HarmonyPostfix]
		private static void UpdateLeaderboardOnAdvanceSongsPostfix(List<SingleTrackData> ___alltrackslist, LevelSelectController __instance)
		{
			if (_hasLeaderboardFinishedLoading)
			{
				_hasLeaderboardFinishedLoading = false;
				globalLeaderboard?.ShowLoadingSwirly();
				globalLeaderboard?.HideSlider();
				globalLeaderboard?.HideErrorText();
				globalLeaderboard?.ClearLeaderboard();
			}
			if (!__instance.randomizing)
			{
				globalLeaderboard?.UpdateLeaderboard(__instance, ___alltrackslist, OnUpdateLeaderboardCallback);
			}
		}

		private static void OnUpdateLeaderboardCallback(GlobalLeaderboard.LeaderboardState state)
		{
			switch (state)
			{
			case GlobalLeaderboard.LeaderboardState.ErrorNoSongHashFound:
			case GlobalLeaderboard.LeaderboardState.ErrorNoLeaderboardFound:
				globalLeaderboard.ShowErrorText();
				break;
			case GlobalLeaderboard.LeaderboardState.ReadyToRefresh:
				globalLeaderboard.RefreshLeaderboard();
				break;
			case GlobalLeaderboard.LeaderboardState.ErrorUnexpected:
				Plugin.LogError("Unexpected Error during leaderboard Update request");
				break;
			}
			if (state != GlobalLeaderboard.LeaderboardState.SongDataLoaded || state != GlobalLeaderboard.LeaderboardState.SongDataMissing)
			{
				_hasLeaderboardFinishedLoading = true;
				globalLeaderboard.HideLoadingSwirly();
			}
		}
	}
	public class LeaderboardRowEntry : MonoBehaviour
	{
		public GameObject singleScore;

		public TMP_Text rank;

		public TMP_Text username;

		public TMP_Text score;

		public TMP_Text percent;

		public TMP_Text grade;

		public TMP_Text maxcombo;

		public Image imageStrip;

		public bool hasBackground;

		public string replayId;

		public int rowId;

		public void ConstructLeaderboardEntry(GameObject singleScore, TMP_Text rank, TMP_Text username, TMP_Text score, TMP_Text percent, TMP_Text grade, TMP_Text maxcombo, bool hasBackground = false)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			this.singleScore = singleScore;
			this.rank = rank;
			((Component)rank).GetComponent<RectTransform>().sizeDelta = new Vector2(45f, 35f);
			rank.alignment = (TextAlignmentOptions)4097;
			this.username = username;
			((Component)username).GetComponent<RectTransform>().sizeDelta = new Vector2(170f, 35f);
			username.alignment = (TextAlignmentOptions)4097;
			this.score = score;
			((Component)score).GetComponent<RectTransform>().sizeDelta = new Vector2(170f, 35f);
			score.alignment = (TextAlignmentOptions)4100;
			this.percent = percent;
			((Component)percent).GetComponent<RectTransform>().sizeDelta = new Vector2(85f, 35f);
			percent.alignment = (TextAlignmentOptions)4100;
			this.grade = grade;
			((Component)grade).GetComponent<RectTransform>().sizeDelta = new Vector2(40f, 35f);
			this.maxcombo = maxcombo;
			((Component)maxcombo).GetComponent<RectTransform>().sizeDelta = new Vector2(55f, 35f);
			maxcombo.alignment = (TextAlignmentOptions)4100;
			this.hasBackground = hasBackground;
			imageStrip = ((Component)this.singleScore.transform.Find("Image")).gameObject.GetComponent<Image>();
			((Component)imageStrip).gameObject.SetActive(hasBackground);
		}

		public void ToggleBackground()
		{
			hasBackground = !hasBackground;
			((Component)imageStrip).gameObject.SetActive(hasBackground);
		}

		public void UpdateTheme()
		{
			//IL_0011: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			((Graphic)imageStrip).color = Theme.colors.leaderboard.rowEntry;
			((Graphic)rank).color = Theme.colors.leaderboard.headerText;
			TMP_Text obj = username;
			TMP_Text obj2 = score;
			TMP_Text obj3 = percent;
			TMP_Text obj4 = grade;
			Color val = (((Graphic)maxcombo).color = Theme.colors.leaderboard.text);
			Color val3 = (((Graphic)obj4).color = val);
			Color val5 = (((Graphic)obj3).color = val3);
			Color color = (((Graphic)obj2).color = val5);
			((Graphic)obj).color = color;
			TMP_Text obj5 = rank;
			TMP_Text obj6 = username;
			TMP_Text obj7 = score;
			TMP_Text obj8 = percent;
			TMP_Text obj9 = grade;
			Color32 val8 = (maxcombo.outlineColor = Color32.op_Implicit(Theme.colors.leaderboard.textOutline));
			Color32 val10 = (obj9.outlineColor = val8);
			Color32 val12 = (obj8.outlineColor = val10);
			Color32 val14 = (obj7.outlineColor = val12);
			Color32 outlineColor = (obj6.outlineColor = val14);
			obj5.outlineColor = outlineColor;
		}
	}
	public static class LeaderboardFactory
	{
		private static TMP_Text _leaderboardHeaderPrefab;

		private static TMP_Text _leaderboardTextPrefab;

		private static GameObject _steamLeaderboardPrefab;

		private static GameObject _singleScorePrefab;

		private static GameObject _panelBodyPrefab;

		private static LeaderboardRowEntry _singleRowPrefab;

		private static bool _isInititialized;

		[HarmonyPatch(typeof(GameObjectFactory), "OnLevelSelectControllerInitialize")]
		[HarmonyPostfix]
		public static void OnLevelSelectStart()
		{
			if (!_isInititialized)
			{
				SetSteamLeaderboardPrefab();
				SetSingleScorePrefab();
				SetLeaderboardHeaderPrefab();
				SetLeaderboardTextPrefab();
				SetSingleRowPrefab();
				_isInititialized = true;
			}
			UpdateTheme();
		}

		private static void UpdateTheme()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: 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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			LeaderboardColors leaderboard = Theme.colors.leaderboard;
			((Graphic)_panelBodyPrefab.GetComponent<Image>()).color = leaderboard.panelBody;
			for (int i = 0; i < 3; i++)
			{
				GameObject val = _steamLeaderboardPrefab.GetComponent<LeaderboardManager>().tabs[i];
				ColorBlock colors = ((Selectable)((Component)val.transform.Find("Button")).gameObject.GetComponent<Button>()).colors;
				((ColorBlock)(ref colors)).normalColor = ((ColorBlock)(ref leaderboard.tabs)).normalColor;
				((ColorBlock)(ref colors)).pressedColor = ((ColorBlock)(ref leaderboard.tabs)).pressedColor;
				((ColorBlock)(ref colors)).highlightedColor = ((ColorBlock)(ref leaderboard.tabs)).highlightedColor;
				((Selectable)((Component)val.transform.Find("Button")).gameObject.GetComponent<Button>()).colors = colors;
			}
			((Graphic)((Component)_panelBodyPrefab.transform.Find("scoresbody")).gameObject.GetComponent<Image>()).color = leaderboard.scoresBody;
			_singleRowPrefab.UpdateTheme();
			((Graphic)_leaderboardTextPrefab).color = leaderboard.text;
			_leaderboardTextPrefab.outlineColor = Color32.op_Implicit(leaderboard.textOutline);
			((Graphic)_leaderboardHeaderPrefab).color = leaderboard.headerText;
			_leaderboardHeaderPrefab.outlineColor = Color32.op_Implicit(leaderboard.textOutline);
		}

		private static void SetSteamLeaderboardPrefab()
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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)
			GameObject gameObject = GameObject.Find("Camera-Popups").gameObject;
			GameObject gameObject2 = ((Component)gameObject.transform.Find("LeaderboardCanvas")).gameObject;
			_steamLeaderboardPrefab = Object.Instantiate<GameObject>(gameObject2);
			((Object)_steamLeaderboardPrefab).name = "CustomLeaderboardCanvas";
			_steamLeaderboardPrefab.SetActive(true);
			GameObjectFactory.DestroyFromParent(_steamLeaderboardPrefab, "BG");
			Object.DestroyImmediate((Object)(object)_steamLeaderboardPrefab.GetComponent<CanvasScaler>());
			RectTransform component = _steamLeaderboardPrefab.GetComponent<RectTransform>();
			component.anchoredPosition = new Vector2(237f, -311f);
			((Transform)component).localScale = Vector2.op_Implicit(Vector2.one * 0.5f);
			SetPanelBodyInSteamLeaderboard();
			Object.DontDestroyOnLoad((Object)(object)_steamLeaderboardPrefab);
		}

		private static void SetPanelBodyInSteamLeaderboard()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			_panelBodyPrefab = ((Component)_steamLeaderboardPrefab.transform.Find("PanelBody")).gameObject;
			_panelBodyPrefab.SetActive(true);
			RectTransform component = _panelBodyPrefab.GetComponent<RectTransform>();
			component.anchoredPosition = Vector2.zero;
			component.sizeDelta = new Vector2(750f, 300f);
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "CloseButton");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "txt_legal");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "txt_leaderboards");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "txt_songname");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "rule");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "HelpBtn");
			GameObjectFactory.DestroyFromParent(_panelBodyPrefab, "loadingspinner_parent");
			SetTabsInPanelBody();
			SetErrorsInPanelBody();
			SetScoreboardInPanelBody();
			AddSliderInPanelBody();
		}

		private static void SetTabsInPanelBody()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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)
			GameObject gameObject = ((Component)_panelBodyPrefab.transform.Find("tabs")).gameObject;
			gameObject.SetActive(false);
			Object.DestroyImmediate((Object)(object)gameObject.GetComponent<HorizontalLayoutGroup>());
			for (int i = 0; i < 3; i++)
			{
				GameObject val = _steamLeaderboardPrefab.GetComponent<LeaderboardManager>().tabs[i];
				GameObjectFactory.DestroyFromParent(val, "label");
				GameObjectFactory.DestroyFromParent(val, "rule");
				RectTransform component = val.GetComponent<RectTransform>();
				component.anchoredPosition = new Vector2(15f, -40f);
				component.sizeDelta = new Vector2(40f, 40f);
			}
			VerticalLayoutGroup val2 = gameObject.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)val2).childForceExpandWidth = false;
			bool childScaleWidth = (((HorizontalOrVerticalLayoutGroup)val2).childScaleHeight = false);
			((HorizontalOrVerticalLayoutGroup)val2).childScaleWidth = childScaleWidth;
			childScaleWidth = (((HorizontalOrVerticalLayoutGroup)val2).childControlHeight = false);
			((HorizontalOrVerticalLayoutGroup)val2).childControlWidth = childScaleWidth;
			((LayoutGroup)val2).padding.left = 20;
			((LayoutGroup)val2).padding.top = 36;
			RectTransform component2 = gameObject.GetComponent<RectTransform>();
			component2.anchoredPosition = new Vector2(328f, -10f);
			component2.sizeDelta = new Vector2(-676f, 280f);
		}

		private static void SetErrorsInPanelBody()
		{
			//IL_002d: 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)
			GameObject gameObject = ((Component)_panelBodyPrefab.transform.Find("errors")).gameObject;
			RectTransform component = gameObject.GetComponent<RectTransform>();
			component.anchoredPosition = new Vector2(-30f, 15f);
			component.sizeDelta = new Vector2(-200f, 0f);
			gameObject.SetActive(false);
			((Component)gameObject.transform.Find("error_noleaderboard")).gameObject.SetActive(true);
		}

		private static void SetScoreboardInPanelBody()
		{
			//IL_002d: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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)
			GameObject gameObject = ((Component)_panelBodyPrefab.transform.Find("scoresbody")).gameObject;
			RectTransform component = gameObject.GetComponent<RectTransform>();
			component.anchoredPosition = new Vector2(0f, -10f);
			component.sizeDelta = Vector2.one * -20f;
			GameObject gameObject2 = ((Component)_panelBodyPrefab.transform.Find("scoreboard")).gameObject;
			gameObject2.AddComponent<RectMask2D>();
			RectTransform component2 = gameObject2.GetComponent<RectTransform>();
			component2.anchoredPosition = new Vector2(-30f, -10f);
			component2.sizeDelta = new Vector2(-80f, -20f);
		}

		private static void AddSliderInPanelBody()
		{
			GameObjectFactory.CreateVerticalSliderFromPrefab(_panelBodyPrefab.transform, "LeaderboardVerticalSlider");
		}

		private static void SetSingleScorePrefab()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)_panelBodyPrefab.transform.Find("scoreboard/SingleScore")).gameObject;
			_singleScorePrefab = Object.Instantiate<GameObject>(gameObject);
			((Object)_singleScorePrefab).name = "singleScorePrefab";
			_singleScorePrefab.GetComponent<RectTransform>().sizeDelta = new Vector2(_singleScorePrefab.GetComponent<RectTransform>().sizeDelta.x, 35f);
			GameObject gameObject2 = ((Component)_singleScorePrefab.transform.Find("Image")).gameObject;
			LayoutElement val = gameObject2.AddComponent<LayoutElement>();
			val.ignoreLayout = true;
			RectTransform component = gameObject2.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(-5f, 0f);
			component.anchoredPosition = new Vector2(-10f, 0f);
			Image component2 = gameObject2.GetComponent<Image>();
			((Behaviour)component2).enabled = true;
			((MaskableGraphic)component2).maskable = true;
			_singleScorePrefab.gameObject.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_singleScorePrefab.gameObject);
		}

		private static void SetLeaderboardHeaderPrefab()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			Text val = Object.Instantiate<Text>(((Component)_singleScorePrefab.transform.Find("Num")).GetComponent<Text>());
			_leaderboardHeaderPrefab = Object.Instantiate<TMP_Text>(GameObjectFactory.GetComfortaaFont);
			((Object)_leaderboardHeaderPrefab).name = "LeaderboardHeaderPrefab";
			_leaderboardHeaderPrefab.alignment = (TextAlignmentOptions)514;
			((MaskableGraphic)_leaderboardHeaderPrefab).maskable = true;
			_leaderboardHeaderPrefab.enableWordWrapping = false;
			((Graphic)_leaderboardHeaderPrefab).color = Theme.colors.leaderboard.headerText;
			((Component)_leaderboardHeaderPrefab).gameObject.SetActive(true);
			_leaderboardHeaderPrefab.enableAutoSizing = true;
			_leaderboardHeaderPrefab.fontSizeMax = _leaderboardHeaderPrefab.fontSize;
			Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
			Object.DontDestroyOnLoad((Object)(object)((Component)_leaderboardHeaderPrefab).gameObject);
		}

		private static void SetLeaderboardTextPrefab()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			Text val = Object.Instantiate<Text>(((Component)_singleScorePrefab.transform.Find("Name")).GetComponent<Text>());
			_leaderboardTextPrefab = Object.Instantiate<TMP_Text>(GameObjectFactory.GetComfortaaFont);
			((Object)_leaderboardTextPrefab).name = "LeaderboardTextPrefab";
			_leaderboardTextPrefab.alignment = (TextAlignmentOptions)514;
			((MaskableGraphic)_leaderboardTextPrefab).maskable = true;
			_leaderboardTextPrefab.enableWordWrapping = false;
			((Component)_leaderboardTextPrefab).gameObject.SetActive(true);
			((Graphic)_leaderboardTextPrefab).color = Theme.colors.leaderboard.text;
			_leaderboardTextPrefab.enableAutoSizing = true;
			_leaderboardTextPrefab.fontSizeMax = _leaderboardTextPrefab.fontSize;
			DestroyNumNameScoreFromSingleScorePrefab();
			Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
			Object.DontDestroyOnLoad((Object)(object)((Component)_leaderboardTextPrefab).gameObject);
		}

		private static void DestroyNumNameScoreFromSingleScorePrefab()
		{
			GameObjectFactory.DestroyFromParent(_singleScorePrefab, "Num");
			GameObjectFactory.DestroyFromParent(_singleScorePrefab, "Name");
			GameObjectFactory.DestroyFromParent(_singleScorePrefab, "Score");
		}

		private static void SetSingleRowPrefab()
		{
			_singleRowPrefab = _singleScorePrefab.AddComponent<LeaderboardRowEntry>();
			TMP_Text val = Object.Instantiate<TMP_Text>(_leaderboardHeaderPrefab, _singleScorePrefab.transform);
			((Object)val).name = "rank";
			TMP_Text val2 = Object.Instantiate<TMP_Text>(_leaderboardTextPrefab, _singleScorePrefab.transform);
			((Object)val2).name = "username";
			TMP_Text val3 = Object.Instantiate<TMP_Text>(_leaderboardTextPrefab, _singleScorePrefab.transform);
			((Object)val3).name = "score";
			TMP_Text val4 = Object.Instantiate<TMP_Text>(_leaderboardTextPrefab, _singleScorePrefab.transform);
			((Object)val4).name = "percent";
			TMP_Text val5 = Object.Instantiate<TMP_Text>(_leaderboardTextPrefab, _singleScorePrefab.transform);
			((Object)val5).name = "grade";
			TMP_Text val6 = Object.Instantiate<TMP_Text>(_leaderboardTextPrefab, _singleScorePrefab.transform);
			((Object)val6).name = "maxcombo";
			_singleRowPrefab.ConstructLeaderboardEntry(_singleScorePrefab, val, val2, val3, val4, val5, val6);
			((Object)_singleRowPrefab.singleScore).name = "singleRowPrefab";
		}

		public static GameObject CreateSteamLeaderboardFromPrefab(Transform canvasTransform, string name)
		{
			GameObject val = Object.Instantiate<GameObject>(_steamLeaderboardPrefab, canvasTransform);
			((Object)val).name = name;
			return val;
		}

		public static LeaderboardRowEntry CreateLeaderboardRowEntryFromScore(Transform canvasTransform, string name, ScoreDataFromDB scoreData, int count, Color gradeColor, LevelSelectController levelSelectControllerInstance)
		{
			//IL_007a: 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_0108: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			LeaderboardRowEntry leaderboardRowEntry = Object.Instantiate<LeaderboardRowEntry>(_singleRowPrefab, canvasTransform);
			((Object)leaderboardRowEntry).name = name;
			leaderboardRowEntry.username.text = scoreData.player;
			leaderboardRowEntry.score.text = $"{scoreData.score:n0}" + $" ({scoreData.replay_speed:0.00}x)";
			GameObject val = GameObjectFactory.CreateBubble(new Vector2(175f, 200f), ((Object)leaderboardRowEntry).name + "ScoreBubble", GetTallyBubbleText(scoreData.GetTally), 10, false, 22);
			bool childControlHeight;
			if (scoreData.modifiers != null && !scoreData.modifiers.Contains("NONE"))
			{
				TMP_Text score = leaderboardRowEntry.score;
				score.text += "*";
				GameObject val2 = new GameObject("HorizontalLayout", new Type[1] { typeof(HorizontalLayoutGroup) });
				val2.transform.SetParent(val.transform.Find("Window Body"));
				HorizontalLayoutGroup component = val2.GetComponent<HorizontalLayoutGroup>();
				childControlHeight = (((HorizontalOrVerticalLayoutGroup)component).childForceExpandHeight = false);
				((HorizontalOrVerticalLayoutGroup)component).childControlHeight = childControlHeight;
				RectTransform component2 = val2.GetComponent<RectTransform>();
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(0.5f, 0f);
				component2.anchorMax = val3;
				component2.anchorMin = val3;
				component2.anchoredPosition = Vector2.zero;
				((Component)val.transform.Find("Window Body/BubbleText")).GetComponent<TMP_Text>().rectTransform.sizeDelta = new Vector2(175f, 150f);
				string[] modifiers = scoreData.modifiers;
				foreach (string text in modifiers)
				{
					((MaskableGraphic)GameObjectFactory.CreateImageHolder(val2.transform, Vector2.zero, Vector2.one * 42f, AssetManager.GetSprite(text + ".png"), text + "Icon", true).GetComponent<Image>()).maskable = false;
				}
			}
			((Component)leaderboardRowEntry.score).gameObject.AddComponent<BubblePopupHandler>().Initialize(val, true);
			leaderboardRowEntry.rank.text = "#" + count;
			leaderboardRowEntry.percent.text = scoreData.percentage.ToString("0.00") + "%";
			leaderboardRowEntry.grade.text = scoreData.grade;
			if (scoreData.grade == "SS")
			{
				leaderboardRowEntry.grade.text = "S";
				GameObjectFactory.CreateDoubleText(leaderboardRowEntry.grade.transform, "DoubleS" + scoreData.player + "Text", "S", Color.yellow);
			}
			else if (scoreData.grade == "SSS")
			{
				leaderboardRowEntry.grade.text = "S";
				GameObjectFactory.CreateTripleText(leaderboardRowEntry.grade.transform, "TripleS" + scoreData.player + "Text", "S", Color.yellow);
			}
			else
			{
				((Graphic)leaderboardRowEntry.grade).color = gradeColor;
			}
			if (scoreData.is_rated)
			{
				leaderboardRowEntry.maxcombo.text = Mathf.RoundToInt(scoreData.tt) + "tt";
				((Component)leaderboardRowEntry.maxcombo).gameObject.AddComponent<BubblePopupHandler>().Initialize(GameObjectFactory.CreateBubble(new Vector2(150f, 75f), ((Object)leaderboardRowEntry).name + "ComboBubble", $"{scoreData.max_combo} combo", 10, true, 22), true);
			}
			else
			{
				leaderboardRowEntry.maxcombo.text = scoreData.max_combo + "x";
			}
			leaderboardRowEntry.replayId = scoreData.replay_id;
			leaderboardRowEntry.rowId = count;
			leaderboardRowEntry.singleScore.AddComponent<CanvasGroup>();
			HorizontalLayoutGroup val4 = leaderboardRowEntry.singleScore.AddComponent<HorizontalLayoutGroup>();
			((LayoutGroup)val4).childAlignment = (TextAnchor)3;
			childControlHeight = (((HorizontalOrVerticalLayoutGroup)val4).childForceExpandHeight = false);
			((HorizontalOrVerticalLayoutGroup)val4).childForceExpandWidth = childControlHeight;
			childControlHeight = (((HorizontalOrVerticalLayoutGroup)val4).childScaleHeight = false);
			((HorizontalOrVerticalLayoutGroup)val4).childScaleWidth = childControlHeight;
			childControlHeight = (((HorizontalOrVerticalLayoutGroup)val4).childControlHeight = false);
			((HorizontalOrVerticalLayoutGroup)val4).childControlWidth = childControlHeight;
			((HorizontalOrVerticalLayoutGroup)val4).spacing = 8f;
			((LayoutGroup)val4).padding.left = 8;
			((LayoutGroup)val4).padding.top = 2;
			leaderboardRowEntry.singleScore.SetActive(true);
			((Component)leaderboardRowEntry.singleScore.transform.Find("Image")).gameObject.SetActive(count % 2 == 0);
			string replayId = leaderboardRowEntry.replayId;
			if (replayId != "" && replayId != null)
			{
				GameObjectFactory.CreateCustomButton(leaderboardRowEntry.singleScore.transform, Vector2.zero, new Vector2(26f, 26f), "►", "ReplayButton", (Action)delegate
				{
					Plugin.LogInfo("ID:" + replayId);
					ReplaySystemManager.ResolveLoadReplay(replayId, levelSelectControllerInstance);
				});
			}
			return leaderboardRowEntry;
		}

		private static string GetTallyBubbleText(int[] tally)
		{
			return (tally != null) ? ($"Perfect: {tally[4]}\n" + $"Nice: {tally[3]}\n" + $"Okay: {tally[2]}\n" + $"Meh: {tally[1]}\n" + $"Nasty: {tally[0]}\n") : "No Tally";
		}

		public static GameObject CreateDefaultPanel(Transform canvasTransform, Vector2 anchoredPosition, Vector2 size, string name)
		{
			//IL_001d: 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_0037: 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)
			GameObject val = Object.Instantiate<GameObject>(_panelBodyPrefab, canvasTransform);
			((Object)val).name = name;
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchoredPosition = anchoredPosition;
			component.sizeDelta = size;
			((Transform)component).localScale = Vector2.op_Implicit(Vector2.one * 0.5f);
			GameObjectFactory.DestroyFromParent(val, "scoreboard");
			GameObjectFactory.DestroyFromParent(val, "tabs");
			GameObjectFactory.DestroyFromParent(val, "errors");
			GameObjectFactory.DestroyFromParent(val, "LeaderboardVerticalSlider");
			return val;
		}
	}
	[BepInPlugin("TootTallyLeaderboard", "TootTallyLeaderboard", "1.0.11")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin, ITootTallyModule
	{
		public class Options
		{
			public ConfigEntry<bool> ShowLeaderboard { get; set; }

			public ConfigEntry<bool> ShowCoolS { get; set; }

			public ConfigEntry<bool> SubmitScores { get; set; }

			public ConfigEntry<string> SessionDate { get; set; }

			public ConfigEntry<float> SessionStartTT { get; set; }
		}

		public static Plugin Instance;

		private const string CONFIG_NAME = "TootTally.cfg";

		public Options option;

		private Harmony _harmony;

		public bool ShouldUpdateSession;

		public static TootTallySettingPage settingPage;

		public ConfigEntry<bool> ModuleConfigEnabled { get; set; }

		public bool IsConfigInitialized { get; set; }

		public string Name
		{
			get
			{
				return "TootTally Leaderboard";
			}
			set
			{
				Name = value;
			}
		}

		public static void LogInfo(string msg)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)msg);
		}

		public static void LogError(string msg)
		{
			((BaseUnityPlugin)Instance).Logger.LogError((object)msg);
		}

		public static void LogWarning(string msg)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)msg);
		}

		public static void LogDebug(string msg)
		{
			if (Plugin.Instance.DebugMode.Value)
			{
				((BaseUnityPlugin)Instance).Logger.LogDebug((object)msg);
			}
		}

		private void Awake()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (!((Object)(object)Instance != (Object)null))
			{
				Instance = this;
				_harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				GameInitializationEvent.Register(((BaseUnityPlugin)this).Info, (Action)TryInitialize);
			}
		}

		private void TryInitialize()
		{
			ModuleConfigEnabled = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Modules", "TootTally Leaderboard", true, "Leaderboard and Replay features for TootTally");
			TootTallyModuleManager.AddModule((ITootTallyModule)(object)this);
		}

		public void LoadModule()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			string text = Path.Combine(Paths.BepInExRootPath, "config/");
			ConfigFile val = new ConfigFile(text + "TootTally.cfg", true);
			option = new Options
			{
				ShowLeaderboard = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show Leaderboard", true, "Show TootTally Leaderboard on Song Select."),
				ShowCoolS = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show Cool S", false, "Show special graphic when getting SS and SSS on a song."),
				SubmitScores = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Suibmit Scores", true, "Submit your scores to the Toottally leaderboard."),
				SessionDate = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Session Date", DateTime.Now.ToString(), "The last time that the session started recording."),
				SessionStartTT = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TT Session Start", 0f, "The amount of TT you started the session with.")
			};
			Plugin.MainTootTallySettingPage.AddToggle("Show Leaderboard", option.ShowLeaderboard, (UnityAction<bool>)null);
			Plugin.MainTootTallySettingPage.AddToggle("Show Cool S", option.ShowCoolS, (UnityAction<bool>)null);
			Plugin.MainTootTallySettingPage.AddToggle("Submit Scores", option.SubmitScores, (UnityAction<bool>)null);
			AssetManager.LoadAssets(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Instance).Info.Location), "Assets"));
			ShouldUpdateSession = DateTime.Parse(Instance.option.SessionDate.Value).Date.CompareTo(DateTime.Now.Date) < 0;
			_harmony.PatchAll(typeof(LeaderboardFactory));
			_harmony.PatchAll(typeof(ReplaySystemManager));
			_harmony.PatchAll(typeof(GlobalLeaderboardManager));
			LogInfo("Module loaded!");
		}

		public void UnloadModule()
		{
			_harmony.UnpatchSelf();
			settingPage.Remove();
			LogInfo("Module unloaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "TootTallyLeaderboard";

		public const string PLUGIN_NAME = "TootTallyLeaderboard";

		public const string PLUGIN_VERSION = "1.0.11";
	}
}
namespace TootTallyLeaderboard.Replays
{
	public class NewReplaySystem
	{
		[Serializable]
		private class ReplayVersion
		{
			public string version { get; set; }
		}

		[Serializable]
		private class ReplayData
		{
			public string version { get; set; }

			public string username { get; set; }

			public string starttime { get; set; }

			public string endtime { get; set; }

			public string input { get; set; }

			public string song { get; set; }

			public string uuid { get; set; }

			public float samplerate { get; set; }

			public float scrollspeed { get; set; }

			public int defaultnotelength { get; set; }

			public float gamespeedmultiplier { get; set; }

			public string gamemodifiers { get; set; }

			public float audiolatency { get; set; }

			public int pluginbuilddate { get; set; }

			public string gameversion { get; set; }

			public string songhash { get; set; }

			public int finalscore { get; set; }

			public int maxcombo { get; set; }

			public int[] finalnotetallies { get; set; }

			public List<dynamic[]> framedata { get; set; }

			public List<dynamic[]> notedata { get; set; }

			public List<dynamic[]> tootdata { get; set; }

			public ReplayData(float sampleRate)
			{
				framedata = new List<object[]>();
				notedata = new List<object[]>();
				tootdata = new List<object[]>();
				pluginbuilddate = Plugin.BUILDDATE;
				version = "2.1.0";
				username = TootTallyUser.userInfo.username;
				audiolatency = GlobalVariables.localsettings.latencyadjust;
				gameversion = Application.version;
				samplerate = sampleRate;
			}

			public void ClearData()
			{
				framedata?.Clear();
				notedata?.Clear();
				tootdata?.Clear();
			}

			public void SetStartTime()
			{
				starttime = new DateTimeOffset(DateTime.Now.ToUniversalTime()).ToUnixTimeSeconds().ToString();
			}

			public void SetEndTime()
			{
				endtime = new DateTimeOffset(DateTime.Now.ToUniversalTime()).ToUnixTimeSeconds().ToString();
			}
		}

		public enum FDStruct
		{
			T,
			N,
			P,
			MX,
			MY
		}

		public enum TDStruct
		{
			T,
			N,
			O
		}

		public enum NDStruct
		{
			NS,
			R,
			I,
			C,
			M,
			S,
			H,
			HC,
			TL
		}

		public enum ReplayState
		{
			None,
			ReplayLoadErrorIncompatible,
			ReplayLoadError,
			ReplayLoadSuccess,
			ReplayLoadNotFound
		}

		public static List<string> incompatibleReplayVersions = new List<string> { "1.0.0" };

		public const string REPLAY_VERSION = "2.1.0";

		private int _frameIndex;

		private int _tootIndex;

		private ReplayData _replayData;

		private dynamic[] _lastFrame;

		private dynamic[] _currentFrame;

		private dynamic[] _currentToot;

		private dynamic[] _currentNote;

		private bool _wasTouchScreenUsed;

		private bool _wasTabletUsed;

		private bool _isTooting;

		private int _maxCombo;

		private bool _isLastNote;

		private const float FLOAT_PRECISION = 1000f;

		private int _lastTally;

		public float GetReplaySpeed => _replayData.gamespeedmultiplier;

		public bool GetIsTooting => _isTooting;

		public string GetUsername => _replayData.username;

		public string GetSongName => _replayData.song;

		public bool IsFullCombo => GlobalVariables.gameplay_notescores[0] == 0 && GlobalVariables.gameplay_notescores[1] == 0 && GlobalVariables.gameplay_notescores[2] == 0;

		public bool IsTripleS => GlobalVariables.gameplay_notescores[0] == 0 && GlobalVariables.gameplay_notescores[1] == 0 && GlobalVariables.gameplay_notescores[2] == 0 && GlobalVariables.gameplay_notescores[3] == 0;

		public bool GetIsOldReplay => TootTallyGlobalVariables.isOldReplay;

		public string GetVersion => _replayData.version;

		public NewReplaySystem()
		{
			_replayData = new ReplayData(60f);
		}

		public void SetupRecording(int targetFramerate)
		{
			_replayData = new ReplayData(targetFramerate);
			_replayData.gamemodifiers = GameModifierManager.GetModifiersString();
			_replayData.scrollspeed = GlobalVariables.gamescrollspeed;
			_replayData.gamespeedmultiplier = float.Parse(ReplaySystemManager.gameSpeedMultiplier.ToString("0.00"));
			TromboneTrack val = TrackLookup.lookup(GlobalVariables.chosen_track_data.trackref);
			_replayData.song = val.trackname_long;
			if (val is CustomTrack)
			{
				_replayData.songhash = SongDataHelper.GetSongHash(val);
			}
			else
			{
				_replayData.songhash = val.trackref;
			}
			_currentFrame = new object[5];
			_currentNote = new object[9];
			_currentToot = new object[3];
			Plugin.LogInfo("Started recording replay");
		}

		public void SetReplayDefaultNoteLength(int spacing)
		{
			_replayData.defaultnotelength = spacing;
		}

		public int GetDefaultNoteLength()
		{
			return _replayData.defaultnotelength;
		}

		public void SetStartTime()
		{
			_replayData.SetStartTime();
			Plugin.LogInfo("Replay started recording at " + _replayData.starttime);
		}

		public void SetEndTime()
		{
			_replayData.SetEndTime();
			Plugin.LogInfo("Replay recording finished at " + _replayData.endtime);
		}

		public void SetUsernameAndSongName(string username, string songname)
		{
			_replayData.username = username;
			_replayData.song = songname;
		}

		public void RecordFrameData(GameController __instance, float time, float noteHolderPosition)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (Input.touchCount > 0)
			{
				_wasTouchScreenUsed = true;
			}
			object[] array = new object[5]
			{
				Round(time, 10f),
				Round(noteHolderPosition, 10f),
				Round(__instance.pointer.transform.localPosition.y),
				(int)Input.mousePosition.x,
				(int)Input.mousePosition.y
			};
			bool flag = _lastFrame == null;
			if (flag || ((flag | ((dynamic)array[2] != _lastFrame[2] && (dynamic)array[1] != _lastFrame[1] && (dynamic)array[4] != _lastFrame[4])) ? true : false))
			{
				_replayData.framedata.Add(array);
				_lastFrame = array;
			}
		}

		public float Round(float f, float mult = 1f)
		{
			return Mathf.Round(f * 1000f * mult) / (1000f * mult);
		}

		public void RecordNoteDataPrefix(GameController __instance)
		{
			_currentNote = new object[9]
			{
				Round(__instance.notescoreaverage),
				__instance.released_button_between_notes ? 1 : 0,
				0,
				0,
				0,
				0,
				0f,
				0,
				0
			};
		}

		public void RecordNoteDataPostfix(GameController __instance)
		{
			_currentNote[2] = __instance.currentnoteindex;
			_currentNote[3] = __instance.highestcombocounter;
			_currentNote[4] = __instance.multiplier;
			_currentNote[5] = __instance.totalscore;
			_currentNote[6] = Round(__instance.currenthealth);
			_currentNote[7] = (_maxCombo = __instance.highestcombo_level);
			_currentNote[8] = _lastTally;
			_replayData.notedata.Add(_currentNote);
		}

		public void SaveLastNoteTally(int tallyIndex)
		{
			_lastTally = tallyIndex;
		}

		public void RecordToot(float time, float noteHolderPosition, bool isTooting)
		{
			object[] item = new object[3]
			{
				Round(time, 10f),
				Round(noteHolderPosition, 10f),
				isTooting ? 1 : 0
			};
			_replayData.tootdata.Add(item);
		}

		public string GetRecordedReplayJson(string uuid)
		{
			_replayData.uuid = uuid;
			_replayData.input = GetInputTypeString();
			_replayData.finalscore = GlobalVariables.gameplay_scoretotal;
			_replayData.maxcombo = _maxCombo;
			_replayData.finalnotetallies = new int[5]
			{
				_replayData.notedata.Count((dynamic[] x) => x[8] == 4),
				_replayData.notedata.Count((dynamic[] x) => x[8] == 3),
				_replayData.notedata.Count((dynamic[] x) => x[8] == 2),
				_replayData.notedata.Count((dynamic[] x) => x[8] == 1),
				_replayData.notedata.Count((dynamic[] x) => x[8] == 0)
			};
			return JsonConvert.SerializeObject((object)_replayData);
		}

		private string GetInputTypeString()
		{
			if (_wasTabletUsed)
			{
				return "Tablet";
			}
			if (_wasTouchScreenUsed)
			{
				return "Touch";
			}
			return "Mouse";
		}

		public void OnReplayPlayerStart()
		{
			_frameIndex = 0;
			_tootIndex = 0;
			_isTooting = false;
			_isLastNote = false;
			_currentFrame = ((_replayData.framedata.Count > 0) ? _replayData.framedata.First() : null);
			_currentNote = ((_replayData.notedata.Count > 0) ? _replayData.notedata.First() : null);
			_currentToot = new object[3] { 0, 0, 0 };
		}

		public void OnReplayRewind(float newTiming, GameController __instance)
		{
			if (_replayData.framedata.Count != 0)
			{
				_frameIndex = Mathf.Clamp(_replayData.framedata.FindIndex((dynamic[] frame) => (float)frame[0] > newTiming) - 1, 0, _replayData.framedata.Count - 1);
				_currentFrame = _replayData.framedata[_frameIndex];
			}
			if (_replayData.tootdata.Count != 0)
			{
				_tootIndex = Mathf.Clamp(_replayData.tootdata.FindIndex((dynamic[] frame) => (float)frame[0] > newTiming) - 1, 0, _replayData.tootdata.Count - 1);
				_currentToot = _replayData.tootdata[_tootIndex];
			}
			_isTooting = false;
			if (_replayData.notedata.Count != 0 && __instance.currentnoteindex != 0)
			{
				__instance.currentscore = (int)_replayData.notedata.Find((dynamic[] note) => (int)note[2] == __instance.currentnoteindex - 1)[5];
			}
		}

		public ReplayState LoadReplay(string replayFileName)
		{
			string text = Path.Combine(Paths.BepInExRootPath, "Replays/");
			if (!Directory.Exists(text))
			{
				Plugin.LogInfo("Replay folder not found");
				return ReplayState.ReplayLoadError;
			}
			if (!File.Exists(text + replayFileName + ".ttr"))
			{
				Plugin.LogInfo("Replay File does not exist");
				return ReplayState.ReplayLoadNotFound;
			}
			string text2 = FileHelper.ReadJsonFromFile(text, replayFileName + ".ttr");
			string version = JsonConvert.DeserializeObject<ReplayVersion>(text2).version;
			_replayData = JsonConvert.DeserializeObject<ReplayData>(text2);
			TootTallyGlobalVariables.isOldReplay = IsOldReplayFormat(version);
			if (GetIsOldReplay)
			{
				ConvertToCurrentReplayVersion(ref _replayData);
				GlobalVariables.gamescrollspeed = _replayData.scrollspeed;
			}
			if (incompatibleReplayVersions.Contains(_replayData.pluginbuilddate.ToString()))
			{
				TootTallyNotifManager.DisplayError($"Replay incompatible:\nReplay Build Date is {_replayData.pluginbuilddate}\nCurrent Build Date is {Plugin.BUILDDATE}", 6f);
				Plugin.LogError("Cannot load replay:");
				Plugin.LogError("   Replay Build Date is " + _replayData.pluginbuilddate);
				Plugin.LogError("   Current Plugin Build Date " + Plugin.BUILDDATE);
				return ReplayState.ReplayLoadErrorIncompatible;
			}
			GameModifierManager.LoadModifiersFromString(_replayData.gamemodifiers ?? "");
			return ReplayState.ReplayLoadSuccess;
		}

		private bool IsOldReplayFormat(string version)
		{
			return version == null || string.Compare(version, "2.0.0") < 0;
		}

		private void ConvertToCurrentReplayVersion(ref ReplayData replayData)
		{
			TootTallyNotifManager.DisplayNotif("Converting old replay format...", 6f);
			object[][] array = new object[replayData.framedata.Count][];
			for (int i = 0; i < replayData.framedata.Count; i++)
			{
				array[i] = new object[5]
				{
					(int)Math.Abs(replayData.framedata[i][0]),
					(int)replayData.framedata[i][0],
					(float)replayData.framedata[i][1] / 100f,
					0,
					0
				};
			}
			object[][] array2 = new object[replayData.notedata.Count][];
			for (int j = 0; j < replayData.notedata.Count; j++)
			{
				array2[j] = new object[9]
				{
					(float)replayData.notedata[j][5] / 1000f,
					-1,
					(int)replayData.notedata[j][0],
					-1,
					(int)replayData.notedata[j][2],
					(int)replayData.notedata[j][1],
					(int)replayData.notedata[j][3],
					-1,
					(int)replayData.notedata[j][4]
				};
			}
			object[][] array3 = new object[replayData.tootdata.Count][];
			for (int k = 0; k < replayData.tootdata.Count; k++)
			{
				array3[k] = new object[3]
				{
					(int)Math.Abs(replayData.tootdata[k][0]),
					replayData.tootdata[k][0],
					(k % 2 == 0) ? 1 : 0
				};
			}
			replayData.framedata = array.ToList();
			replayData.notedata = array2.ToList();
			replayData.tootdata = array3.ToList();
		}

		public void PlaybackReplay(GameController __instance, float time)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			Cursor.visible = true;
			if (!__instance.controllermode)
			{
				__instance.controllermode = true;
			}
			time = ((!GetIsOldReplay) ? (time - ((float)GlobalVariables.localsettings.latencyadjust / 1000f - _replayData.audiolatency / 1000f)) : (((_replayData.pluginbuilddate < 20230705) ? Math.Abs(__instance.noteholder.transform.position.x) : Math.Abs(__instance.noteholderr.anchoredPosition.x)) * GetNoteHolderPrecisionMultiplier()));
			PlaybackTimeFrameData(time);
			PlaybackTimeTootData(time);
			if (_replayData.framedata.Count > _frameIndex && _lastFrame != null && _currentFrame != null)
			{
				InterpolateTimeCursorPosition(time, __instance);
			}
		}

		public static float GetNoteHolderPrecisionMultiplier()
		{
			return 10f / ((GlobalVariables.gamescrollspeed <= 1f) ? GlobalVariables.gamescrollspeed : 1f);
		}

		private void InterpolateTimeCursorPosition(float time, GameController __instance)
		{
			if (_currentFrame[0] - _lastFrame[0] > 0)
			{
				float num = (time - (float)_lastFrame[0]) / ((float)_currentFrame[0] - (float)_lastFrame[0]);
				float num2 = EasingHelper.Lerp((float)_lastFrame[2], (float)_currentFrame[2], num);
				SetCursorPosition(__instance, num2);
				__instance.puppet_humanc.doPuppetControl((0f - num2) / 225f);
			}
			else
			{
				SetCursorPosition(__instance, (float)_currentFrame[2]);
			}
		}

		private void PlaybackTimeFrameData(float time)
		{
			if (_lastFrame != _currentFrame && time >= _currentFrame[0])
			{
				_lastFrame = _currentFrame;
			}
			if (_replayData.framedata.Count > _frameIndex && (_currentFrame == null || time >= _currentFrame[0]))
			{
				_frameIndex = _replayData.framedata.FindIndex((_frameIndex > 1) ? (_frameIndex - 1) : 0, (dynamic[] x) => time < x[0]);
				if (_replayData.framedata.Count > _frameIndex && _frameIndex != -1)
				{
					_currentFrame = _replayData.framedata[_frameIndex];
				}
			}
		}

		private void PlaybackTimeTootData(float time)
		{
			if (_currentToot != null && time >= _currentToot[0] && _isTooting != (_currentToot[2] == 1))
			{
				_isTooting = _currentToot[2] == 1;
			}
			if (_replayData.tootdata.Count > _tootIndex && time >= _currentToot[0])
			{
				_currentToot = _replayData.tootdata[_tootIndex++];
			}
		}

		public void SetNoteScorePrefix(GameController __instance)
		{
			if (_replayData.notedata.Count != 0 && !_isLastNote)
			{
				_currentNote = _replayData.notedata.Find((dynamic[] x) => x[2] == __instance.currentnoteindex);
				_isLastNote = _replayData.notedata.Last()[2] == __instance.currentnoteindex;
			}
			if (_currentNote != null)
			{
				__instance.notescoreaverage = (float)_currentNote[0];
				if (!GetIsOldReplay)
				{
					__instance.released_button_between_notes = _currentNote[1] == 1;
				}
			}
		}

		public void SetNoteScorePostFix(GameController __instance)
		{
			if (_currentNote != null)
			{
				__instance.rainbowcontroller.champmode = _currentNote[6] == 100;
				__instance.multiplier = (int)_currentNote[4];
				if (__instance.currentscore < 0)
				{
					__instance.currentscore = (int)_currentNote[5];
				}
				__instance.totalscore = (int)_currentNote[5];
				__instance.currenthealth = (float)_currentNote[6];
				if (!GetIsOldReplay)
				{
					__instance.highestcombocounter = (int)_currentNote[3];
					__instance.highestcombo_level = (int)_currentNote[7];
				}
				_currentNote = null;
			}
		}

		public void SetCursorPosition(GameController __instance, float newPosition)
		{
			//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)
			//IL_0016: 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)
			Vector2 val = Vector2.op_Implicit(__instance.pointer.transform.localPosition);
			val.y = newPosition;
			__instance.pointer.transform.localPosition = Vector2.op_Implicit(val);
		}

		public void ClearData()
		{
			Plugin.LogInfo("Replay data cleared");
			_replayData?.ClearData();
		}
	}
	public static class ReplaySystemManager
	{
		public enum ReplayManagerState
		{
			None,
			Paused,
			Recording,
			Replaying,
			Spectating
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction<float> <>9__36_0;

			public static UnityAction<float> <>9__36_1;

			public static Action<string> <>9__60_1;

			public static Action<int> <>9__60_0;

			public static UnityAction <>9__75_0;

			internal void <OnSetUpBGControllerRefsDelayedPostFix>b__36_0(float value)
			{
				_videoPlayer.playbackSpeed = value;
			}

			internal void <OnSetUpBGControllerRefsDelayedPostFix>b__36_1(float value)
			{
				_videoPlayer.time = _videoPlayer.length * (double)value;
			}

			internal void <StartAPICallCoroutine>b__60_0(int songHashInDB)
			{
				if (songHashInDB == 0)
				{
					_replayUUID = null;
					return;
				}
				((MonoBehaviour)Plugin.Instance).StartCoroutine((IEnumerator)TootTallyAPIService.GetReplayUUID(Plugin.GetAPIKey, SongDataHelper.GetChoosenSongHash(), gameSpeedMultiplier, (Action<string>)delegate(string UUID)
				{
					_replayUUID = UUID;
				}));
			}

			internal void <StartAPICallCoroutine>b__60_1(string UUID)
			{
				_replayUUID = UUID;
			}

			internal void <OnPauseAddReplayButton>b__75_0()
			{
				_replayFileName = "TempReplay";
				_replay.SetUsernameAndSongName(TootTallyUser.userInfo.username, GlobalVariables.chosen_track_data.trackname_long);
				Plugin.LogInfo("TempReplay Loaded");
				_currentGCInstance.pauseRetryLevel();
			}
		}

		public static List<string> incompatibleReplayPluginBuildDate = new List<string> { "20230106" };

		private const float SWIRLY_SPEED = 0.5f;

		private static int _targetFramerate;

		private static bool _hasPaused;

		private static bool _hasRewindReplay;

		private static bool _hasReleaseToot;

		private static bool _lastIsTooting;

		private static float _elapsedTime;

		private static string _replayUUID;

		private static string _replayFileName;

		private static float _replayTracktime;

		private static NewReplaySystem _replay;

		private static GameObject _toottallyPauseWarning;

		private static ReplayManagerState _replayManagerState;

		private static Slider _replaySpeedSlider;

		private static Slider _replayTimestampSlider;

		private static VideoPlayer _videoPlayer;

		private static TMP_Text _replayIndicatorMarquee;

		private static readonly Vector3 _marqueeScroll = new Vector3(60f, 0f, 0f);

		private static readonly Vector3 _marqueeStartingPosition = new Vector3(500f, -100f, 100f);

		private static GameController _currentGCInstance;

		private static SecondDegreeDynamicsAnimation _pausePointerAnimation;

		private static GameObject _pauseArrow;

		private static Vector2 _pauseArrowDestination;

		private static GameObject _tootTallyScorePanel;

		private static LoadingIcon _loadingSwirly;

		private static LevelSelectController _currentLevelSelectInstance;

		public static bool wasPlayingReplay => TootTallyGlobalVariables.wasReplaying;

		public static float gameSpeedMultiplier => TootTallyGlobalVariables.gameSpeedMultiplier;

		[HarmonyPatch(typeof(GameController), "Start")]
		[HarmonyPrefix]
		public static void GameControllerPrefixPatch(GameController __instance)
		{
			TootTallyGlobalVariables.wasReplaying = _replayFileName != null && _replayFileName != "Spectating";
			if (_replay == null)
			{
				_replayManagerState = ReplayManagerState.None;
				_replay = new NewReplaySystem();
			}
		}

		[HarmonyPatch(typeof(GameController), "Start")]
		[HarmonyPostfix]
		public static void GameControllerPostfixPatch(GameController __instance)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			_currentGCInstance = __instance;
			if (!__instance.freeplay)
			{
				if (_replayFileName == null && !TootTallyGlobalVariables.isSpectating)
				{
					OnRecordingStart();
				}
				e