Decompiled source of HachimiMusic v1.0.0

BepInEx\plugins\HJM-HachimiMusic\HJM.HachimiMusic.REPO.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HJM.HachimiMusic.REPO
{
	public static class BoomboxHud
	{
		private static TextMeshProUGUI songText;

		private static TextMeshProUGUI volumeText;

		private static Transform lastEnergyParent;

		private static string volumeMessage;

		private static float volumeUntil;

		public static void ShowVolume(int percent)
		{
			volumeMessage = $"音量: {percent}%";
			volumeUntil = Time.unscaledTime + 3f;
		}

		public static void UpdateHud()
		{
			if ((Object)(object)EnergyUI.instance == (Object)null)
			{
				return;
			}
			EnsureTexts();
			if (!((Object)(object)songText == (Object)null) && !((Object)(object)volumeText == (Object)null))
			{
				UpdatePositions();
				HachimiBoombox hachimiBoombox = FindLocalRelevantPlayingBoombox();
				if ((Object)(object)hachimiBoombox != (Object)null && !string.IsNullOrEmpty(hachimiBoombox.CurrentTrackTitle))
				{
					((Component)songText).gameObject.SetActive(true);
					((TMP_Text)songText).text = "正在播放: " + hachimiBoombox.CurrentTrackTitle;
				}
				else
				{
					((Component)songText).gameObject.SetActive(false);
				}
				if (!string.IsNullOrEmpty(volumeMessage) && Time.unscaledTime <= volumeUntil)
				{
					((Component)volumeText).gameObject.SetActive(true);
					((TMP_Text)volumeText).text = volumeMessage;
				}
				else
				{
					((Component)volumeText).gameObject.SetActive(false);
				}
			}
		}

		private static HachimiBoombox FindLocalRelevantPlayingBoombox()
		{
			foreach (HachimiBoombox activeBoombox in HachimiBoombox.ActiveBoomboxes)
			{
				if ((Object)(object)activeBoombox != (Object)null && activeBoombox.IsPlaying && activeBoombox.IsLocalRelevant())
				{
					return activeBoombox;
				}
			}
			return null;
		}

		private static void EnsureTexts()
		{
			//IL_007d: 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)
			Transform parent = ((Component)EnergyUI.instance).transform.parent;
			if (!((Object)(object)parent == (Object)null) && (!((Object)(object)songText != (Object)null) || !((Object)(object)volumeText != (Object)null) || !((Object)(object)lastEnergyParent == (Object)(object)parent)))
			{
				lastEnergyParent = parent;
				TextMeshProUGUI component = ((Component)EnergyUI.instance).GetComponent<TextMeshProUGUI>();
				if (!((Object)(object)component == (Object)null))
				{
					songText = CreateHudLine("HachimiSongHUD", parent, component, 13f, new Color(1f, 0.92f, 0.45f, 1f));
					volumeText = CreateHudLine("HachimiVolumeHUD", parent, component, 11.5f, new Color(0.85f, 0.95f, 1f, 1f));
					UpdatePositions();
				}
			}
		}

		private static void UpdatePositions()
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)songText == (Object)null || (Object)(object)volumeText == (Object)null || (Object)(object)EnergyUI.instance == (Object)null)
			{
				return;
			}
			TextMeshProUGUI component = ((Component)EnergyUI.instance).GetComponent<TextMeshProUGUI>();
			Canvas componentInParent = ((Component)EnergyUI.instance).GetComponentInParent<Canvas>();
			Canvas val = ((componentInParent != null) ? componentInParent.rootCanvas : null);
			if (!((Object)(object)component == (Object)null) && !((Object)(object)val == (Object)null))
			{
				RectTransform component2 = ((Component)val).GetComponent<RectTransform>();
				if (!((Object)(object)component2 == (Object)null))
				{
					Vector3[] array = (Vector3[])(object)new Vector3[4];
					component2.GetWorldCorners(array);
					float x = array[0].x;
					float num = array[3].x - array[0].x;
					float num2 = x + num * 0.015f;
					Vector3[] array2 = (Vector3[])(object)new Vector3[4];
					((TMP_Text)component).rectTransform.GetWorldCorners(array2);
					float x2 = array2[0].x;
					float y = array2[0].y;
					float num3 = array2[1].y - array2[0].y;
					float z = ((TMP_Text)component).transform.position.z;
					float num4 = Mathf.Max(num2, x2 - num3 * 1.05f);
					((Transform)((TMP_Text)songText).rectTransform).position = new Vector3(num4, y - num3 * 0.06f, z);
					((Transform)((TMP_Text)volumeText).rectTransform).position = new Vector3(num4, y - num3 * 0.62f, z);
				}
			}
		}

		private static TextMeshProUGUI CreateHudLine(string name, Transform parent, TextMeshProUGUI template, float fontSize, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001a: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			val.transform.localRotation = Quaternion.identity;
			val.transform.localScale = Vector3.one;
			RectTransform obj = val.AddComponent<RectTransform>();
			obj.anchorMin = new Vector2(0f, 1f);
			obj.anchorMax = new Vector2(0f, 1f);
			obj.pivot = new Vector2(0f, 1f);
			obj.sizeDelta = new Vector2(680f, 32f);
			TextMeshProUGUI obj2 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj2).font = ((TMP_Text)template).font;
			((TMP_Text)obj2).fontSharedMaterial = ((TMP_Text)template).fontSharedMaterial;
			((TMP_Text)obj2).fontSize = fontSize;
			((TMP_Text)obj2).fontStyle = ((TMP_Text)template).fontStyle;
			((Graphic)obj2).color = color;
			((TMP_Text)obj2).alignment = (TextAlignmentOptions)257;
			((TMP_Text)obj2).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)obj2).overflowMode = (TextOverflowModes)1;
			((Graphic)obj2).raycastTarget = false;
			val.SetActive(false);
			return obj2;
		}
	}
	public static class BoomboxPrefabBuilder
	{
		public const string ItemName = "Hachimi Boombox";

		public const string PrefabName = "Item Hachimi Boombox";

		private static bool registered;

		private static GameObject prefabContainer;

		public static Item RegisteredItem { get; private set; }

		public static void TryRegister()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			if (registered)
			{
				return;
			}
			if ((Object)(object)StatsManager.instance == (Object)null || StatsManager.instance.itemDictionary == null || StatsManager.instance.itemDictionary.Count == 0)
			{
				Plugin.Log.LogWarning((object)"StatsManager.instance.itemDictionary is not ready yet.");
				return;
			}
			Item val = FindTemplateItem(new List<Item>(StatsManager.instance.itemDictionary.Values).ToArray());
			if ((Object)(object)val == (Object)null || val.prefab == null || (Object)(object)((PrefabRef<GameObject>)(object)val.prefab).Prefab == (Object)null)
			{
				Plugin.Log.LogError((object)"Could not find a suitable vanilla Item template prefab to clone.");
				return;
			}
			prefabContainer = new GameObject("HJM_PrefabContainer");
			prefabContainer.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)prefabContainer);
			GameObject obj = Object.Instantiate<GameObject>(((PrefabRef<GameObject>)(object)val.prefab).Prefab, prefabContainer.transform);
			((Object)obj).name = "Item Hachimi Boombox";
			obj.SetActive(true);
			StripTemplateScripts(obj);
			SetupItemScriptableObject(obj, val);
			SetupToggleAndEquippable(obj);
			SetupBoomboxVisuals(obj, out var speaker, out var speaker2, out var light, out var light2);
			HachimiBoombox hachimiBoombox = obj.AddComponent<HachimiBoombox>();
			hachimiBoombox.speaker1 = speaker;
			hachimiBoombox.speaker2 = speaker2;
			hachimiBoombox.light1 = light;
			hachimiBoombox.light2 = light2;
			ItemAttributes component = obj.GetComponent<ItemAttributes>();
			if (Items.RegisterItem(component) != null)
			{
				registered = true;
				RegisteredItem = component.item;
				if (!StatsManager.instance.itemDictionary.ContainsKey(((Object)component.item).name))
				{
					StatsManager.instance.itemDictionary.Add(((Object)component.item).name, component.item);
				}
				Plugin.Log.LogInfo((object)string.Format("Registered '{0}' successfully (price: {1}).", "Hachimi Boombox", component.item.value.valueMin));
			}
			else
			{
				Plugin.Log.LogError((object)"Failed to register 'Hachimi Boombox' via REPOLib.");
			}
		}

		private static Item FindTemplateItem(Item[] items)
		{
			string[] array = new string[5] { "Item Tracker", "Item Valuable Tracker", "Item Extraction Tracker", "Item Walkie Talkie", "Item Rubber Duck" };
			Item[] array2;
			foreach (string value in array)
			{
				array2 = items;
				foreach (Item val in array2)
				{
					if ((Object)(object)val != (Object)null && val.prefab != null && (Object)(object)((PrefabRef<GameObject>)(object)val.prefab).Prefab != (Object)null && ((Object)val).name.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return val;
					}
				}
			}
			array2 = items;
			foreach (Item val2 in array2)
			{
				if ((Object)(object)val2 != (Object)null && val2.prefab != null && (Object)(object)((PrefabRef<GameObject>)(object)val2.prefab).Prefab != (Object)null && (Object)(object)((PrefabRef<GameObject>)(object)val2.prefab).Prefab.GetComponent<ItemEquippable>() != (Object)null)
				{
					return val2;
				}
			}
			return null;
		}

		private static void StripTemplateScripts(GameObject root)
		{
			Type[] array = new Type[8]
			{
				typeof(ItemTracker),
				typeof(ItemWalkieTalkie),
				typeof(ItemRubberDuck),
				typeof(ItemBattery),
				typeof(ItemLight),
				typeof(ItemHealthPack),
				typeof(ItemDrone),
				typeof(ItemOrb)
			};
			foreach (Type type in array)
			{
				Component[] componentsInChildren = root.GetComponentsInChildren(type, true);
				for (int j = 0; j < componentsInChildren.Length; j++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[j]);
				}
			}
			BatteryVisualLogic[] componentsInChildren2 = root.GetComponentsInChildren<BatteryVisualLogic>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)((Component)componentsInChildren2[i]).gameObject);
			}
		}

		private static void SetupItemScriptableObject(GameObject root, Item templateItem)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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)
			ItemAttributes component = root.GetComponent<ItemAttributes>();
			Item val = ScriptableObject.CreateInstance<Item>();
			((Object)val).name = "Item Hachimi Boombox";
			val.status = (Status)1;
			val.disabled = false;
			val.itemName = "Hachimi Boombox";
			val.itemNameLocalized = null;
			val.description = "基米音乐汇便携音响:支持放进物品栏继续播放,E键开关,R随机切歌,PgUp/PgDn顺序切歌,-/=调节音量。";
			val.itemType = (itemType)13;
			val.itemSecretShopType = (itemSecretShopType)1;
			val.emojiIcon = templateItem.emojiIcon;
			val.itemVolume = templateItem.itemVolume;
			val.colorPreset = templateItem.colorPreset;
			val.maxAmount = Plugin.ShopMaxAmount.Value;
			val.maxAmountInShop = Plugin.ShopMaxAmountInShop.Value;
			val.minPlayerCount = 1;
			val.maxPurchase = false;
			val.physicalItem = true;
			Value val2 = ScriptableObject.CreateInstance<Value>();
			val2.valueMin = Plugin.ShopPrice.Value;
			val2.valueMax = Plugin.ShopPrice.Value;
			val.value = val2;
			component.item = val;
			component.icon = null;
		}

		private static void SetupToggleAndEquippable(GameObject root)
		{
			ItemToggle val = root.GetComponent<ItemToggle>();
			if ((Object)(object)val == (Object)null)
			{
				val = root.AddComponent<ItemToggle>();
			}
			val.playSound = true;
			val.autoTurnOffWhenEquipped = false;
			if ((Object)(object)root.GetComponent<ItemEquippable>() == (Object)null)
			{
				root.AddComponent<ItemEquippable>();
			}
		}

		private static void SetupBoomboxVisuals(GameObject root, out Transform speaker1, out Transform speaker2, out Light light1, out Light light2)
		{
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Expected O, but got Unknown
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer[] componentsInChildren = root.GetComponentsInChildren<MeshRenderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Renderer)componentsInChildren[i]).enabled = false;
			}
			ValuableBoombox val = FindVanillaBoombox();
			if ((Object)(object)val != (Object)null)
			{
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, root.transform);
				((Object)val2).name = "BoomboxVisual";
				val2.transform.localPosition = Vector3.zero;
				val2.transform.localRotation = Quaternion.identity;
				val2.transform.localScale = Vector3.one * 0.48f;
				Collider[] componentsInChildren2 = val2.GetComponentsInChildren<Collider>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
				}
				Rigidbody[] componentsInChildren3 = val2.GetComponentsInChildren<Rigidbody>(true);
				for (int i = 0; i < componentsInChildren3.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
				}
				ValuableBoombox component = val2.GetComponent<ValuableBoombox>();
				speaker1 = (((Object)(object)component != (Object)null) ? component.speaker1 : null);
				speaker2 = (((Object)(object)component != (Object)null) ? component.speaker2 : null);
				light1 = (((Object)(object)component != (Object)null) ? component.light1 : null);
				light2 = (((Object)(object)component != (Object)null) ? component.light2 : null);
				MonoBehaviour[] componentsInChildren4 = val2.GetComponentsInChildren<MonoBehaviour>(true);
				for (int i = 0; i < componentsInChildren4.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren4[i]);
				}
				if ((Object)(object)speaker1 != (Object)null && (Object)(object)speaker2 != (Object)null && (Object)(object)light1 != (Object)null && (Object)(object)light2 != (Object)null)
				{
					return;
				}
			}
			GameObject val3 = new GameObject("BoomboxVisual");
			val3.transform.SetParent(root.transform, false);
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj).name = "Body";
			Object.DestroyImmediate((Object)(object)obj.GetComponent<Collider>());
			obj.transform.SetParent(val3.transform, false);
			obj.transform.localScale = new Vector3(0.42f, 0.22f, 0.16f);
			Material material = new Material(Shader.Find("Standard"))
			{
				color = new Color(0.14f, 0.16f, 0.2f)
			};
			obj.GetComponent<Renderer>().material = material;
			GameObject obj2 = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj2).name = "Handle";
			Object.DestroyImmediate((Object)(object)obj2.GetComponent<Collider>());
			obj2.transform.SetParent(val3.transform, false);
			obj2.transform.localPosition = new Vector3(0f, 0.14f, 0f);
			obj2.transform.localScale = new Vector3(0.24f, 0.03f, 0.04f);
			obj2.GetComponent<Renderer>().material = material;
			speaker1 = CreateSpeaker(val3.transform, "Speaker1", new Vector3(-0.11f, 0f, 0.082f), out light1);
			speaker2 = CreateSpeaker(val3.transform, "Speaker2", new Vector3(0.11f, 0f, 0.082f), out light2);
		}

		private static Transform CreateSpeaker(Transform parent, string name, Vector3 localPos, out Light light)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_007a: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive((PrimitiveType)2);
			((Object)val).name = name;
			Object.DestroyImmediate((Object)(object)val.GetComponent<Collider>());
			val.transform.SetParent(parent, false);
			val.transform.localPosition = localPos;
			val.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
			val.transform.localScale = new Vector3(0.13f, 0.015f, 0.13f);
			Material val2 = new Material(Shader.Find("Standard"))
			{
				color = new Color(0.9f, 0.25f, 0.7f)
			};
			val2.EnableKeyword("_EMISSION");
			val2.SetColor("_EmissionColor", Color.black);
			val.GetComponent<Renderer>().material = val2;
			GameObject val3 = new GameObject(name + "_Light");
			val3.transform.SetParent(val.transform, false);
			val3.transform.localPosition = new Vector3(0f, 0.5f, 0f);
			light = val3.AddComponent<Light>();
			light.type = (LightType)2;
			light.range = 3.5f;
			light.intensity = 0f;
			((Behaviour)light).enabled = false;
			return val.transform;
		}

		private static ValuableBoombox FindVanillaBoombox()
		{
			try
			{
				GameObject[] array = Resources.LoadAll<GameObject>("Valuables");
				foreach (GameObject val in array)
				{
					if (!((Object)(object)val == (Object)null))
					{
						ValuableBoombox componentInChildren = val.GetComponentInChildren<ValuableBoombox>(true);
						if ((Object)(object)componentInChildren != (Object)null)
						{
							return componentInChildren;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("FindVanillaBoombox fallback: " + ex.Message));
			}
			return null;
		}
	}
	public class HachimiBoombox : MonoBehaviourPunCallbacks
	{
		public static readonly List<HachimiBoombox> ActiveBoomboxes = new List<HachimiBoombox>();

		public Transform speaker1;

		public Transform speaker2;

		public Light light1;

		public Light light2;

		private PhysGrabObject physGrabObject;

		private ItemEquippable itemEquippable;

		private ItemToggle itemToggle;

		private GameObject audioHost;

		private AudioSource audioSource;

		private Vector3 speaker1BaseScale = Vector3.one;

		private Vector3 speaker2BaseScale = Vector3.one;

		private Material speaker1Mat;

		private Material speaker2Mat;

		private bool isPlaying;

		private int currentTrackIndex;

		private bool prevToggleState;

		private float trackStartTime;

		private bool waitingForClipLoad;

		private float boomboxVolume = 0.85f;

		public string CurrentTrackTitle
		{
			get
			{
				TrackEntry track = TrackLibrary.GetTrack(currentTrackIndex);
				if (track == null)
				{
					return string.Empty;
				}
				return track.Title;
			}
		}

		public bool IsPlaying => isPlaying;

		private void Awake()
		{
			//IL_008e: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			ActiveBoomboxes.Add(this);
			boomboxVolume = Mathf.Clamp(Plugin.Volume.Value, 0f, 2f);
			physGrabObject = ((Component)this).GetComponent<PhysGrabObject>();
			itemEquippable = ((Component)this).GetComponent<ItemEquippable>();
			itemToggle = ((Component)this).GetComponent<ItemToggle>();
			if ((Object)(object)itemToggle != (Object)null)
			{
				itemToggle.autoTurnOffWhenEquipped = false;
				prevToggleState = itemToggle.toggleState;
			}
			if ((Object)(object)speaker1 != (Object)null)
			{
				speaker1BaseScale = speaker1.localScale;
				Renderer component = ((Component)speaker1).GetComponent<Renderer>();
				if ((Object)(object)component != (Object)null)
				{
					speaker1Mat = component.material;
				}
			}
			if ((Object)(object)speaker2 != (Object)null)
			{
				speaker2BaseScale = speaker2.localScale;
				Renderer component2 = ((Component)speaker2).GetComponent<Renderer>();
				if ((Object)(object)component2 != (Object)null)
				{
					speaker2Mat = component2.material;
				}
			}
			if ((Object)(object)light1 != (Object)null)
			{
				((Behaviour)light1).enabled = false;
			}
			if ((Object)(object)light2 != (Object)null)
			{
				((Behaviour)light2).enabled = false;
			}
			CreateAudioHost();
		}

		private void CreateAudioHost()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			audioHost = new GameObject($"HachimiAudioHost_{((Object)this).GetInstanceID()}");
			audioSource = audioHost.AddComponent<AudioSource>();
			audioSource.playOnAwake = false;
			audioSource.loop = false;
			audioSource.spatialBlend = 1f;
			audioSource.rolloffMode = (AudioRolloffMode)1;
			audioSource.minDistance = 2.5f;
			audioSource.maxDistance = 24f;
			audioSource.dopplerLevel = 0f;
			if ((Object)(object)AudioManager.instance != (Object)null && (Object)(object)AudioManager.instance.SoundMasterGroup != (Object)null)
			{
				audioSource.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
			}
		}

		private void OnDestroy()
		{
			ActiveBoomboxes.Remove(this);
			if ((Object)(object)audioHost != (Object)null)
			{
				Object.Destroy((Object)(object)audioHost);
			}
		}

		private void Update()
		{
			if ((Object)(object)itemToggle != (Object)null && itemToggle.toggleState != prevToggleState)
			{
				prevToggleState = itemToggle.toggleState;
				OnToggleChanged(itemToggle.toggleState);
			}
			UpdateAudioHostPosition();
			UpdateAudioPlayback();
			UpdateVisualsAndHeadBob();
		}

		private void UpdateAudioHostPosition()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if ((Object)(object)audioHost == (Object)null)
			{
				return;
			}
			if ((Object)(object)itemEquippable != (Object)null && itemEquippable.IsEquipped())
			{
				PlayerAvatar ownerPlayerAvatar = itemEquippable.GetOwnerPlayerAvatar();
				if ((Object)(object)ownerPlayerAvatar != (Object)null)
				{
					audioHost.transform.position = ((Component)ownerPlayerAvatar).transform.position + Vector3.up * 1.1f;
					return;
				}
			}
			if ((Object)(object)physGrabObject != (Object)null)
			{
				audioHost.transform.position = physGrabObject.centerPoint;
			}
			else
			{
				audioHost.transform.position = ((Component)this).transform.position;
			}
		}

		private void UpdateAudioPlayback()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			audioSource.volume = Mathf.Clamp(boomboxVolume, 0f, 2f);
			if (!isPlaying)
			{
				if (audioSource.isPlaying)
				{
					audioSource.Stop();
				}
			}
			else
			{
				if (TrackLibrary.TrackCount == 0)
				{
					return;
				}
				if (waitingForClipLoad)
				{
					TrackEntry track = TrackLibrary.GetTrack(currentTrackIndex);
					if (track != null && (Object)(object)track.Clip != (Object)null)
					{
						waitingForClipLoad = false;
						PlayClip(track);
					}
				}
				else if ((Object)(object)audioSource.clip != (Object)null && !audioSource.isPlaying && Time.unscaledTime - trackStartTime > 0.5f && SemiFunc.IsMasterClientOrSingleplayer())
				{
					RequestSetTrack(TrackLibrary.WrapIndex(currentTrackIndex + 1));
				}
			}
		}

		private void UpdateVisualsAndHeadBob()
		{
			//IL_007f: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			bool flag = (Object)(object)physGrabObject != (Object)null && physGrabObject.grabbed;
			bool flag2 = (Object)(object)itemEquippable != (Object)null && itemEquippable.IsEquipped();
			if (isPlaying && flag && !flag2)
			{
				float num = 1f + Mathf.Sin(Time.time * 80f) * 0.025f;
				if ((Object)(object)speaker1 != (Object)null)
				{
					speaker1.localScale = speaker1BaseScale * num;
				}
				if ((Object)(object)speaker2 != (Object)null)
				{
					speaker2.localScale = speaker2BaseScale * num;
				}
				float num2 = Mathf.PingPong(Time.time * 0.5f, 1f);
				float num3 = 4f;
				if (SemiFunc.Photosensitivity())
				{
					num2 = 0.75f;
					num3 = 2f;
				}
				Color val = Color.HSVToRGB(num2, 1f, 1f);
				if ((Object)(object)speaker1Mat != (Object)null)
				{
					Color val2 = Color.Lerp(speaker1Mat.GetColor("_EmissionColor"), val, Time.deltaTime * 15f);
					speaker1Mat.SetColor("_EmissionColor", val2);
				}
				if ((Object)(object)speaker2Mat != (Object)null)
				{
					Color val3 = Color.Lerp(speaker2Mat.GetColor("_EmissionColor"), val, Time.deltaTime * 15f);
					speaker2Mat.SetColor("_EmissionColor", val3);
				}
				if ((Object)(object)light1 != (Object)null)
				{
					((Behaviour)light1).enabled = true;
					light1.color = val;
					light1.intensity = Mathf.Lerp(light1.intensity, num3, Time.deltaTime * 4f);
				}
				if ((Object)(object)light2 != (Object)null)
				{
					((Behaviour)light2).enabled = true;
					light2.color = val;
					light2.intensity = Mathf.Lerp(light2.intensity, num3, Time.deltaTime * 4f);
				}
				float num4 = Mathf.Sin(Time.time * 15f) * 0.5f;
				float num5 = Mathf.Sin(Time.time * 15f) * 25f;
				{
					foreach (PhysGrabber item in physGrabObject.playerGrabbing)
					{
						if ((Object)(object)item == (Object)null)
						{
							continue;
						}
						if (item.isLocal)
						{
							if ((Object)(object)CameraAim.Instance != (Object)null)
							{
								CameraAim.Instance.AdditiveAimY(num4);
							}
							item.OverrideGrabDistance(1f);
							item.OverrideDisableRotationControls();
							if ((Object)(object)item.playerAvatar != (Object)null && (Object)(object)item.playerAvatar.playerExpression != (Object)null)
							{
								item.playerAvatar.playerExpression.OverrideExpressionSet(4, 100f);
							}
							if ((Object)(object)PlayerExpressionsUI.instance != (Object)null)
							{
								if ((Object)(object)PlayerExpressionsUI.instance.playerExpression != (Object)null)
								{
									PlayerExpressionsUI.instance.playerExpression.OverrideExpressionSet(4, 100f);
								}
								if ((Object)(object)PlayerExpressionsUI.instance.playerAvatarVisuals != (Object)null)
								{
									PlayerExpressionsUI.instance.playerAvatarVisuals.HeadTiltOverride(num5 * 0.5f);
								}
							}
						}
						else if ((Object)(object)item.playerAvatar != (Object)null && (Object)(object)item.playerAvatar.playerAvatarVisuals != (Object)null)
						{
							item.playerAvatar.playerAvatarVisuals.HeadTiltOverride(num5);
						}
					}
					return;
				}
			}
			FadeOutLightsAndSpeakers();
		}

		private void FadeOutLightsAndSpeakers()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: 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)
			if ((Object)(object)speaker1 != (Object)null)
			{
				speaker1.localScale = Vector3.Lerp(speaker1.localScale, speaker1BaseScale, Time.deltaTime * 6f);
			}
			if ((Object)(object)speaker2 != (Object)null)
			{
				speaker2.localScale = Vector3.Lerp(speaker2.localScale, speaker2BaseScale, Time.deltaTime * 6f);
			}
			if ((Object)(object)speaker1Mat != (Object)null)
			{
				speaker1Mat.SetColor("_EmissionColor", Color.Lerp(speaker1Mat.GetColor("_EmissionColor"), Color.black, Time.deltaTime * 6f));
			}
			if ((Object)(object)speaker2Mat != (Object)null)
			{
				speaker2Mat.SetColor("_EmissionColor", Color.Lerp(speaker2Mat.GetColor("_EmissionColor"), Color.black, Time.deltaTime * 6f));
			}
			if ((Object)(object)light1 != (Object)null && ((Behaviour)light1).enabled)
			{
				light1.intensity = Mathf.Lerp(light1.intensity, 0f, Time.deltaTime * 6f);
				if (light1.intensity < 0.02f)
				{
					((Behaviour)light1).enabled = false;
				}
			}
			if ((Object)(object)light2 != (Object)null && ((Behaviour)light2).enabled)
			{
				light2.intensity = Mathf.Lerp(light2.intensity, 0f, Time.deltaTime * 6f);
				if (light2.intensity < 0.02f)
				{
					((Behaviour)light2).enabled = false;
				}
			}
		}

		private void OnToggleChanged(bool newState)
		{
			if (newState)
			{
				isPlaying = true;
				if (SemiFunc.IsMasterClientOrSingleplayer())
				{
					RequestSetTrack(currentTrackIndex);
				}
				else
				{
					PlayCurrentTrack(IsLocalRelevant());
				}
				return;
			}
			isPlaying = false;
			waitingForClipLoad = false;
			if ((Object)(object)audioSource != (Object)null)
			{
				audioSource.Stop();
			}
		}

		public override void OnPlayerEnteredRoom(Player newPlayer)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer() && (Object)(object)((MonoBehaviourPun)this).photonView != (Object)null && ((MonoBehaviourPun)this).photonView.ViewID != 0)
			{
				if (isPlaying)
				{
					float num = (((Object)(object)audioSource != (Object)null && audioSource.isPlaying) ? audioSource.time : 0f);
					((MonoBehaviourPun)this).photonView.RPC("RPC_SyncTrack", newPlayer, new object[4]
					{
						currentTrackIndex,
						TrackLibrary.CurrentSeed,
						num,
						boomboxVolume
					});
				}
				else
				{
					((MonoBehaviourPun)this).photonView.RPC("RPC_SetVolume", newPlayer, new object[1] { boomboxVolume });
				}
			}
		}

		public void RequestAdjustVolume(float delta)
		{
			float num = Mathf.Clamp(Mathf.Round((boomboxVolume + delta) * 10f) / 10f, 0f, 2f);
			if (GameManager.Multiplayer() && (Object)(object)((MonoBehaviourPun)this).photonView != (Object)null && ((MonoBehaviourPun)this).photonView.ViewID != 0)
			{
				((MonoBehaviourPun)this).photonView.RPC("RPC_SetVolume", (RpcTarget)0, new object[1] { num });
			}
			else
			{
				ApplyVolume(num);
			}
		}

		[PunRPC]
		private void RPC_SetVolume(float vol)
		{
			ApplyVolume(vol);
		}

		private void ApplyVolume(float vol)
		{
			boomboxVolume = Mathf.Clamp(vol, 0f, 2f);
			if ((Object)(object)audioSource != (Object)null)
			{
				audioSource.volume = boomboxVolume;
			}
			if (IsLocalRelevant())
			{
				BoomboxHud.ShowVolume(Mathf.RoundToInt(boomboxVolume * 100f));
			}
		}

		public void RequestNextTrack(int delta)
		{
			if (isPlaying && TrackLibrary.TrackCount != 0)
			{
				int trackIndex = TrackLibrary.WrapIndex(currentTrackIndex + delta);
				RequestSetTrack(trackIndex);
			}
		}

		public void RequestRandomTrack()
		{
			if (isPlaying && TrackLibrary.TrackCount != 0)
			{
				int randomIndex = TrackLibrary.GetRandomIndex(currentTrackIndex);
				RequestSetTrack(randomIndex);
			}
		}

		private void RequestSetTrack(int trackIndex)
		{
			if (GameManager.Multiplayer() && (Object)(object)((MonoBehaviourPun)this).photonView != (Object)null && ((MonoBehaviourPun)this).photonView.ViewID != 0)
			{
				((MonoBehaviourPun)this).photonView.RPC("RPC_SyncTrack", (RpcTarget)0, new object[4]
				{
					trackIndex,
					TrackLibrary.CurrentSeed,
					0f,
					boomboxVolume
				});
			}
			else
			{
				ApplyTrack(trackIndex, TrackLibrary.CurrentSeed, 0f, boomboxVolume);
			}
		}

		[PunRPC]
		private void RPC_SyncTrack(int trackIndex, int seed, float playbackTime, float volume)
		{
			ApplyTrack(trackIndex, seed, playbackTime, volume);
		}

		private void ApplyTrack(int trackIndex, int seed, float playbackTime, float volume)
		{
			boomboxVolume = Mathf.Clamp(volume, 0f, 2f);
			TrackLibrary.EnsureSeed(seed);
			currentTrackIndex = TrackLibrary.WrapIndex(trackIndex);
			if (isPlaying)
			{
				PlayCurrentTrack(IsLocalRelevant(), playbackTime);
			}
		}

		private void PlayCurrentTrack(bool showToast, float seekTime = 0f)
		{
			TrackEntry track = TrackLibrary.GetTrack(currentTrackIndex);
			if (track != null)
			{
				if ((Object)(object)track.Clip == (Object)null)
				{
					waitingForClipLoad = true;
				}
				else
				{
					PlayClip(track, seekTime);
				}
			}
		}

		private void PlayClip(TrackEntry entry, float seekTime = 0f)
		{
			if (!((Object)(object)audioSource == (Object)null) && !((Object)(object)entry.Clip == (Object)null))
			{
				audioSource.Stop();
				audioSource.clip = entry.Clip;
				if (seekTime > 0.1f && seekTime < entry.Clip.length)
				{
					audioSource.time = seekTime;
				}
				audioSource.Play();
				trackStartTime = Time.unscaledTime;
			}
		}

		public bool IsLocalHeld()
		{
			if ((Object)(object)physGrabObject == (Object)null || !physGrabObject.grabbed)
			{
				return false;
			}
			foreach (PhysGrabber item in physGrabObject.playerGrabbing)
			{
				if ((Object)(object)item != (Object)null && item.isLocal)
				{
					return true;
				}
			}
			return false;
		}

		public bool IsLocalOwnedInInventory()
		{
			if ((Object)(object)itemEquippable == (Object)null || !itemEquippable.IsEquipped())
			{
				return false;
			}
			PlayerAvatar ownerPlayerAvatar = itemEquippable.GetOwnerPlayerAvatar();
			if ((Object)(object)ownerPlayerAvatar != (Object)null)
			{
				return (Object)(object)ownerPlayerAvatar == (Object)(object)PlayerAvatar.instance;
			}
			return false;
		}

		public bool IsLocalRelevant()
		{
			if (!IsLocalHeld())
			{
				return IsLocalOwnedInInventory();
			}
			return true;
		}
	}
	[BepInPlugin("hjm.hachimimusic.repo", "HachimiMusic / 基米音乐汇", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(StatsManager), "LoadItemsFromFolder")]
			[HarmonyPostfix]
			private static void AfterLoadItems()
			{
				BoomboxPrefabBuilder.TryRegister();
			}

			[HarmonyPatch(typeof(StatsManager), "LoadGame", new Type[]
			{
				typeof(string),
				typeof(List<string>)
			})]
			[HarmonyPostfix]
			private static void OnLoadGame(StatsManager __instance)
			{
				if (SemiFunc.IsMasterClientOrSingleplayer() && GrantOneInSave.Value)
				{
					string text = "Item Hachimi Boombox";
					if (!__instance.itemsPurchased.TryGetValue(text, out var value) || value <= 0)
					{
						__instance.itemsPurchased[text] = 1;
						__instance.itemsPurchasedTotal[text] = Mathf.Max(__instance.itemsPurchasedTotal.GetValueOrDefault(text, 0), 1);
						Log.LogInfo((object)("Granted 1 '" + text + "' into the loaded save's truck."));
					}
					GrantOneInSave.Value = false;
				}
			}

			[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
			[HarmonyPostfix]
			private static void OnLevelChanged()
			{
				TrackLibrary.ReshuffleForRun();
			}
		}

		private static class SecretShopPatch
		{
			private static readonly MethodInfo SpawnShopItemMethod = AccessTools.Method(typeof(PunManager), "SpawnShopItem", (Type[])null, (Type[])null);

			[HarmonyTargetMethod]
			private static MethodBase TargetMethod()
			{
				MethodInfo[] methods = typeof(PunManager).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.Name == "ShopPopulateItemVolumes" && methodInfo.GetParameters().Length == 1)
					{
						return methodInfo;
					}
				}
				return null;
			}

			[HarmonyPrefix]
			private static void Prefix(PunManager __instance, object _spawns)
			{
				if (!SemiFunc.IsMasterClientOrSingleplayer() || (Object)(object)BoomboxPrefabBuilder.RegisteredItem == (Object)null || (Object)(object)ShopManager.instance == (Object)null || !ShopManager.instance.secretItemVolumes.TryGetValue((itemSecretShopType)1, out var value) || value == null || value.Count == 0)
				{
					return;
				}
				ItemVolume val = null;
				int index = -1;
				for (int i = 0; i < value.Count; i++)
				{
					if ((Object)(object)value[i] != (Object)null)
					{
						val = value[i];
						index = i;
						break;
					}
				}
				if (!((Object)(object)val == (Object)null) && !(SpawnShopItemMethod == null))
				{
					List<Item> list = new List<Item> { BoomboxPrefabBuilder.RegisteredItem };
					object[] parameters = new object[5] { val, list, 0, true, _spawns };
					if ((bool)SpawnShopItemMethod.Invoke(__instance, parameters))
					{
						value.RemoveAt(index);
						Object.Destroy((Object)(object)((Component)val).gameObject);
						Log.LogInfo((object)"Guaranteed Hachimi Boombox spawned in shop secret room (shop_attic).");
					}
				}
			}
		}

		public const string PluginGuid = "hjm.hachimimusic.repo";

		public const string PluginName = "HachimiMusic / 基米音乐汇";

		public const string PluginVersion = "1.0.0";

		private static readonly FieldInfo InputDisableTimerField = AccessTools.Field(typeof(PlayerController), "InputDisableTimer");

		private static readonly FieldInfo GrabbedObjectField = AccessTools.Field(typeof(PhysGrabber), "grabbedPhysGrabObject");

		private static readonly FieldInfo LookingAtObjectField = AccessTools.Field(typeof(PhysGrabber), "currentlyLookingAtPhysGrabObject");

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<KeyCode> KeyRandomTrack;

		internal static ConfigEntry<KeyCode> KeyPrevTrack;

		internal static ConfigEntry<KeyCode> KeyNextTrack;

		internal static ConfigEntry<KeyCode> KeyVolumeDown;

		internal static ConfigEntry<KeyCode> KeyVolumeUp;

		internal static ConfigEntry<float> Volume;

		internal static ConfigEntry<int> ShopPrice;

		internal static ConfigEntry<int> ShopMaxAmount;

		internal static ConfigEntry<int> ShopMaxAmountInShop;

		internal static ConfigEntry<bool> GrantOneInSave;

		internal static ConfigEntry<KeyCode> KeySpawnTest;

		private static string toastText;

		private static float toastUntil;

		private void Awake()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			KeyRandomTrack = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "RandomTrackKey", (KeyCode)114, "Key to switch to a random track.");
			KeyPrevTrack = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "PreviousTrackKey", (KeyCode)280, "Key to switch to the previous track in the playlist.");
			KeyNextTrack = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "NextTrackKey", (KeyCode)281, "Key to switch to the next track in the playlist.");
			KeyVolumeDown = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "VolumeDownKey", (KeyCode)45, "Key to decrease boombox volume.");
			KeyVolumeUp = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "VolumeUpKey", (KeyCode)61, "Key to increase boombox volume.");
			Volume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 0.85f, new ConfigDescription("Boombox playback volume (0.0 to 2.0).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			ShopPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "Price", 1000, "Price of the Hachimi Boombox in the shop.");
			ShopMaxAmount = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "MaxAmount", 3, "Maximum total Hachimi Boomboxes.");
			ShopMaxAmountInShop = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "MaxAmountInShop", 1, "Maximum Hachimi Boomboxes in the shop at once.");
			GrantOneInSave = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "GrantOneInSave", false, "If true, grants 1 Hachimi Boombox into your loaded save's truck once, then sets itself to false.");
			KeySpawnTest = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Testing", "SpawnTestKey", (KeyCode)290, "Host-only key to spawn a Hachimi Boombox in front of you for testing.");
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			TrackLibrary.Initialize((MonoBehaviour)(object)this, directoryName);
			Harmony val = new Harmony("hjm.hachimimusic.repo");
			val.PatchAll(typeof(Patches));
			val.PatchAll(typeof(SecretShopPatch));
			Log.LogInfo((object)"HachimiMusic / 基米音乐汇 v1.0.0 loaded.");
		}

		private void Update()
		{
			//IL_0040: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			BoomboxHud.UpdateHud();
			if (!((Object)(object)PlayerController.instance != (Object)null) || !(InputDisableTimerField != null) || !((float)InputDisableTimerField.GetValue(PlayerController.instance) > 0f))
			{
				if (Input.GetKeyDown(KeyRandomTrack.Value))
				{
					FindTargetBoombox()?.RequestRandomTrack();
				}
				else if (Input.GetKeyDown(KeyPrevTrack.Value))
				{
					FindTargetBoombox()?.RequestNextTrack(-1);
				}
				else if (Input.GetKeyDown(KeyNextTrack.Value))
				{
					FindTargetBoombox()?.RequestNextTrack(1);
				}
				else if (Input.GetKeyDown(KeyVolumeDown.Value))
				{
					FindTargetBoombox()?.RequestAdjustVolume(-0.1f);
				}
				else if (Input.GetKeyDown(KeyVolumeUp.Value))
				{
					FindTargetBoombox()?.RequestAdjustVolume(0.1f);
				}
				else if (Input.GetKeyDown(KeySpawnTest.Value) && SemiFunc.IsMasterClientOrSingleplayer() && (Object)(object)BoomboxPrefabBuilder.RegisteredItem != (Object)null && (Object)(object)Camera.main != (Object)null)
				{
					Vector3 val = ((Component)Camera.main).transform.position + ((Component)Camera.main).transform.forward * 1.2f;
					Items.SpawnItem(BoomboxPrefabBuilder.RegisteredItem, val, Quaternion.identity);
					ShowToast("已在前方生成一个 Hachimi Boombox");
				}
			}
		}

		private static HachimiBoombox FindTargetBoombox()
		{
			if ((Object)(object)PhysGrabber.instance != (Object)null)
			{
				object? obj = GrabbedObjectField?.GetValue(PhysGrabber.instance);
				PhysGrabObject val = (PhysGrabObject)((obj is PhysGrabObject) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					HachimiBoombox component = ((Component)val).GetComponent<HachimiBoombox>();
					if ((Object)(object)component != (Object)null)
					{
						return component;
					}
				}
				object? obj2 = LookingAtObjectField?.GetValue(PhysGrabber.instance);
				PhysGrabObject val2 = (PhysGrabObject)((obj2 is PhysGrabObject) ? obj2 : null);
				if ((Object)(object)val2 != (Object)null)
				{
					HachimiBoombox component2 = ((Component)val2).GetComponent<HachimiBoombox>();
					if ((Object)(object)component2 != (Object)null)
					{
						return component2;
					}
				}
			}
			foreach (HachimiBoombox activeBoombox in HachimiBoombox.ActiveBoomboxes)
			{
				if ((Object)(object)activeBoombox != (Object)null && activeBoombox.IsLocalOwnedInInventory() && activeBoombox.IsPlaying)
				{
					return activeBoombox;
				}
			}
			foreach (HachimiBoombox activeBoombox2 in HachimiBoombox.ActiveBoomboxes)
			{
				if ((Object)(object)activeBoombox2 != (Object)null && activeBoombox2.IsLocalOwnedInInventory())
				{
					return activeBoombox2;
				}
			}
			return null;
		}

		internal static void ShowToast(string message)
		{
			toastText = message;
			toastUntil = Time.unscaledTime + 3f;
		}

		private void OnGUI()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (!string.IsNullOrEmpty(toastText) && !(Time.unscaledTime > toastUntil))
			{
				GUI.Label(new Rect(20f, (float)(Screen.height - 40), 400f, 30f), toastText);
			}
		}
	}
	public sealed class TrackEntry
	{
		public string FilePath;

		public string FileName;

		public string Title;

		public AudioClip Clip;
	}
	public static class TrackLibrary
	{
		private static readonly List<TrackEntry> AllTracks = new List<TrackEntry>();

		private static readonly List<TrackEntry> ShuffledTracks = new List<TrackEntry>();

		private static readonly Dictionary<string, string> TitleMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static NetworkedEvent seedEvent;

		private static int currentSeed;

		private static bool hasSeed;

		private static bool loadingStarted;

		public static int CurrentSeed => currentSeed;

		public static bool IsLoaded { get; private set; }

		public static int TrackCount
		{
			get
			{
				if (ShuffledTracks.Count <= 0)
				{
					return AllTracks.Count;
				}
				return ShuffledTracks.Count;
			}
		}

		public static void Initialize(MonoBehaviour runner, string pluginDir)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (loadingStarted)
			{
				return;
			}
			loadingStarted = true;
			seedEvent = new NetworkedEvent("HJM_HachimiMusic_Seed", (Action<EventData>)OnSeedEventReceived);
			LoadTrackTitles(Path.Combine(pluginDir, "tracks.json"));
			string text = Path.Combine(pluginDir, "CustomBoomboxMusic");
			if (!Directory.Exists(text))
			{
				Plugin.Log.LogWarning((object)("CustomBoomboxMusic directory not found: " + text));
				IsLoaded = true;
				return;
			}
			string[] files = Directory.GetFiles(text, "*.ogg", SearchOption.TopDirectoryOnly);
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			string[] array = files;
			foreach (string text2 in array)
			{
				string fileName = Path.GetFileName(text2);
				string value;
				string title = ((TitleMap.TryGetValue(fileName, out value) && !string.IsNullOrWhiteSpace(value)) ? value : Path.GetFileNameWithoutExtension(text2));
				AllTracks.Add(new TrackEntry
				{
					FilePath = text2,
					FileName = fileName,
					Title = title
				});
			}
			ApplySeed(Environment.TickCount);
			Plugin.Log.LogInfo((object)$"Found {AllTracks.Count} .ogg tracks in CustomBoomboxMusic.");
			runner.StartCoroutine(LoadAllClipsCoroutine());
		}

		private static void LoadTrackTitles(string jsonPath)
		{
			if (!File.Exists(jsonPath))
			{
				return;
			}
			try
			{
				foreach (Match item in Regex.Matches(File.ReadAllText(jsonPath), "\\{[^{}]*\\}", RegexOptions.Singleline))
				{
					Match match = Regex.Match(item.Value, "\"title\"\\s*:\\s*\"((?:\\\\.|[^\"])*)\"");
					Match match2 = Regex.Match(item.Value, "\"file\"\\s*:\\s*\"((?:\\\\.|[^\"])*)\"");
					if (match.Success && match2.Success)
					{
						string key = Regex.Unescape(match2.Groups[1].Value);
						string value = Regex.Unescape(match.Groups[1].Value);
						TitleMap[key] = value;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to parse tracks.json: " + ex.Message));
			}
		}

		private static IEnumerator LoadAllClipsCoroutine()
		{
			foreach (TrackEntry entry in AllTracks)
			{
				string absoluteUri = new Uri(entry.FilePath).AbsoluteUri;
				UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip(absoluteUri, (AudioType)14);
				try
				{
					yield return req.SendWebRequest();
					if ((int)req.result == 1)
					{
						AudioClip content = DownloadHandlerAudioClip.GetContent(req);
						if ((Object)(object)content != (Object)null)
						{
							((Object)content).name = entry.Title;
							entry.Clip = content;
						}
					}
					else
					{
						Plugin.Log.LogWarning((object)("Failed to load track '" + entry.FileName + "': " + req.error));
					}
				}
				finally
				{
					((IDisposable)req)?.Dispose();
				}
			}
			IsLoaded = true;
			Plugin.Log.LogInfo((object)$"Finished loading audio clips ({AllTracks.FindAll((TrackEntry t) => (Object)(object)t.Clip != (Object)null).Count}/{AllTracks.Count} ready).");
		}

		public static void ReshuffleForRun()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (AllTracks.Count != 0 && SemiFunc.IsMasterClientOrSingleplayer())
			{
				int hashCode = Guid.NewGuid().GetHashCode();
				ApplySeed(hashCode);
				if (GameManager.Multiplayer() && seedEvent != null)
				{
					seedEvent.RaiseEvent((object)hashCode, NetworkingEvents.RaiseOthers, SendOptions.SendReliable);
				}
			}
		}

		private static void OnSeedEventReceived(EventData data)
		{
			if (data.CustomData is int seed)
			{
				ApplySeed(seed);
			}
		}

		public static void EnsureSeed(int seed)
		{
			if (!hasSeed || currentSeed != seed)
			{
				ApplySeed(seed);
			}
		}

		private static void ApplySeed(int seed)
		{
			currentSeed = seed;
			hasSeed = true;
			ShuffledTracks.Clear();
			ShuffledTracks.AddRange(AllTracks);
			Random random = new Random(currentSeed);
			for (int num = ShuffledTracks.Count - 1; num > 0; num--)
			{
				int num2 = random.Next(num + 1);
				List<TrackEntry> shuffledTracks = ShuffledTracks;
				int index = num;
				List<TrackEntry> shuffledTracks2 = ShuffledTracks;
				int index2 = num2;
				TrackEntry value = ShuffledTracks[num2];
				TrackEntry value2 = ShuffledTracks[num];
				shuffledTracks[index] = value;
				shuffledTracks2[index2] = value2;
			}
		}

		public static TrackEntry GetTrack(int index)
		{
			if (ShuffledTracks.Count == 0)
			{
				return null;
			}
			int index2 = (index % ShuffledTracks.Count + ShuffledTracks.Count) % ShuffledTracks.Count;
			return ShuffledTracks[index2];
		}

		public static int WrapIndex(int index)
		{
			if (ShuffledTracks.Count == 0)
			{
				return 0;
			}
			return (index % ShuffledTracks.Count + ShuffledTracks.Count) % ShuffledTracks.Count;
		}

		public static int GetRandomIndex(int excludeIndex)
		{
			if (ShuffledTracks.Count <= 1)
			{
				return 0;
			}
			int num;
			do
			{
				num = Random.Range(0, ShuffledTracks.Count);
			}
			while (num == excludeIndex);
			return num;
		}
	}
}