Decompiled source of MusicPlaylists v1.6.0

MusicPlaylists.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ModHub;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MusicPlaylists")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.6.0.0")]
[assembly: AssemblyInformationalVersion("1.6.0")]
[assembly: AssemblyProduct("MusicPlaylists")]
[assembly: AssemblyTitle("MusicPlaylists")]
[assembly: AssemblyVersion("1.6.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MusicPlaylists
{
	public static class AudioCache
	{
		private static readonly Dictionary<string, AudioClip> _clips = new Dictionary<string, AudioClip>();

		private static readonly HashSet<string> _loading = new HashSet<string>();

		private static readonly HashSet<string> _failed = new HashSet<string>();

		public static int Version { get; private set; }

		public static AudioClip Get(string name)
		{
			AudioClip value;
			return (name != null && _clips.TryGetValue(name, out value) && (Object)(object)value != (Object)null) ? value : null;
		}

		public static bool IsLoading(string name)
		{
			return _loading.Contains(name);
		}

		public static bool IsFailed(string name)
		{
			return _failed.Contains(name);
		}

		public static bool IsLoaded(string name)
		{
			return (Object)(object)Get(name) != (Object)null;
		}

		public static void Request(string name)
		{
			if (!string.IsNullOrEmpty(name) && !IsLoaded(name) && !_loading.Contains(name) && !_failed.Contains(name) && !((Object)(object)Plugin.Instance == (Object)null))
			{
				_loading.Add(name);
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Load(name));
			}
		}

		public static void Retry(string name)
		{
			_failed.Remove(name);
		}

		public static void Unload(string name)
		{
			if (_clips.TryGetValue(name, out var value))
			{
				_clips.Remove(name);
				if ((Object)(object)value != (Object)null)
				{
					value.UnloadAudioData();
					Object.Destroy((Object)(object)value);
				}
			}
			_failed.Remove(name);
		}

		public static void Retain(HashSet<string> keep)
		{
			List<string> list = new List<string>();
			foreach (string key in _clips.Keys)
			{
				if (!keep.Contains(key))
				{
					list.Add(key);
				}
			}
			foreach (string item in list)
			{
				Unload(item);
			}
		}

		private static AudioType TypeOf(string name)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			return (AudioType)(Path.GetExtension(name).ToLowerInvariant() switch
			{
				".ogg" => 14, 
				".wav" => 20, 
				".mp3" => 13, 
				_ => 0, 
			});
		}

		private static IEnumerator Load(string name)
		{
			string path = Storage.FullPath(name);
			if (!File.Exists(path))
			{
				Done(name, null, "file not found");
				yield break;
			}
			string uri;
			try
			{
				uri = new Uri(path).AbsoluteUri;
			}
			catch (Exception ex)
			{
				Exception e = ex;
				Done(name, null, e.Message);
				yield break;
			}
			UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip(uri, TypeOf(name));
			try
			{
				DownloadHandler downloadHandler = req.downloadHandler;
				DownloadHandlerAudioClip dh = (DownloadHandlerAudioClip)(object)((downloadHandler is DownloadHandlerAudioClip) ? downloadHandler : null);
				if (dh != null)
				{
					dh.compressed = true;
					dh.streamAudio = false;
				}
				yield return req.SendWebRequest();
				if ((int)req.result != 1)
				{
					Done(name, null, req.error);
					yield break;
				}
				AudioClip clip;
				try
				{
					clip = DownloadHandlerAudioClip.GetContent(req);
				}
				catch (Exception ex2)
				{
					Done(name, null, ex2.Message);
					yield break;
				}
				if ((Object)(object)clip == (Object)null || clip.length <= 0.1f)
				{
					Done(name, null, "unsupported or empty audio");
					yield break;
				}
				((Object)clip).name = Path.GetFileNameWithoutExtension(name);
				Done(name, clip, null);
			}
			finally
			{
				((IDisposable)req)?.Dispose();
			}
		}

		private static void Done(string name, AudioClip clip, string error)
		{
			_loading.Remove(name);
			if ((Object)(object)clip != (Object)null)
			{
				_clips[name] = clip;
			}
			else
			{
				_failed.Add(name);
				Plugin.Warn("Cannot load '" + name + "': " + error);
			}
			Version++;
		}
	}
	public static class Loc
	{
		private enum Lang
		{
			En,
			Ru,
			Uk
		}

		public enum Category
		{
			Menu,
			Biome,
			Combat,
			Other
		}

		private static readonly Dictionary<string, string[]> S = new Dictionary<string, string[]>
		{
			{
				"title",
				new string[3] { "MUSIC", "МУЗЫКА", "МУЗИКА" }
			},
			{
				"general",
				new string[3] { "General settings", "Общие настройки", "Загальні налаштування" }
			},
			{
				"library",
				new string[3] { "Library", "Библиотека", "Бібліотека" }
			},
			{
				"pick_biome",
				new string[3] { "Pick a biome on the left to build its playlist.", "Выбери биом слева, чтобы собрать для него плейлист.", "Обери біом ліворуч, щоб зібрати для нього плейлист." }
			},
			{
				"biomes",
				new string[3] { "Biomes", "Биомы", "Біоми" }
			},
			{
				"you_are_here",
				new string[3] { "you are here", "ты здесь", "ти тут" }
			},
			{
				"replaces",
				new string[3] { "Silences game music:", "Глушит музыку игры:", "Глушить музику гри:" }
			},
			{
				"slots_later",
				new string[3] { "(the list fills in once you enter a world)", "(список заполнится, когда зайдёшь в мир)", "(список заповниться, коли зайдеш у світ)" }
			},
			{
				"biome_hint",
				new string[3] { "Starts by itself when you enter the biome, like vanilla music, and keeps playing while you are there. The game's own biome music stays quiet. Combat, bosses and raids stay vanilla: your track pauses and comes back after the fight.", "Включается сама, когда заходишь в биом, как ванильная музыка, и играет, пока ты там. Музыка биома из игры молчит. Бои, боссы и набеги остаются ванильными: твой трек встаёт на паузу и возвращается после боя.", "Вмикається сама, коли заходиш у біом, як ванільна музика, і грає, поки ти там. Музика біому з гри мовчить. Бої, боси й набіги лишаються ванільними: твій трек стає на паузу і повертається після бою." }
			},
			{
				"mod_enabled",
				new string[3] { "Mod enabled", "Мод включён", "Мод увімкнено" }
			},
			{
				"show_name",
				new string[3] { "Show track name when it starts", "Показывать название трека при старте", "Показувати назву треку на старті" }
			},
			{
				"fade_in",
				new string[3] { "Smooth start", "Плавное начало", "Плавний початок" }
			},
			{
				"fade_out",
				new string[3] { "Fade-out at the end", "Затухание в конце", "Згасання в кінці" }
			},
			{
				"off",
				new string[3] { "off", "выкл", "вимк" }
			},
			{
				"sec",
				new string[3] { "s", "с", "с" }
			},
			{
				"switch_now",
				new string[3] { "Change music right away when the place changes (base, biome, dungeon)", "Сразу менять музыку при смене места (база, биом, подземелье)", "Одразу змінювати музику при зміні місця (база, біом, підземелля)" }
			},
			{
				"switch_fade",
				new string[3] { "Fade when switching", "Затухание при смене", "Згасання при зміні" }
			},
			{
				"volume_game",
				new string[3] { "Volume follows the game's Music slider (Settings → Audio).", "Громкость берётся из ползунка «Музыка» в настройках игры (Настройки → Звук).", "Гучність береться з повзунка «Музика» в налаштуваннях гри (Налаштування → Звук)." }
			},
			{
				"duck_others",
				new string[3] { "Play over other music mods (Music Overhaul and the like)", "Играть поверх музыки других модов (Music Overhaul и подобных)", "Грати поверх музики інших модів (Music Overhaul і подібних)" }
			},
			{
				"mod_off_warn",
				new string[3] { "The mod is switched off in General settings: nothing plays.", "Мод выключен в общих настройках: музыка не играет.", "Мод вимкнено в загальних налаштуваннях: музика не грає." }
			},
			{
				"mod_turn_on",
				new string[3] { "Turn the mod on", "Включить мод", "Увімкнути мод" }
			},
			{
				"mod_turned_on",
				new string[3] { "The mod is on.", "Мод включён.", "Мод увімкнено." }
			},
			{
				"track_vol",
				new string[3] { "Track volume", "Громкость трека", "Гучність треку" }
			},
			{
				"pause_len",
				new string[3] { "Pause between tracks (when \"No pauses\" is off)", "Пауза между треками (если «Без пауз» выключено)", "Пауза між треками (якщо «Без пауз» вимкнено)" }
			},
			{
				"storage_info",
				new string[3] { "Your music is copied into the mod's own folder. If the original file is deleted or moved, the copy stays and keeps playing. The folder is outside the plugin folder, so mod updates do not touch it.", "Музыка копируется в собственную папку мода. Если оригинал удалят или перенесут, копия останется и продолжит играть. Папка лежит вне папки плагина, поэтому обновления мода её не трогают.", "Музика копіюється у власну теку мода. Якщо оригінал видалять або перенесуть, копія залишиться і гратиме далі. Тека лежить поза текою плагіна, тож оновлення мода її не чіпають." }
			},
			{
				"folder",
				new string[3] { "Folder:", "Папка:", "Тека:" }
			},
			{
				"own_music",
				new string[3] { "My playlist on", "Свой плейлист включён", "Свій плейлист увімкнено" }
			},
			{
				"shuffle",
				new string[3] { "Shuffle", "Перемешивать", "Перемішувати" }
			},
			{
				"continuous",
				new string[3] { "No pauses (next track right away)", "Без пауз (следующий трек сразу)", "Без пауз (наступний трек одразу)" }
			},
			{
				"tracks",
				new string[3] { "Tracks", "Треки", "Треки" }
			},
			{
				"no_tracks",
				new string[3] { "No tracks yet: vanilla music plays here.", "Треков пока нет: здесь играет ванильная музыка.", "Треків поки немає: тут грає ванільна музика." }
			},
			{
				"add_path",
				new string[3] { "File or folder path (Ctrl+V)", "Путь к файлу или папке (Ctrl+V)", "Шлях до файлу або теки (Ctrl+V)" }
			},
			{
				"add",
				new string[3] { "Add", "Добавить", "Додати" }
			},
			{
				"from_library",
				new string[3] { "+ From library", "+ Из библиотеки", "+ З бібліотеки" }
			},
			{
				"back_tracks",
				new string[3] { "< Back to tracks", "< Назад к трекам", "< Назад до треків" }
			},
			{
				"in_playlist",
				new string[3] { "in playlist", "уже в плейлисте", "вже в плейлисті" }
			},
			{
				"import",
				new string[3] { "Import", "Импорт", "Імпорт" }
			},
			{
				"take_import",
				new string[3] { "Take from Import folder", "Забрать из папки Import", "Забрати з теки Import" }
			},
			{
				"open_lib",
				new string[3] { "Open Library folder", "Открыть папку библиотеки", "Відкрити теку бібліотеки" }
			},
			{
				"open_import",
				new string[3] { "Open Import folder", "Открыть папку Import", "Відкрити теку Import" }
			},
			{
				"lib_empty",
				new string[3] { "The library is empty. Paste a path above or drop files into the Import folder.", "Библиотека пуста. Вставь путь выше или кинь файлы в папку Import.", "Бібліотека порожня. Встав шлях вище або закинь файли в теку Import." }
			},
			{
				"used_in",
				new string[3] { "playlists", "плейл.", "плейл." }
			},
			{
				"confirm_del",
				new string[3] { "Click again to delete", "Ещё раз, чтобы удалить", "Ще раз, щоб видалити" }
			},
			{
				"loading",
				new string[3] { "loading...", "загрузка...", "завантаження..." }
			},
			{
				"failed",
				new string[3] { "cannot play", "не играет", "не грає" }
			},
			{
				"missing",
				new string[3] { "file missing", "файла нет", "файлу немає" }
			},
			{
				"imported",
				new string[3] { "Imported: {0}", "Импортировано: {0}", "Імпортовано: {0}" }
			},
			{
				"added",
				new string[3] { "Added to playlist: {0}", "Добавлено в плейлист: {0}", "Додано в плейлист: {0}" }
			},
			{
				"err_empty",
				new string[3] { "Paste a path first.", "Сначала вставь путь.", "Спершу встав шлях." }
			},
			{
				"err_notfound",
				new string[3] { "Nothing found at this path.", "По этому пути ничего нет.", "За цим шляхом нічого немає." }
			},
			{
				"err_format",
				new string[3] { "Only .ogg, .wav and .mp3 are supported.", "Поддерживаются только .ogg, .wav и .mp3.", "Підтримуються лише .ogg, .wav і .mp3." }
			},
			{
				"err_noaudio",
				new string[3] { "No .ogg / .wav / .mp3 in this folder.", "В папке нет .ogg / .wav / .mp3.", "У теці немає .ogg / .wav / .mp3." }
			},
			{
				"err_other",
				new string[3] { "Import failed: {0}", "Не удалось импортировать: {0}", "Не вдалося імпортувати: {0}" }
			},
			{
				"import_none",
				new string[3] { "The Import folder is empty.", "Папка Import пуста.", "Тека Import порожня." }
			},
			{
				"deleted",
				new string[3] { "Deleted from library: {0}", "Удалено из библиотеки: {0}", "Видалено з бібліотеки: {0}" }
			},
			{
				"applied",
				new string[3] { "Saved.", "Сохранено.", "Збережено." }
			},
			{
				"reverted",
				new string[3] { "Changes undone.", "Изменения отменены.", "Зміни скасовано." }
			},
			{
				"vanilla_done",
				new string[3] { "All biomes switched to vanilla music (playlists and library kept). Press Apply.", "Все биомы переключены на ванильную музыку (плейлисты и библиотека сохранены). Нажми «Применить».", "Усі біоми переключено на ванільну музику (плейлисти й бібліотеку збережено). Натисни «Застосувати»." }
			},
			{
				"btn_vanilla",
				new string[3] { "All vanilla", "Всё как в ванилле", "Усе як у ванілі" }
			},
			{
				"btn_cancel",
				new string[3] { "Cancel", "Отменить", "Скасувати" }
			},
			{
				"btn_apply",
				new string[3] { "Apply", "Применить", "Застосувати" }
			},
			{
				"now_playing",
				new string[3] { "Now playing", "Сейчас играет", "Зараз грає" }
			},
			{
				"playing_here",
				new string[3] { "playing now", "играет сейчас", "грає зараз" }
			},
			{
				"m_menu",
				new string[3] { "Main menu", "Главное меню", "Головне меню" }
			},
			{
				"m_intro",
				new string[3] { "Intro", "Вступление", "Вступ" }
			},
			{
				"m_credits",
				new string[3] { "Credits", "Титры", "Титри" }
			},
			{
				"m_combat",
				new string[3] { "Combat", "Бой", "Бій" }
			},
			{
				"m_boss",
				new string[3] { "Boss", "Босс", "Бос" }
			},
			{
				"m_event",
				new string[3] { "Raid", "Набег", "Набіг" }
			},
			{
				"m_home",
				new string[3] { "Home / base", "Дом / база", "Дім / база" }
			},
			{
				"m_sailing",
				new string[3] { "Sailing", "Плавание", "Плавання" }
			},
			{
				"m_respawn",
				new string[3] { "Respawn", "Возрождение", "Відродження" }
			},
			{
				"m_dungeon",
				new string[3] { "Dungeon", "Подземелье", "Підземелля" }
			},
			{
				"m_trader",
				new string[3] { "Trader", "Торговец", "Торговець" }
			},
			{
				"m_sleep",
				new string[3] { "Sleep", "Сон", "Сон" }
			},
			{
				"b_meadows",
				new string[3] { "Meadows", "Луга", "Луки" }
			},
			{
				"b_forest",
				new string[3] { "Black Forest", "Чёрный лес", "Чорний ліс" }
			},
			{
				"b_swamp",
				new string[3] { "Swamp", "Болото", "Болото" }
			},
			{
				"b_mountain",
				new string[3] { "Mountains", "Горы", "Гори" }
			},
			{
				"b_plains",
				new string[3] { "Plains", "Равнины", "Рівнини" }
			},
			{
				"b_mist",
				new string[3] { "Mistlands", "Туманные земли", "Туманні землі" }
			},
			{
				"b_ash",
				new string[3] { "Ashlands", "Пепельные земли", "Попелясті землі" }
			},
			{
				"b_north",
				new string[3] { "Deep North", "Глубокий север", "Глибока північ" }
			},
			{
				"b_ocean",
				new string[3] { "Ocean", "Океан", "Океан" }
			},
			{
				"b_home",
				new string[3] { "Home / base", "Дом / база", "Дім / база" }
			},
			{
				"b_dungeon",
				new string[3] { "Dungeons", "Подземелья", "Підземелля" }
			},
			{
				"special",
				new string[3] { "Special", "Особые", "Особливі" }
			},
			{
				"home_hint",
				new string[3] { "Plays while you are inside your house: under a roof (the game's Shelter status) at your base. Step outside and the biome music comes back. Takes priority over the biome. Combat and raids stay vanilla.", "Играет, пока ты в доме: под крышей (статус «Укрытие») на своей базе. Вышел из дома, и снова играет музыка биома. Важнее музыки биома. Бои и набеги остаются ванильными.", "Грає, поки ти в домі: під дахом (статус «Укриття») на своїй базі. Вийшов з дому, і знову грає музика біому. Важливіша за музику біому. Бої та набіги лишаються ванільними." }
			},
			{
				"dungeon_hint",
				new string[3] { "Starts by itself when you enter any dungeon: crypts, caves, mines and the rest. Takes priority over home and biome. Bosses stay vanilla.", "Включается сама, когда заходишь в любое подземелье: склепы, пещеры, шахты и остальное. Важнее дома и биома. Боссы остаются ванильными.", "Вмикається сама, коли заходиш у будь-яке підземелля: склепи, печери, шахти та інше. Важливіша за дім і біом. Боси лишаються ванільними." }
			},
			{
				"t_morning",
				new string[3] { "morning", "утро", "ранок" }
			},
			{
				"t_day",
				new string[3] { "day", "день", "день" }
			},
			{
				"t_evening",
				new string[3] { "evening", "вечер", "вечір" }
			},
			{
				"t_night",
				new string[3] { "night", "ночь", "ніч" }
			},
			{
				"boss_eikthyr",
				new string[3] { "Eikthyr", "Эйктюр", "Ейктюр" }
			},
			{
				"boss_elder",
				new string[3] { "The Elder", "Древний", "Древній" }
			},
			{
				"boss_bonemass",
				new string[3] { "Bonemass", "Масса костей", "Маса кісток" }
			},
			{
				"boss_moder",
				new string[3] { "Moder", "Модер", "Модер" }
			},
			{
				"boss_yagluth",
				new string[3] { "Yagluth", "Яглут", "Яглут" }
			},
			{
				"boss_queen",
				new string[3] { "The Queen", "Королева", "Королева" }
			},
			{
				"boss_fader",
				new string[3] { "Fader", "Фейдер", "Фейдер" }
			}
		};

		private static readonly string[][] BossKeys = new string[11][]
		{
			new string[2] { "eikthyr", "boss_eikthyr" },
			new string[2] { "gdking", "boss_elder" },
			new string[2] { "elder", "boss_elder" },
			new string[2] { "bonemass", "boss_bonemass" },
			new string[2] { "moder", "boss_moder" },
			new string[2] { "dragon", "boss_moder" },
			new string[2] { "goblinking", "boss_yagluth" },
			new string[2] { "yagluth", "boss_yagluth" },
			new string[2] { "seekerqueen", "boss_queen" },
			new string[2] { "queen", "boss_queen" },
			new string[2] { "fader", "boss_fader" }
		};

		private static readonly string[][] BiomeKeys = new string[13][]
		{
			new string[2] { "meadows", "b_meadows" },
			new string[2] { "blackforest", "b_forest" },
			new string[2] { "forest", "b_forest" },
			new string[2] { "swamp", "b_swamp" },
			new string[2] { "mountain", "b_mountain" },
			new string[2] { "plains", "b_plains" },
			new string[2] { "mistlands", "b_mist" },
			new string[2] { "mist", "b_mist" },
			new string[2] { "ashlands", "b_ash" },
			new string[2] { "ash", "b_ash" },
			new string[2] { "deepnorth", "b_north" },
			new string[2] { "north", "b_north" },
			new string[2] { "ocean", "b_ocean" }
		};

		private static readonly Dictionary<string, string> BiomeLoc = new Dictionary<string, string>
		{
			{ "Meadows", "b_meadows" },
			{ "BlackForest", "b_forest" },
			{ "Swamp", "b_swamp" },
			{ "Mountain", "b_mountain" },
			{ "Plains", "b_plains" },
			{ "Mistlands", "b_mist" },
			{ "AshLands", "b_ash" },
			{ "DeepNorth", "b_north" },
			{ "Ocean", "b_ocean" },
			{ "Home", "b_home" },
			{ "Dungeon", "b_dungeon" }
		};

		private static readonly string[] DungeonWords = new string[10] { "crypt", "cave", "dungeon", "mine", "tomb", "vault", "interior", "infected", "sunken", "morgen" };

		private static Lang Current
		{
			get
			{
				string text = null;
				try
				{
					Localization instance = Localization.instance;
					text = ((instance != null) ? instance.GetSelectedLanguage() : null);
				}
				catch
				{
				}
				if (text == "Russian")
				{
					return Lang.Ru;
				}
				if (text == "Ukrainian")
				{
					return Lang.Uk;
				}
				return Lang.En;
			}
		}

		public static string T(string key)
		{
			if (!S.TryGetValue(key, out var value))
			{
				return key;
			}
			return value[(int)Current];
		}

		public static string F(string key, object arg)
		{
			return string.Format(T(key), arg);
		}

		private static string Match(string low, string[][] table)
		{
			foreach (string[] array in table)
			{
				if (low.Contains(array[0]))
				{
					return array[1];
				}
			}
			return null;
		}

		public static Category CategoryOf(string raw)
		{
			string text = (raw ?? "").ToLowerInvariant();
			if (text.Contains("menu") || text.Contains("intro") || text.Contains("credits"))
			{
				return Category.Menu;
			}
			if (text.Contains("boss") || text.Contains("combat") || text.Contains("event") || text.Contains("raid") || text.Contains("army") || Match(text, BossKeys) != null)
			{
				return Category.Combat;
			}
			if (IsDungeonWord(text) || text.Contains("home"))
			{
				return Category.Other;
			}
			if (Match(text, BiomeKeys) != null)
			{
				return Category.Biome;
			}
			return Category.Other;
		}

		public static string BiomeName(string biome)
		{
			string value;
			return (biome != null && BiomeLoc.TryGetValue(biome, out value)) ? T(value) : biome;
		}

		public static bool IsDungeonWord(string low)
		{
			string[] dungeonWords = DungeonWords;
			foreach (string value in dungeonWords)
			{
				if (low.Contains(value))
				{
					return true;
				}
			}
			return false;
		}

		public static string BiomeFromSlot(string slot)
		{
			string text = Match((slot ?? "").ToLowerInvariant(), BiomeKeys);
			if (text == null)
			{
				return null;
			}
			foreach (KeyValuePair<string, string> item in BiomeLoc)
			{
				if (item.Value == text)
				{
					return item.Key;
				}
			}
			return null;
		}

		public static string TimeOfSlot(string slot)
		{
			string text = (slot ?? "").ToLowerInvariant();
			if (text.Contains("morning"))
			{
				return T("t_morning");
			}
			if (text.Contains("evening"))
			{
				return T("t_evening");
			}
			if (text.Contains("night"))
			{
				return T("t_night");
			}
			if (text.Contains("day"))
			{
				return T("t_day");
			}
			return "";
		}
	}
	public static class MusicDriver
	{
		private class Order
		{
			public List<string> Tracks = new List<string>();

			public int Pos;

			public string Signature;
		}

		private class DuckState
		{
			public bool Written;

			public float Base;

			public float Value;

			public bool Muted;
		}

		public static readonly string[] Biomes = new string[11]
		{
			"Meadows", "BlackForest", "Swamp", "Mountain", "Plains", "Mistlands", "AshLands", "DeepNorth", "Ocean", "Home",
			"Dungeon"
		};

		public const string Home = "Home";

		public const string Dungeon = "Dungeon";

		private static MusicMan _bound;

		private static Object _mappedEnv;

		private static bool _mapped;

		private static readonly Dictionary<string, List<string>> _biomeSlots = new Dictionary<string, List<string>>();

		private static string _currentBiome;

		private static bool _inDungeon;

		private static bool _atHome;

		private static float _nextBiomeCheck;

		private static bool _dirty = true;

		private static int _appliedCacheVersion = -1;

		private static AudioSource _src;

		private static string _playingKey;

		private static string _playingTrack;

		private static bool _paused;

		private static float _fade;

		private static float _lastTime;

		private static string _gapKey;

		private static float _gapUntil;

		private static readonly Dictionary<string, Order> _orders = new Dictionary<string, Order>();

		private static float _duck = 1f;

		private static AudioSource _duckSrc;

		private static bool _duckWritten;

		private static float _duckBase;

		private static float _duckValue;

		private static bool _previewMute;

		private static bool _previewMuteApplied;

		private static readonly Dictionary<AudioSource, DuckState> _others = new Dictionary<AudioSource, DuckState>();

		private static float _nextScan;

		private static readonly string _ownAssembly = typeof(MusicDriver).Assembly.GetName().Name;

		private static string _loggedWant = "-";

		private static string _loggedState = "";

		private static readonly FieldInfo _fSource = AccessTools.Field(typeof(MusicMan), "m_musicSource");

		private static readonly FieldInfo _fCurrent = AccessTools.Field(typeof(MusicMan), "m_currentMusic");

		private static readonly FieldInfo _fMasterVol = AccessTools.Field(typeof(MusicMan), "m_masterMusicVolume");

		private static readonly MethodInfo _mGetCurrentBiome = AccessTools.Method(typeof(EnvMan), "GetCurrentBiome", (Type[])null, (Type[])null);

		private static readonly MethodInfo _mInInterior = AccessTools.Method(typeof(Character), "InInterior", (Type[])null, (Type[])null);

		private static readonly MethodInfo _mInsideArea = FindInsideArea();

		private static readonly MethodInfo _mSafeInHome = SafeMethod(typeof(Player), "IsSafeInHome");

		private static readonly MethodInfo _mInShelter = SafeMethod(typeof(Player), "InShelter") ?? SafeMethod(typeof(Character), "InShelter");

		private const float HomeDelay = 1.5f;

		private static bool _homeRaw;

		private static float _homeRawSince;

		private static string _homeHow = "";

		private static object _playerBaseType;

		public static string CurrentBiome => _currentBiome;

		public static string CurrentPlace => _inDungeon ? "Dungeon" : (_atHome ? "Home" : _currentBiome);

		public static string PlayingKey => ((Object)(object)_src != (Object)null && (Object)(object)_src.clip != (Object)null && !_paused) ? _playingKey : null;

		public static bool MuteForPreview
		{
			get
			{
				return _previewMute;
			}
			set
			{
				_previewMute = value;
			}
		}

		public static float GameMusicVolume
		{
			get
			{
				try
				{
					if (_fMasterVol != null && _fMasterVol.IsStatic)
					{
						return Mathf.Clamp01(Convert.ToSingle(_fMasterVol.GetValue(null)));
					}
				}
				catch
				{
				}
				return Mathf.Clamp01(PlayerPrefs.GetFloat("MusicVolume", 1f));
			}
		}

		public static AudioSource Source
		{
			get
			{
				MusicMan instance = MusicMan.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return null;
				}
				object? obj = _fSource?.GetValue(instance);
				AudioSource val = (AudioSource)((obj is AudioSource) ? obj : null);
				return ((Object)(object)val != (Object)null) ? val : ((Component)instance).GetComponent<AudioSource>();
			}
		}

		public static string NowPlayingSlot
		{
			get
			{
				MusicMan instance = MusicMan.instance;
				if ((Object)(object)instance == (Object)null || _fCurrent == null)
				{
					return null;
				}
				object? value = _fCurrent.GetValue(instance);
				return ((NamedMusic)(((value is NamedMusic) ? value : null)?)).m_name;
			}
		}

		public static bool IsSpecial(string b)
		{
			return b == "Home" || b == "Dungeon";
		}

		public static void MarkDirty()
		{
			_dirty = true;
		}

		public static IReadOnlyList<string> SlotsOf(string biome)
		{
			IReadOnlyList<string> result;
			if (!_biomeSlots.TryGetValue(biome, out var value))
			{
				IReadOnlyList<string> readOnlyList = new string[0];
				result = readOnlyList;
			}
			else
			{
				IReadOnlyList<string> readOnlyList = value;
				result = readOnlyList;
			}
			return result;
		}

		public static void Tick()
		{
			MusicMan instance = MusicMan.instance;
			if ((Object)(object)instance == (Object)null)
			{
				StopOwn();
				return;
			}
			if ((Object)(object)instance != (Object)(object)_bound)
			{
				Bind(instance);
			}
			MapBiomes(instance);
			TrackBiome();
			EnsureSource();
			if (_dirty || _appliedCacheVersion != AudioCache.Version)
			{
				Preload();
			}
			Drive();
		}

		private static void Bind(MusicMan mm)
		{
			Plugin.Log("Bound to the game music. Checks: biome=" + ((_mGetCurrentBiome != null) ? "ok" : "MISSING") + " baseArea=" + ((_mInsideArea != null) ? "ok" : "MISSING") + " shelter=" + ((_mInShelter != null) ? "ok" : "MISSING") + " homeFire=" + ((_mSafeInHome != null) ? "ok" : "MISSING") + " dungeon=" + ((_mInInterior != null) ? "ok" : "MISSING") + " musicSlider=" + ((_fMasterVol != null) ? "ok" : "MISSING"));
			_bound = mm;
			_mapped = false;
			_mappedEnv = null;
			_duckSrc = null;
			_duckWritten = false;
			_dirty = true;
		}

		private static void EnsureSource()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if ((Object)(object)_src == (Object)null)
			{
				GameObject val = new GameObject("MusicPlaylists_Player");
				Object.DontDestroyOnLoad((Object)(object)val);
				_src = val.AddComponent<AudioSource>();
				_src.playOnAwake = false;
				_src.loop = false;
				_src.spatialBlend = 0f;
				_src.priority = 0;
			}
			AudioSource source = Source;
			if ((Object)(object)source != (Object)null)
			{
				if ((Object)(object)_src.outputAudioMixerGroup != (Object)(object)source.outputAudioMixerGroup)
				{
					_src.outputAudioMixerGroup = source.outputAudioMixerGroup;
				}
				_src.ignoreListenerPause = source.ignoreListenerPause;
				_src.bypassReverbZones = source.bypassReverbZones;
			}
		}

		private static void MapBiomes(MusicMan mm)
		{
			Object instance = (Object)(object)EnvMan.instance;
			if (_mapped && instance == _mappedEnv)
			{
				return;
			}
			_mapped = true;
			_mappedEnv = instance;
			_biomeSlots.Clear();
			HashSet<string> hashSet = new HashSet<string>(from m in mm.m_music
				where m != null && !string.IsNullOrEmpty(m.m_name)
				select m.m_name);
			if (instance != (Object)null && AccessTools.Field(((object)instance).GetType(), "m_biomes")?.GetValue(instance) is IEnumerable enumerable)
			{
				foreach (object item in enumerable)
				{
					if (item == null)
					{
						continue;
					}
					Type type = item.GetType();
					string text = AccessTools.Field(type, "m_biome")?.GetValue(item)?.ToString();
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					string[] array = new string[4] { "m_musicMorning", "m_musicDay", "m_musicEvening", "m_musicNight" };
					foreach (string text2 in array)
					{
						string text3 = AccessTools.Field(type, text2)?.GetValue(item) as string;
						if (!string.IsNullOrEmpty(text3) && hashSet.Contains(text3))
						{
							Link(text, text3);
						}
					}
				}
			}
			foreach (string item2 in hashSet)
			{
				if (Loc.CategoryOf(item2) == Loc.Category.Biome)
				{
					string text4 = Loc.BiomeFromSlot(item2);
					if (text4 != null)
					{
						Link(text4, item2);
					}
				}
			}
			foreach (KeyValuePair<string, List<string>> biomeSlot in _biomeSlots)
			{
				Plugin.Log("Biome " + biomeSlot.Key + ": " + string.Join(", ", biomeSlot.Value));
			}
		}

		private static void Link(string biome, string slot)
		{
			if (!_biomeSlots.TryGetValue(biome, out var value))
			{
				value = (_biomeSlots[biome] = new List<string>());
			}
			if (!value.Contains(slot))
			{
				value.Add(slot);
			}
		}

		private static MethodInfo SafeMethod(Type t, string name)
		{
			try
			{
				return AccessTools.GetDeclaredMethods(t).FirstOrDefault((MethodInfo m) => m.Name == name && m.GetParameters().Length == 0);
			}
			catch
			{
				return null;
			}
		}

		private static MethodInfo FindInsideArea()
		{
			try
			{
				return AccessTools.GetDeclaredMethods(typeof(EffectArea)).FirstOrDefault(delegate(MethodInfo m)
				{
					if (m.Name != "IsPointInsideArea" || !m.IsStatic)
					{
						return false;
					}
					ParameterInfo[] parameters = m.GetParameters();
					return parameters.Length >= 2 && parameters[0].ParameterType == typeof(Vector3) && parameters[1].ParameterType.IsEnum;
				});
			}
			catch
			{
				return null;
			}
		}

		private static bool IsAtBase(Vector3 pos)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (_mInsideArea == null)
			{
				return false;
			}
			try
			{
				ParameterInfo[] parameters = _mInsideArea.GetParameters();
				if (_playerBaseType == null)
				{
					_playerBaseType = Enum.Parse(parameters[1].ParameterType, "PlayerBase");
				}
				object[] parameters2 = ((parameters.Length < 3) ? new object[2] { pos, _playerBaseType } : new object[3] { pos, _playerBaseType, 0f });
				return _mInsideArea.Invoke(null, parameters2) != null;
			}
			catch
			{
				return false;
			}
		}

		private static void TrackBiome()
		{
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < _nextBiomeCheck)
			{
				return;
			}
			_nextBiomeCheck = Time.unscaledTime + 0.5f;
			string text = null;
			try
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)EnvMan.instance != (Object)null && _mGetCurrentBiome != null)
				{
					text = _mGetCurrentBiome.Invoke(EnvMan.instance, null)?.ToString();
				}
			}
			catch
			{
				text = null;
			}
			if (text == "None")
			{
				text = null;
			}
			bool flag = false;
			bool atHome = false;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				try
				{
					flag = _mInInterior != null && (bool)_mInInterior.Invoke(localPlayer, null);
				}
				catch
				{
				}
				if (!flag)
				{
					bool flag2 = IsAtBase(((Component)localPlayer).transform.position);
					bool flag3 = false;
					bool flag4 = false;
					try
					{
						flag3 = _mInShelter != null && (bool)_mInShelter.Invoke(localPlayer, null);
					}
					catch
					{
					}
					try
					{
						flag4 = _mSafeInHome != null && (bool)_mSafeInHome.Invoke(localPlayer, null);
					}
					catch
					{
					}
					bool flag5 = (flag3 && flag2) || flag4;
					if (flag5 != _homeRaw)
					{
						_homeRaw = flag5;
						_homeRawSince = Time.unscaledTime;
					}
					atHome = ((Time.unscaledTime - _homeRawSince >= 1.5f) ? flag5 : _atHome);
					_homeHow = (flag3 ? "shelter" : "no shelter") + (flag2 ? "+area" : "") + (flag4 ? "+fire" : "");
				}
			}
			_currentBiome = text;
			_inDungeon = flag;
			_atHome = atHome;
		}

		private static string DescribePlaylists()
		{
			return string.Join(", ", PlaylistStore.Db.playlists.Select((Playlist p) => p.biome + ":" + (p.enabled ? "on" : "off") + "/" + p.tracks.Count + ((p.tracks.Count > 0 && p.tracks.All(AudioCache.IsFailed)) ? "/broken" : "")));
		}

		private static Playlist ActivePlaylist(string key)
		{
			if (key == null)
			{
				return null;
			}
			Playlist playlist = PlaylistStore.Db.Find(key);
			return (playlist != null && playlist.enabled && playlist.tracks.Any((string t) => !AudioCache.IsFailed(t))) ? playlist : null;
		}

		private static string WantedKey()
		{
			if (!Plugin.ModEnabled.Value || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return null;
			}
			if (_inDungeon && ActivePlaylist("Dungeon") != null)
			{
				return "Dungeon";
			}
			if (_atHome && ActivePlaylist("Home") != null)
			{
				return "Home";
			}
			if (_inDungeon)
			{
				return null;
			}
			return (ActivePlaylist(_currentBiome) != null) ? _currentBiome : null;
		}

		private static bool VanillaPriority()
		{
			AudioSource source = Source;
			if ((Object)(object)source == (Object)null || !source.isPlaying)
			{
				return false;
			}
			return Loc.CategoryOf(NowPlayingSlot) == Loc.Category.Combat;
		}

		private static void Preload()
		{
			_dirty = false;
			_appliedCacheVersion = AudioCache.Version;
			HashSet<string> hashSet = new HashSet<string>();
			if (Plugin.ModEnabled.Value)
			{
				foreach (Playlist playlist in PlaylistStore.Db.playlists)
				{
					if (!playlist.enabled)
					{
						continue;
					}
					foreach (string track in playlist.tracks)
					{
						hashSet.Add(track);
						if (!AudioCache.IsLoaded(track))
						{
							AudioCache.Request(track);
						}
					}
				}
			}
			if (_playingTrack != null)
			{
				hashSet.Add(_playingTrack);
			}
			if (PlaylistMenu.PreviewTrack != null)
			{
				hashSet.Add(PlaylistMenu.PreviewTrack);
			}
			AudioCache.Retain(hashSet);
		}

		private static void Drive()
		{
			float unscaledDeltaTime = Time.unscaledDeltaTime;
			float num = Mathf.Max(0.1f, Plugin.SwitchFade.Value);
			string text = WantedKey();
			bool flag = VanillaPriority();
			string text2 = (_currentBiome ?? "-") + "|" + _atHome + "|" + _inDungeon + "|" + (text ?? "-") + "|" + Plugin.ModEnabled.Value;
			if (text2 != _loggedState)
			{
				_loggedState = text2;
				_loggedWant = text;
				Plugin.Log("Place: biome=" + (_currentBiome ?? "-") + " base=" + _atHome + ((_homeHow.Length > 0) ? (" (" + _homeHow + ")") : "") + " dungeon=" + _inDungeon + " mod=" + (Plugin.ModEnabled.Value ? "on" : "OFF") + " playlists=[" + DescribePlaylists() + "] -> playlist " + (text ?? "none (vanilla)"));
			}
			bool flag2 = (Object)(object)_src.clip != (Object)null;
			bool flag3 = flag2 && !flag && Plugin.ModEnabled.Value && (Object)(object)Player.m_localPlayer != (Object)null && (_playingKey == text || !Plugin.SwitchImmediately.Value);
			float num2 = (flag3 ? 1f : 0f);
			_fade = Mathf.MoveTowards(_fade, num2, unscaledDeltaTime / num);
			if (flag2)
			{
				if (!flag3 && _fade <= 0.001f)
				{
					if (flag && _playingKey == text && Plugin.ModEnabled.Value)
					{
						if (!_paused)
						{
							_src.Pause();
							_paused = true;
						}
					}
					else
					{
						StopOwn();
					}
				}
				else if (flag3 && _paused)
				{
					_src.UnPause();
					_paused = false;
				}
				else if (!_paused)
				{
					if (_src.isPlaying)
					{
						_lastTime = _src.time;
					}
					else if (_lastTime >= _src.clip.length - 1.5f)
					{
						OnTrackEnded(text);
					}
					else if (Application.isFocused)
					{
						_src.time = Mathf.Clamp(_lastTime, 0f, _src.clip.length - 0.1f);
						_src.Play();
					}
				}
			}
			if ((Object)(object)_src.clip == (Object)null && text != null && !flag && (!(_gapKey == text) || !(Time.unscaledTime < _gapUntil)))
			{
				PlayNext(text);
			}
			if (text != _gapKey)
			{
				_gapKey = null;
			}
			bool flag4 = !flag && (text != null || ((Object)(object)_src.clip != (Object)null && !_paused));
			_duck = Mathf.MoveTowards(_duck, flag4 ? 0f : 1f, unscaledDeltaTime / num);
		}

		private static void OnTrackEnded(string want)
		{
			string playingKey = _playingKey;
			StopOwn();
			if (want != null)
			{
				Playlist playlist = ActivePlaylist(want);
				if (want == playingKey && playlist != null && !playlist.continuous)
				{
					_gapKey = want;
					_gapUntil = Time.unscaledTime + Mathf.Max(0f, Plugin.PauseSeconds.Value);
				}
				else
				{
					PlayNext(want);
				}
			}
		}

		private static bool PlayNext(string key)
		{
			Playlist playlist = ActivePlaylist(key);
			if (playlist == null)
			{
				return false;
			}
			string text = string.Join("|", playlist.tracks) + (playlist.shuffle ? "#s" : "#o");
			if (!_orders.TryGetValue(key, out var value) || value.Signature != text)
			{
				value = new Order
				{
					Signature = text,
					Tracks = new List<string>(playlist.tracks),
					Pos = 0
				};
				if (playlist.shuffle)
				{
					Shuffle(value.Tracks, null);
				}
				_orders[key] = value;
			}
			for (int i = 0; i < value.Tracks.Count; i++)
			{
				if (value.Pos >= value.Tracks.Count)
				{
					value.Pos = 0;
					if (playlist.shuffle)
					{
						Shuffle(value.Tracks, _playingTrack);
					}
				}
				string text2 = value.Tracks[value.Pos];
				AudioClip val = AudioCache.Get(text2);
				if ((Object)(object)val == (Object)null)
				{
					AudioCache.Request(text2);
					if (AudioCache.IsLoading(text2))
					{
						return false;
					}
					value.Pos++;
					continue;
				}
				value.Pos++;
				_src.clip = val;
				_src.time = 0f;
				_src.loop = false;
				_src.volume = 0f;
				_src.Play();
				_playingKey = key;
				_playingTrack = text2;
				_paused = false;
				_fade = 1f;
				_lastTime = 0f;
				_gapKey = null;
				Plugin.Log("Playing " + text2 + " (" + key + ")");
				if (Plugin.ShowTrackName.Value && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					((Character)Player.m_localPlayer).Message((MessageType)1, Loc.T("now_playing") + ": " + ((Object)val).name, 0, (Sprite)null, false);
				}
				return true;
			}
			return false;
		}

		private static void StopOwn()
		{
			if ((Object)(object)_src != (Object)null)
			{
				_src.Stop();
				_src.clip = null;
			}
			_playingKey = null;
			_playingTrack = null;
			_paused = false;
			_fade = 0f;
			_lastTime = 0f;
		}

		public static void LateTick()
		{
			if ((Object)(object)_src != (Object)null)
			{
				float volume = 0f;
				AudioClip clip = _src.clip;
				if ((Object)(object)clip != (Object)null)
				{
					float length = clip.length;
					float num = Mathf.Clamp(_src.time, 0f, length);
					float num2 = 1f;
					float num3 = Mathf.Min(Plugin.FadeIn.Value, length / 3f);
					if (num3 > 0.01f)
					{
						num2 *= Mathf.Clamp01(num / num3);
					}
					float num4 = Mathf.Min(Plugin.FadeOut.Value, length / 3f);
					if (num4 > 0.01f)
					{
						num2 *= Mathf.Clamp01((length - num) / num4);
					}
					volume = Mathf.Min(1f, GameMusicVolume * TrackVolume(_playingTrack)) * Smooth(num2) * Smooth(_fade);
				}
				_src.volume = volume;
				_src.mute = _previewMute;
			}
			DuckOthers();
			AudioSource source = Source;
			if ((Object)(object)source != (Object)(object)_duckSrc)
			{
				_duckSrc = source;
				_duckWritten = false;
				_previewMuteApplied = false;
			}
			if ((Object)(object)source == (Object)null)
			{
				return;
			}
			if (_previewMute != _previewMuteApplied)
			{
				source.mute = _previewMute;
				_previewMuteApplied = _previewMute;
			}
			float num5 = ((_duckWritten && Mathf.Approximately(source.volume, _duckValue)) ? _duckBase : source.volume);
			float num6 = Smooth(_duck);
			if (num6 >= 0.999f)
			{
				if (_duckWritten)
				{
					source.volume = num5;
					_duckWritten = false;
				}
			}
			else
			{
				_duckBase = num5;
				_duckValue = num5 * num6;
				source.volume = _duckValue;
				_duckWritten = true;
			}
		}

		private static void ScanOthers()
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < _nextScan)
			{
				return;
			}
			_nextScan = Time.unscaledTime + 1f;
			foreach (AudioSource item in _others.Keys.Where((AudioSource k) => (Object)(object)k == (Object)null).ToList())
			{
				_others.Remove(item);
			}
			AudioSource source = Source;
			AudioMixerGroup val = (((Object)(object)source != (Object)null) ? source.outputAudioMixerGroup : null);
			AudioSource[] array;
			try
			{
				array = Resources.FindObjectsOfTypeAll<AudioSource>();
			}
			catch
			{
				return;
			}
			AudioSource[] array2 = array;
			foreach (AudioSource val2 in array2)
			{
				if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)_src || (Object)(object)val2 == (Object)(object)source || _others.ContainsKey(val2))
				{
					continue;
				}
				GameObject gameObject = ((Component)val2).gameObject;
				Scene scene = gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && !((Object)gameObject).name.StartsWith("MusicPlaylists_") && !(val2.spatialBlend > 0.5f))
				{
					bool flag = (Object)(object)val != (Object)null && (Object)(object)val2.outputAudioMixerGroup == (Object)(object)val;
					if (!flag)
					{
						flag = IsMusicMod(gameObject);
					}
					if (flag)
					{
						_others[val2] = new DuckState();
						Plugin.Log("Other music source found: " + ((Object)gameObject).name + " (silenced while your playlist plays)");
					}
				}
			}
		}

		private static bool IsMusicMod(GameObject go)
		{
			Transform val = go.transform;
			while ((Object)(object)val != (Object)null)
			{
				MonoBehaviour[] components = ((Component)val).GetComponents<MonoBehaviour>();
				foreach (MonoBehaviour val2 in components)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						Type type = ((object)val2).GetType();
						string name = type.Assembly.GetName().Name;
						if (!(name == _ownAssembly) && !name.StartsWith("assembly_") && !name.StartsWith("UnityEngine") && (name.IndexOf("music", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("audio", StringComparison.OrdinalIgnoreCase) >= 0 || type.Name.IndexOf("music", StringComparison.OrdinalIgnoreCase) >= 0))
						{
							return true;
						}
					}
				}
				val = val.parent;
			}
			return false;
		}

		private static void DuckOthers()
		{
			bool flag = Plugin.DuckOtherMods.Value && Plugin.ModEnabled.Value;
			if (flag)
			{
				ScanOthers();
			}
			if (_others.Count == 0)
			{
				return;
			}
			float num = (flag ? Smooth(_duck) : 1f);
			foreach (KeyValuePair<AudioSource, DuckState> other in _others)
			{
				AudioSource key = other.Key;
				DuckState value = other.Value;
				if ((Object)(object)key == (Object)null)
				{
					continue;
				}
				if (_previewMute != value.Muted)
				{
					key.mute = _previewMute;
					value.Muted = _previewMute;
				}
				float num2 = ((value.Written && Mathf.Approximately(key.volume, value.Value)) ? value.Base : key.volume);
				if (num >= 0.999f)
				{
					if (value.Written)
					{
						key.volume = num2;
						value.Written = false;
					}
				}
				else
				{
					value.Base = num2;
					value.Value = num2 * num;
					key.volume = value.Value;
					value.Written = true;
				}
			}
		}

		public static float TrackVolume(string libName)
		{
			PlaylistDb playlistDb = PlaylistMenu.EditingDb ?? PlaylistStore.Db;
			return playlistDb.TrackVolume(libName);
		}

		private static float Smooth(float x)
		{
			return x * x * (3f - 2f * x);
		}

		private static void Shuffle(List<string> list, string avoidFirst)
		{
			for (int num = list.Count - 1; num > 0; num--)
			{
				int index = Random.Range(0, num + 1);
				string value = list[num];
				list[num] = list[index];
				list[index] = value;
			}
			if (avoidFirst != null && list.Count > 1 && list[0] == avoidFirst)
			{
				string value2 = list[0];
				list[0] = list[list.Count - 1];
				list[list.Count - 1] = value2;
			}
		}

		public static void RestoreAll()
		{
			StopOwn();
			AudioSource source = Source;
			if ((Object)(object)source != (Object)null)
			{
				if (_duckWritten)
				{
					source.volume = _duckBase;
				}
				if (_previewMuteApplied)
				{
					source.mute = false;
				}
			}
			_duckWritten = false;
			_previewMuteApplied = false;
			_duck = 1f;
			foreach (KeyValuePair<AudioSource, DuckState> other in _others)
			{
				if (!((Object)(object)other.Key == (Object)null))
				{
					if (other.Value.Written)
					{
						other.Key.volume = other.Value.Base;
					}
					if (other.Value.Muted)
					{
						other.Key.mute = false;
					}
				}
			}
			_others.Clear();
		}
	}
	public class PlaylistMenu
	{
		private enum View
		{
			None,
			General,
			Library,
			Slot
		}

		private const string BlockOwner = "kaefchik.musicplaylists";

		private const float W = 1120f;

		private const float H = 720f;

		private const float RowH = 52f;

		private const float TrackH = 40f;

		private PlaylistDb _edit;

		private bool _gEnabled;

		private bool _gShowName;

		private float _gPause;

		private float _gFadeIn;

		private float _gFadeOut;

		private float _gSwitchFade;

		private bool _gSwitchNow;

		private bool _gDuckOthers;

		private View _view = View.None;

		private string _slot;

		private string _path = "";

		private bool _picker;

		private Vector2 _leftScroll;

		private Vector2 _rightScroll;

		private string _status;

		private bool _statusErr;

		private float _statusUntil;

		private string _confirmDelete;

		private float _confirmUntil;

		private const float TrackRowH = 74f;

		private AudioSource _preview;

		private bool _previewStarted;

		private bool _mutedMusic;

		private GUIStyle _nameStyle;

		private GUIStyle _dimStyle;

		private GUIStyle _wrapDimStyle;

		public bool IsOpen { get; private set; }

		public static string PreviewTrack { get; private set; }

		public static PlaylistDb EditingDb { get; private set; }

		public void Open()
		{
			if (!IsOpen)
			{
				if (_edit == null)
				{
					BeginEdit();
				}
				IsOpen = true;
				EditingDb = _edit;
				ModHubAPI.SetInputBlock("kaefchik.musicplaylists", true);
			}
		}

		public void Close()
		{
			if (IsOpen)
			{
				IsOpen = false;
				EditingDb = null;
				StopPreview();
				GUI.FocusControl((string)null);
				ModHubAPI.SetInputBlock("kaefchik.musicplaylists", false);
			}
		}

		private void BackToHub()
		{
			Close();
			ModHubAPI.OpenHub();
		}

		private void BeginEdit()
		{
			_edit = PlaylistStore.Db.Clone();
			if (IsOpen)
			{
				EditingDb = _edit;
			}
			_gEnabled = Plugin.ModEnabled.Value;
			_gShowName = Plugin.ShowTrackName.Value;
			_gPause = Plugin.PauseSeconds.Value;
			_gFadeIn = Plugin.FadeIn.Value;
			_gFadeOut = Plugin.FadeOut.Value;
			_gSwitchNow = Plugin.SwitchImmediately.Value;
			_gSwitchFade = Plugin.SwitchFade.Value;
			_gDuckOthers = Plugin.DuckOtherMods.Value;
		}

		private void ApplyEdits()
		{
			Plugin.ModEnabled.Value = _gEnabled;
			Plugin.ShowTrackName.Value = _gShowName;
			Plugin.PauseSeconds.Value = _gPause;
			Plugin.FadeIn.Value = _gFadeIn;
			Plugin.FadeOut.Value = _gFadeOut;
			Plugin.SwitchImmediately.Value = _gSwitchNow;
			Plugin.SwitchFade.Value = _gSwitchFade;
			Plugin.DuckOtherMods.Value = _gDuckOthers;
			PlaylistStore.Save(_edit);
			BeginEdit();
			Status(Loc.T("applied"), error: false);
		}

		private void CancelEdits()
		{
			BeginEdit();
			Status(Loc.T("reverted"), error: false);
		}

		private void AllVanilla()
		{
			foreach (Playlist playlist in _edit.playlists)
			{
				playlist.enabled = false;
			}
			Status(Loc.T("vanilla_done"), error: false);
		}

		public void Update()
		{
			if (PreviewTrack == null)
			{
				return;
			}
			if (AudioCache.IsFailed(PreviewTrack))
			{
				Status(Track(PreviewTrack) + ": " + Loc.T("failed"), error: true);
				StopPreview();
				return;
			}
			AudioClip val = AudioCache.Get(PreviewTrack);
			if (!_previewStarted && (Object)(object)val != (Object)null)
			{
				EnsurePreviewSource();
				_preview.clip = val;
				_preview.volume = PreviewVolume();
				_preview.Play();
				_previewStarted = true;
				MusicDriver.MuteForPreview = true;
				_mutedMusic = true;
			}
			else if (_previewStarted && ((Object)(object)_preview == (Object)null || !_preview.isPlaying))
			{
				StopPreview();
			}
			else if (_previewStarted)
			{
				_preview.volume = PreviewVolume();
			}
		}

		private void EnsurePreviewSource()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			if (!((Object)(object)_preview != (Object)null))
			{
				GameObject val = new GameObject("MusicPlaylists_Preview");
				Object.DontDestroyOnLoad((Object)(object)val);
				_preview = val.AddComponent<AudioSource>();
				_preview.playOnAwake = false;
				_preview.spatialBlend = 0f;
				_preview.loop = false;
				AudioSource source = MusicDriver.Source;
				if ((Object)(object)source != (Object)null)
				{
					_preview.outputAudioMixerGroup = source.outputAudioMixerGroup;
				}
			}
		}

		private void TogglePreview(string track)
		{
			if (PreviewTrack == track)
			{
				StopPreview();
				return;
			}
			StopPreview();
			PreviewTrack = track;
			_previewStarted = false;
			AudioCache.Retry(track);
			AudioCache.Request(track);
		}

		private void StopPreview()
		{
			if ((Object)(object)_preview != (Object)null)
			{
				_preview.Stop();
			}
			PreviewTrack = null;
			_previewStarted = false;
			if (_mutedMusic)
			{
				MusicDriver.MuteForPreview = false;
				_mutedMusic = false;
			}
		}

		public void OnGUI()
		{
			//IL_0034: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0082: 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_0132: 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_0144: Unknown result type (might be due to invalid IL or missing references)
			if (!IsOpen)
			{
				return;
			}
			if (_edit == null)
			{
				BeginEdit();
			}
			HubUI.Ensure();
			EnsureStyles();
			Vector2 val = HubUI.BeginScaled();
			try
			{
				Rect val2 = HubUI.Centered(val, 1120f, 720f);
				HubUI.Window(val2, Loc.T("title"), false);
				if (HubUI.Button(new Rect(((Rect)(ref val2)).x + 18f, ((Rect)(ref val2)).y + 18f, 42f, 42f), "<"))
				{
					BackToHub();
					return;
				}
				if (HubUI.CloseButton(val2))
				{
					Close();
					return;
				}
				float num = ((Rect)(ref val2)).y + 88f;
				float num2 = ((Rect)(ref val2)).yMax - 104f;
				Rect r = default(Rect);
				((Rect)(ref r))..ctor(((Rect)(ref val2)).x + 24f, num, 340f, num2 - num);
				Rect r2 = default(Rect);
				((Rect)(ref r2))..ctor(((Rect)(ref r)).xMax + 24f, num, ((Rect)(ref val2)).xMax - 24f - (((Rect)(ref r)).xMax + 24f), num2 - num);
				DrawLeft(r);
				DrawRight(r2);
				DrawBottom(val2);
			}
			finally
			{
				HubUI.EndScaled();
			}
		}

		private void EnsureStyles()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//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_0062: Expected O, but got Unknown
			if (_nameStyle == null)
			{
				_nameStyle = new GUIStyle(HubUI.NoWrap(HubUI.LabelStyle))
				{
					clipping = (TextClipping)1
				};
				_dimStyle = new GUIStyle(HubUI.NoWrap(HubUI.LabelDimStyle))
				{
					clipping = (TextClipping)1
				};
				_wrapDimStyle = new GUIStyle(HubUI.LabelDimStyle)
				{
					wordWrap = true
				};
			}
		}

		private void DrawLeft(Rect r)
		{
			//IL_001d: 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_00bd: 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)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			float y = ((Rect)(ref r)).y;
			if (HubUI.Button(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 38f), Loc.T("general")))
			{
				Select(View.General, null);
			}
			y += 44f;
			if (HubUI.Button(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 38f), Loc.T("library") + " (" + Storage.LibraryFiles().Count + ")"))
			{
				Select(View.Library, null);
			}
			y += 50f;
			HubUI.Header(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), Loc.T("biomes"));
			y += 40f;
			string[] biomes = MusicDriver.Biomes;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, ((Rect)(ref r)).yMax - y);
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(0f, 0f, ((Rect)(ref val)).width - 18f, Mathf.Max((float)biomes.Length * 56f + 40f, ((Rect)(ref val)).height - 2f));
			_leftScroll = GUI.BeginScrollView(val, _leftScroll, val2);
			float num = 0f;
			bool flag = false;
			Rect val3 = default(Rect);
			foreach (string text in biomes)
			{
				if (!flag && MusicDriver.IsSpecial(text))
				{
					flag = true;
					HubUI.Header(new Rect(0f, num + 4f, ((Rect)(ref val2)).width, 30f), Loc.T("special"));
					num += 40f;
				}
				((Rect)(ref val3))..ctor(0f, num, ((Rect)(ref val2)).width, 52f);
				num += 56f;
				bool flag2 = ((Rect)(ref val3)).Contains(Event.current.mousePosition);
				bool flag3 = _view == View.Slot && _slot == text;
				HubUI.Slot(val3, flag2, flag3);
				Playlist playlist = _edit.Find(text);
				bool flag4 = playlist != null && playlist.enabled && playlist.tracks.Count > 0;
				HubUI.Dot(new Vector2(((Rect)(ref val3)).x + 16f, ((Rect)(ref val3)).center.y), 10f, flag4 ? HubUI.GoldBright : HubUI.TextDim);
				GUI.Label(new Rect(((Rect)(ref val3)).x + 30f, ((Rect)(ref val3)).y + 4f, ((Rect)(ref val3)).width - 80f, 26f), Loc.BiomeName(text), _nameStyle);
				if (text == MusicDriver.CurrentPlace || text == MusicDriver.CurrentBiome)
				{
					GUI.Label(new Rect(((Rect)(ref val3)).x + 30f, ((Rect)(ref val3)).y + 27f, ((Rect)(ref val3)).width - 80f, 20f), Loc.T("you_are_here"), _dimStyle);
				}
				if (playlist != null && playlist.tracks.Count > 0)
				{
					GUI.Label(new Rect(((Rect)(ref val3)).xMax - 48f, ((Rect)(ref val3)).y, 40f, ((Rect)(ref val3)).height), playlist.tracks.Count.ToString(), _dimStyle);
				}
				if (GUI.Button(val3, GUIContent.none, GUIStyle.none))
				{
					Select(View.Slot, text);
				}
			}
			GUI.EndScrollView();
		}

		private void Select(View v, string slot)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			_view = v;
			_slot = slot;
			_picker = false;
			_rightScroll = Vector2.zero;
			_confirmDelete = null;
		}

		private void DrawRight(Rect r)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			switch (_view)
			{
			case View.General:
				DrawGeneral(r);
				break;
			case View.Library:
				DrawLibrary(r);
				break;
			case View.Slot:
				DrawSlot(r);
				break;
			default:
				GUI.Label(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y + 40f, ((Rect)(ref r)).width, 60f), Loc.T("pick_biome"), _nameStyle);
				GUI.Label(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y + 80f, ((Rect)(ref r)).width, 80f), Loc.T("biome_hint"), _wrapDimStyle);
				break;
			}
		}

		private void DrawGeneral(Rect r)
		{
			//IL_001d: 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_008b: 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_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: 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)
			float y = ((Rect)(ref r)).y;
			HubUI.Header(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 36f), Loc.T("general"));
			y += 48f;
			_gEnabled = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), _gEnabled, Loc.T("mod_enabled"));
			y += 40f;
			_gShowName = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), _gShowName, Loc.T("show_name"));
			y += 40f;
			_gDuckOthers = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), _gDuckOthers, Loc.T("duck_others"));
			y += 40f;
			GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 30f), Loc.T("volume_game") + "  " + Mathf.RoundToInt(MusicDriver.GameMusicVolume * 100f) + "%", _dimStyle);
			y += 36f;
			_gPause = Mathf.Round(HubUI.SliderText(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 34f), Loc.T("pause_len"), _gPause, 0f, 300f, Seconds(_gPause), "0", 260f) / 5f) * 5f;
			y += 44f;
			_gFadeIn = Mathf.Round(HubUI.SliderText(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 34f), Loc.T("fade_in"), _gFadeIn, 0f, 15f, Seconds(_gFadeIn), "0.#", 260f) * 2f) / 2f;
			y += 44f;
			_gFadeOut = Mathf.Round(HubUI.SliderText(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 34f), Loc.T("fade_out"), _gFadeOut, 0f, 15f, Seconds(_gFadeOut), "0.#", 260f) * 2f) / 2f;
			y += 44f;
			_gSwitchNow = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), _gSwitchNow, Loc.T("switch_now"));
			y += 40f;
			if (_gSwitchNow)
			{
				_gSwitchFade = Mathf.Round(HubUI.SliderText(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 34f), Loc.T("switch_fade"), _gSwitchFade, 0.5f, 10f, _gSwitchFade.ToString("0.#") + " " + Loc.T("sec"), "0.#", 260f) * 2f) / 2f;
			}
			y += 44f;
			GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 76f), Loc.T("storage_info"), _wrapDimStyle);
			y += 78f;
			GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 40f), Loc.T("folder") + " " + Storage.Root, _wrapDimStyle);
		}

		private void DrawLibrary(Rect r)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0441: Unknown result type (might be due to invalid IL or missing references)
			//IL_0471: Unknown result type (might be due to invalid IL or missing references)
			//IL_0473: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = Storage.LibraryFiles();
			float y = ((Rect)(ref r)).y;
			HubUI.Header(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 36f), Loc.T("library") + " (" + list.Count + ")");
			y += 46f;
			DrawPathLine(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 34f), Loc.T("import"), addToSlot: false);
			y += 42f;
			float num = (((Rect)(ref r)).width - 16f) / 3f;
			if (HubUI.Button(new Rect(((Rect)(ref r)).x, y, num, 36f), Loc.T("take_import")))
			{
				List<string> list2 = Storage.TakeFromImportFolder();
				if (list2.Count == 0)
				{
					Status(Loc.T("import_none"), error: true);
				}
				else
				{
					Status(Loc.F("imported", list2.Count), error: false);
				}
			}
			if (HubUI.Button(new Rect(((Rect)(ref r)).x + num + 8f, y, num, 36f), Loc.T("open_lib")))
			{
				Storage.OpenFolder(Storage.LibraryDir);
			}
			if (HubUI.Button(new Rect(((Rect)(ref r)).x + 2f * (num + 8f), y, num, 36f), Loc.T("open_import")))
			{
				Storage.OpenFolder(Storage.ImportDir);
			}
			y += 46f;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, ((Rect)(ref r)).yMax - y);
			if (list.Count == 0)
			{
				GUI.Label(val, Loc.T("lib_empty"), _wrapDimStyle);
				return;
			}
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(0f, 0f, ((Rect)(ref val)).width - 18f, Mathf.Max((float)list.Count * 44f, ((Rect)(ref val)).height - 2f));
			_rightScroll = GUI.BeginScrollView(val, _rightScroll, val2);
			Rect val3 = default(Rect);
			for (int i = 0; i < list.Count; i++)
			{
				string f = list[i];
				((Rect)(ref val3))..ctor(0f, (float)i * 44f, ((Rect)(ref val2)).width, 40f);
				HubUI.Slot(val3, ((Rect)(ref val3)).Contains(Event.current.mousePosition), PreviewTrack == f);
				if (HubUI.Button(new Rect(((Rect)(ref val3)).x + 4f, ((Rect)(ref val3)).y + 3f, 34f, 34f), (PreviewTrack == f) ? "||" : ">"))
				{
					TogglePreview(f);
				}
				int num2 = _edit.playlists.Count((Playlist p) => p.tracks.Contains(f));
				string text = ((float)Storage.SizeOf(f) / 1048576f).ToString("0.0") + " MB" + ((num2 > 0) ? ("  ·  " + num2 + " " + Loc.T("used_in")) : "");
				GUI.Label(new Rect(((Rect)(ref val3)).x + 46f, ((Rect)(ref val3)).y, ((Rect)(ref val3)).width - 300f, ((Rect)(ref val3)).height), Track(f), _nameStyle);
				GUI.Label(new Rect(((Rect)(ref val3)).xMax - 250f, ((Rect)(ref val3)).y, 200f, ((Rect)(ref val3)).height), text, _dimStyle);
				bool flag = _confirmDelete == f && Time.unscaledTime < _confirmUntil;
				Rect val4 = (flag ? new Rect(((Rect)(ref val3)).xMax - 250f, ((Rect)(ref val3)).y + 3f, 244f, 34f) : new Rect(((Rect)(ref val3)).xMax - 40f, ((Rect)(ref val3)).y + 3f, 34f, 34f));
				if (HubUI.Button(val4, flag ? Loc.T("confirm_del") : "x"))
				{
					if (flag)
					{
						DeleteFromLibrary(f);
						continue;
					}
					_confirmDelete = f;
					_confirmUntil = Time.unscaledTime + 3f;
				}
			}
			GUI.EndScrollView();
		}

		private void DeleteFromLibrary(string f)
		{
			if (PreviewTrack == f)
			{
				StopPreview();
			}
			AudioCache.Unload(f);
			if (!Storage.Delete(f))
			{
				return;
			}
			foreach (Playlist playlist in _edit.playlists)
			{
				playlist.tracks.RemoveAll((string t) => t == f);
			}
			_edit.trackVolumes.Remove(f);
			PlaylistDb playlistDb = PlaylistStore.Db.Clone();
			foreach (Playlist playlist2 in playlistDb.playlists)
			{
				playlist2.tracks.RemoveAll((string t) => t == f);
			}
			playlistDb.trackVolumes.Remove(f);
			PlaylistStore.Save(playlistDb);
			_confirmDelete = null;
			Status(Loc.F("deleted", Track(f)), error: false);
		}

		private void DrawSlot(Rect r)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: 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_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(_slot))
			{
				_view = View.None;
				return;
			}
			Playlist orCreate = _edit.GetOrCreate(_slot);
			float y = ((Rect)(ref r)).y;
			bool flag = _slot == MusicDriver.CurrentPlace || _slot == MusicDriver.CurrentBiome;
			bool flag2 = MusicDriver.PlayingKey == _slot;
			HubUI.Header(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 36f), Loc.BiomeName(_slot) + (flag ? ("  ·  " + Loc.T("you_are_here")) : "") + (flag2 ? ("  ·  " + Loc.T("playing_here")) : ""));
			y += 36f;
			if (MusicDriver.IsSpecial(_slot))
			{
				GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 44f), Loc.T((_slot == "Home") ? "home_hint" : "dungeon_hint"), _wrapDimStyle);
				y += 48f;
			}
			else
			{
				IReadOnlyList<string> readOnlyList = MusicDriver.SlotsOf(_slot);
				string text = ((readOnlyList.Count == 0) ? Loc.T("slots_later") : string.Join(", ", readOnlyList.Select(delegate(string x)
				{
					string text2 = Loc.TimeOfSlot(x);
					return (text2.Length > 0) ? (x + " (" + text2 + ")") : x;
				})));
				GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 22f), Loc.T("replaces") + " " + text, _dimStyle);
				y += 30f;
			}
			float num = (((Rect)(ref r)).width - 16f) / 2f;
			orCreate.enabled = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, num, 32f), orCreate.enabled, Loc.T("own_music"));
			orCreate.shuffle = HubUI.Toggle(new Rect(((Rect)(ref r)).x + num + 16f, y, num, 32f), orCreate.shuffle, Loc.T("shuffle"));
			y += 38f;
			orCreate.continuous = HubUI.Toggle(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 32f), orCreate.continuous, Loc.T("continuous"));
			y += 40f;
			if (!Plugin.ModEnabled.Value || !_gEnabled)
			{
				GUIStyle val = new GUIStyle(_dimStyle);
				val.normal.textColor = HubUI.Danger;
				GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width - 250f, 30f), Loc.T("mod_off_warn"), val);
				if (HubUI.Button(new Rect(((Rect)(ref r)).xMax - 240f, y - 2f, 240f, 34f), Loc.T("mod_turn_on")))
				{
					_gEnabled = true;
					Plugin.ModEnabled.Value = true;
					Status(Loc.T("mod_turned_on"), error: false);
				}
			}
			else
			{
				GUI.Label(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, 30f), Loc.T("volume_game"), _dimStyle);
			}
			y += 38f;
			HubUI.Header(new Rect(((Rect)(ref r)).x, y, ((Rect)(ref r)).width - 230f, 34f), Loc.T("tracks") + " (" + orCreate.tracks.Count + ")");
			if (HubUI.Button(new Rect(((Rect)(ref r)).xMax - 220f, y, 220f, 34f), _picker ? Loc.T("back_tracks") : Loc.T("from_library")))
			{
				_picker = !_picker;
				_rightScroll = Vector2.zero;
			}
			y += 42f;
			Rect area = default(Rect);
			((Rect)(ref area))..ctor(((Rect)(ref r)).x, y, ((Rect)(ref r)).width, ((Rect)(ref r)).yMax - y - 44f);
			if (_picker)
			{
				DrawPicker(area, orCreate);
			}
			else
			{
				DrawTracks(area, orCreate);
			}
			DrawPathLine(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).yMax - 36f, ((Rect)(ref r)).width, 34f), Loc.T("add"), addToSlot: true);
		}

		private void DrawTracks(Rect area, Playlist pl)
		{
			//IL_0075: 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_007c: 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_0082: 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_00c6: 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_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0406: Unknown result type (might be due to invalid IL or missing references)
			if (pl.tracks.Count == 0)
			{
				GUI.Label(area, Loc.T("no_tracks"), _wrapDimStyle);
				return;
			}
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(0f, 0f, ((Rect)(ref area)).width - 18f, Mathf.Max((float)pl.tracks.Count * 78f, ((Rect)(ref area)).height - 2f));
			_rightScroll = GUI.BeginScrollView(area, _rightScroll, val);
			int num = -1;
			int num2 = 0;
			int num3 = -1;
			Rect val2 = default(Rect);
			Rect val3 = default(Rect);
			for (int i = 0; i < pl.tracks.Count; i++)
			{
				string text = pl.tracks[i];
				((Rect)(ref val2))..ctor(0f, (float)i * 78f, ((Rect)(ref val)).width, 74f);
				HubUI.Slot(val2, ((Rect)(ref val2)).Contains(Event.current.mousePosition), PreviewTrack == text);
				((Rect)(ref val3))..ctor(((Rect)(ref val2)).x, ((Rect)(ref val2)).y, ((Rect)(ref val2)).width, 40f);
				float num4 = _edit.TrackVolume(text);
				float num5 = HubUI.SliderText(new Rect(((Rect)(ref val2)).x + 46f, ((Rect)(ref val2)).y + 40f - 2f, ((Rect)(ref val2)).width - 60f, 32f), Loc.T("track_vol"), num4, 0.05f, 2f, Mathf.RoundToInt(num4 * 100f) + "%", "0.##", 150f);
				num5 = Mathf.Round(num5 * 20f) / 20f;
				if (!Mathf.Approximately(num5, num4))
				{
					_edit.SetTrackVolume(text, num5);
				}
				if (HubUI.Button(new Rect(((Rect)(ref val3)).x + 4f, ((Rect)(ref val3)).y + 3f, 34f, 34f), (PreviewTrack == text) ? "||" : ">"))
				{
					TogglePreview(text);
				}
				GUI.Label(new Rect(((Rect)(ref val3)).x + 46f, ((Rect)(ref val3)).y, 26f, ((Rect)(ref val3)).height), i + 1 + ".", _dimStyle);
				GUI.Label(new Rect(((Rect)(ref val3)).x + 74f, ((Rect)(ref val3)).y, ((Rect)(ref val3)).width - 330f, ((Rect)(ref val3)).height), Track(text), _nameStyle);
				string text2 = null;
				if (!Storage.Exists(text))
				{
					text2 = Loc.T("missing");
				}
				else if (AudioCache.IsFailed(text))
				{
					text2 = Loc.T("failed");
				}
				else if (AudioCache.IsLoading(text))
				{
					text2 = Loc.T("loading");
				}
				if (text2 != null)
				{
					GUI.Label(new Rect(((Rect)(ref val3)).xMax - 250f, ((Rect)(ref val3)).y, 130f, ((Rect)(ref val3)).height), text2, _dimStyle);
				}
				if (HubUI.Button(new Rect(((Rect)(ref val3)).xMax - 116f, ((Rect)(ref val3)).y + 3f, 34f, 34f), "^") && i > 0)
				{
					num = i;
					num2 = -1;
				}
				if (HubUI.Button(new Rect(((Rect)(ref val3)).xMax - 78f, ((Rect)(ref val3)).y + 3f, 34f, 34f), "v") && i < pl.tracks.Count - 1)
				{
					num = i;
					num2 = 1;
				}
				if (HubUI.Button(new Rect(((Rect)(ref val3)).xMax - 40f, ((Rect)(ref val3)).y + 3f, 34f, 34f), "x"))
				{
					num3 = i;
				}
			}
			GUI.EndScrollView();
			if (num >= 0)
			{
				string value = pl.tracks[num];
				pl.tracks[num] = pl.tracks[num + num2];
				pl.tracks[num + num2] = value;
			}
			if (num3 >= 0)
			{
				if (PreviewTrack == pl.tracks[num3])
				{
					StopPreview();
				}
				pl.tracks.RemoveAt(num3);
			}
		}

		private void DrawPicker(Rect area, Playlist pl)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: 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)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = Storage.LibraryFiles();
			if (list.Count == 0)
			{
				GUI.Label(area, Loc.T("lib_empty"), _wrapDimStyle);
				return;
			}
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(0f, 0f, ((Rect)(ref area)).width - 18f, Mathf.Max((float)list.Count * 44f, ((Rect)(ref area)).height - 2f));
			_rightScroll = GUI.BeginScrollView(area, _rightScroll, val);
			Rect val2 = default(Rect);
			for (int i = 0; i < list.Count; i++)
			{
				string text = list[i];
				((Rect)(ref val2))..ctor(0f, (float)i * 44f, ((Rect)(ref val)).width, 40f);
				HubUI.Slot(val2, ((Rect)(ref val2)).Contains(Event.current.mousePosition), PreviewTrack == text);
				if (HubUI.Button(new Rect(((Rect)(ref val2)).x + 4f, ((Rect)(ref val2)).y + 3f, 34f, 34f), (PreviewTrack == text) ? "||" : ">"))
				{
					TogglePreview(text);
				}
				GUI.Label(new Rect(((Rect)(ref val2)).x + 46f, ((Rect)(ref val2)).y, ((Rect)(ref val2)).width - 240f, ((Rect)(ref val2)).height), Track(text), _nameStyle);
				if (pl.tracks.Contains(text))
				{
					GUI.Label(new Rect(((Rect)(ref val2)).xMax - 180f, ((Rect)(ref val2)).y, 174f, ((Rect)(ref val2)).height), Loc.T("in_playlist"), _dimStyle);
				}
				else if (HubUI.Button(new Rect(((Rect)(ref val2)).xMax - 40f, ((Rect)(ref val2)).y + 3f, 34f, 34f), "+"))
				{
					pl.tracks.Add(text);
					pl.enabled = true;
				}
			}
			GUI.EndScrollView();
		}

		private void DrawPathLine(Rect r, string buttonText, bool addToSlot)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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)
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref r)).x, ((Rect)(ref r)).y, ((Rect)(ref r)).width - 150f, ((Rect)(ref r)).height);
			_path = HubUI.TextField(val, _path) ?? "";
			if (_path.Length == 0)
			{
				GUI.Label(new Rect(((Rect)(ref val)).x + 10f, ((Rect)(ref val)).y, ((Rect)(ref val)).width - 20f, ((Rect)(ref val)).height), Loc.T("add_path"), _dimStyle);
			}
			if (!HubUI.Button(new Rect(((Rect)(ref r)).xMax - 140f, ((Rect)(ref r)).y, 140f, ((Rect)(ref r)).height), buttonText))
			{
				return;
			}
			string error;
			List<string> list = Storage.Import(_path, out error);
			if (error != null && list.Count == 0)
			{
				switch (error)
				{
				case "empty":
					Status(Loc.T("err_empty"), error: true);
					break;
				case "notfound":
					Status(Loc.T("err_notfound"), error: true);
					break;
				case "format":
					Status(Loc.T("err_format"), error: true);
					break;
				case "noaudio":
					Status(Loc.T("err_noaudio"), error: true);
					break;
				default:
					Status(Loc.F("err_other", error), error: true);
					break;
				}
				return;
			}
			_path = "";
			if (addToSlot && _view == View.Slot && _slot != null)
			{
				Playlist orCreate = _edit.GetOrCreate(_slot);
				int num = 0;
				foreach (string item in list)
				{
					if (!orCreate.tracks.Contains(item))
					{
						orCreate.tracks.Add(item);
						num++;
					}
				}
				orCreate.enabled = true;
				Status(Loc.F("added", num), error: false);
			}
			else
			{
				Status(Loc.F("imported", list.Count), error: false);
			}
		}

		private void DrawBottom(Rect win)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			if (_status != null && Time.unscaledTime < _statusUntil)
			{
				GUIStyle val = new GUIStyle(HubUI.LabelCenterStyle);
				if (_statusErr)
				{
					val.normal.textColor = HubUI.Danger;
				}
				GUI.Label(new Rect(((Rect)(ref win)).x + 24f, ((Rect)(ref win)).yMax - 100f, ((Rect)(ref win)).width - 48f, 28f), _status, val);
			}
			float num = ((Rect)(ref win)).center.x - 393f;
			float num2 = ((Rect)(ref win)).yMax - 66f;
			if (HubUI.Button(new Rect(num, num2, 250f, 46f), Loc.T("btn_vanilla")))
			{
				AllVanilla();
			}
			if (HubUI.Button(new Rect(num + 250f + 18f, num2, 250f, 46f), Loc.T("btn_cancel")))
			{
				CancelEdits();
			}
			if (HubUI.Button(new Rect(num + 536f, num2, 250f, 46f), Loc.T("btn_apply")))
			{
				ApplyEdits();
			}
		}

		private void Status(string text, bool error)
		{
			_status = text;
			_statusErr = error;
			_statusUntil = Time.unscaledTime + 5f;
		}

		private float PreviewVolume()
		{
			return Mathf.Min(1f, MusicDriver.GameMusicVolume * ((_edit != null) ? _edit.TrackVolume(PreviewTrack) : 1f));
		}

		private static string Seconds(float v)
		{
			return (v < 0.25f) ? Loc.T("off") : (v.ToString("0.#") + " " + Loc.T("sec"));
		}

		private static string Track(string libName)
		{
			return Path.GetFileNameWithoutExtension(libName);
		}
	}
	[BepInPlugin("kaefchik.musicplaylists", "MusicPlaylists", "1.6.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "kaefchik.musicplaylists";

		public const string NAME = "MusicPlaylists";

		public const string VERSION = "1.6.0";

		public static Plugin Instance;

		public static ConfigEntry<bool> ModEnabled;

		public static ConfigEntry<bool> ShowTrackName;

		public static ConfigEntry<float> PauseSeconds;

		public static ConfigEntry<bool> DuckOtherMods;

		public static ConfigEntry<float> FadeIn;

		public static ConfigEntry<float> FadeOut;

		public static ConfigEntry<bool> SwitchImmediately;

		public static ConfigEntry<float> SwitchFade;

		private Harmony _harmony;

		private PlaylistMenu _menu;

		private void Awake()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			Instance = this;
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Use your own playlists instead of the vanilla music. They start by themselves when you enter a biome, your base or a dungeon.");
			ShowTrackName = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowTrackName", true, "Show the name of your track in the top-left corner when it starts.");
			PauseSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "PauseBetweenTracksSeconds", 60f, new ConfigDescription("Silence between tracks for playlists with \"No pauses\" off, seconds. Volume always follows the game's Music volume slider.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>()));
			DuckOtherMods = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SilenceOtherMusicMods", true, "While your playlist plays, also silence music of other mods (Music Overhaul and the like), not only the vanilla music.");
			FadeIn = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FadeInSeconds", 3f, new ConfigDescription("Smooth start of every track of yours, seconds (0 = off).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			FadeOut = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FadeOutSeconds", 5f, new ConfigDescription("Fade-out at the end of every track of yours, seconds (0 = off).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>()));
			SwitchImmediately = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SwitchImmediately", true, "When you leave your base, enter a dungeon and so on: fade the current track out and start the new place's music right away. Off: the current track plays to its end first.");
			SwitchFade = ((BaseUnityPlugin)this).Config.Bind<float>("General", "SwitchFadeSeconds", 3f, new ConfigDescription("How long the current track fades out when the place changes, seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
			Storage.EnsureFolders();
			PlaylistStore.Load();
			_menu = new PlaylistMenu();
			ModHubAPI.Register("musicplaylists", "Music", (Action)_menu.Open, (string)null, (Sprite)null, (Color?)null, "A playlist for every biome", 60, (Func<bool>)null, (Action)_menu.Close, (Func<bool>)(() => _menu.IsOpen));
			_harmony = new Harmony("kaefchik.musicplaylists");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("MusicPlaylists 1.6.0 loaded. Library: " + Storage.LibraryDir));
		}

		private void Update()
		{
			MusicDriver.Tick();
			_menu.Update();
		}

		private void LateUpdate()
		{
			MusicDriver.LateTick();
		}

		private void OnGUI()
		{
			_menu.OnGUI();
		}

		private void OnDestroy()
		{
			MusicDriver.RestoreAll();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		public static void Log(string msg)
		{
			Plugin instance = Instance;
			if (instance != null)
			{
				((BaseUnityPlugin)instance).Logger.LogInfo((object)msg);
			}
		}

		public static void Warn(string msg)
		{
			Plugin instance = Instance;
			if (instance != null)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)msg);
			}
		}
	}
	[Serializable]
	public class Playlist
	{
		public string biome = "";

		public bool enabled = true;

		public bool shuffle = true;

		public bool continuous = true;

		public float volume = 1f;

		public List<string> tracks = new List<string>();
	}
	[Serializable]
	public class PlaylistDb
	{
		public int version = 1;

		public List<Playlist> playlists = new List<Playlist>();

		public Dictionary<string, float> trackVolumes = new Dictionary<string, float>();

		public const float MinTrackVolume = 0.05f;

		public const float MaxTrackVolume = 2f;

		public float TrackVolume(string libName)
		{
			float value;
			return (libName != null && trackVolumes.TryGetValue(libName, out value)) ? value : 1f;
		}

		public void SetTrackVolume(string libName, float v)
		{
			v = Mathf.Clamp(v, 0.05f, 2f);
			if (Mathf.Abs(v - 1f) < 0.005f)
			{
				trackVolumes.Remove(libName);
			}
			else
			{
				trackVolumes[libName] = v;
			}
		}

		public Playlist Find(string biome)
		{
			for (int i = 0; i < playlists.Count; i++)
			{
				if (playlists[i].biome == biome)
				{
					return playlists[i];
				}
			}
			return null;
		}

		public Playlist GetOrCreate(string biome)
		{
			Playlist playlist = Find(biome);
			if (playlist == null)
			{
				playlist = new Playlist
				{
					biome = biome
				};
				playlists.Add(playlist);
			}
			return playlist;
		}

		public PlaylistDb Clone()
		{
			PlaylistDb playlistDb = new PlaylistDb
			{
				version = version
			};
			if (trackVolumes != null)
			{
				foreach (KeyValuePair<string, float> trackVolume in trackVolumes)
				{
					playlistDb.trackVolumes[trackVolume.Key] = trackVolume.Value;
				}
			}
			foreach (Playlist playlist in playlists)
			{
				if (playlist != null)
				{
					playlistDb.playlists.Add(new Playlist
					{
						biome = (playlist.biome ?? ""),
						enabled = playlist.enabled,
						shuffle = playlist.shuffle,
						continuous = playlist.continuous,
						volume = playlist.volume,
						tracks = ((playlist.tracks != null) ? new List<string>(playlist.tracks) : new List<string>())
					});
				}
			}
			return playlistDb;
		}
	}
	public static class Storage
	{
		public static readonly string[] Extensions = new string[3] { ".ogg", ".wav", ".mp3" };

		private static List<string> _files = new List<string>();

		private static readonly Dictionary<string, long> _sizes = new Dictionary<string, long>();

		private static float _filesAt = -999f;

		public static string Root => Path.Combine(Paths.ConfigPath, "MusicPlaylists");

		public static string LibraryDir => Path.Combine(Root, "Library");

		public static string ImportDir => Path.Combine(Root, "Import");

		public static string DbPath => Path.Combine(Root, "playlists.json");

		public static void EnsureFolders()
		{
			try
			{
				Directory.CreateDirectory(LibraryDir);
				Directory.CreateDirectory(ImportDir);
				string path = Path.Combine(ImportDir, "_README.txt");
				if (!File.Exists(path))
				{
					File.WriteAllText(path, "EN: Drop .ogg / .wav / .mp3 files here, then press \"Take from Import folder\" in the Music menu.\r\nRU: Кинь сюда файлы .ogg / .wav / .mp3 и нажми \"Забрать из папки Import\" в меню Music.\r\nUK: Закинь сюди файли .ogg / .wav / .mp3 і натисни \"Забрати з теки Import\" у меню Music.\r\n");
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("Cannot create folders: " + ex.Message);
			}
		}

		public static bool IsAudio(string path)
		{
			string text = Path.GetExtension(path)?.ToLowerInvariant();
			return text != null && Array.IndexOf(Extensions, text) >= 0;
		}

		public static string FullPath(string libName)
		{
			return Path.Combine(LibraryDir, libName);
		}

		public static void Invalidate()
		{
			_filesAt = -999f;
		}

		public static List<string> LibraryFiles()
		{
			if (Time.unscaledTime - _filesAt < 1f)
			{
				return _files;
			}
			_filesAt = Time.unscaledTime;
			_sizes.Clear();
			try
			{
				_files = Directory.GetFiles(LibraryDir).Where(IsAudio).Select(Path.GetFileName)
					.OrderBy<string, string>((string n) => n, StringComparer.OrdinalIgnoreCase)
					.ToList();
			}
			catch
			{
				_files = new List<string>();
			}
			return _files;
		}

		public static bool Exists(string libName)
		{
			LibraryFiles();
			return _files.Contains(libName);
		}

		public static long SizeOf(string libName)
		{
			if (_sizes.TryGetValue(libName, out var value))
			{
				return value;
			}
			try
			{
				value = new FileInfo(FullPath(libName)).Length;
			}
			catch
			{
				value = 0L;
			}
			_sizes[libName] = value;
			return value;
		}

		public static List<string> Import(string path, out string error)
		{
			error = null;
			List<string> list = new List<string>();
			path = (path ?? "").Trim().Trim('"');
			if (path.Length == 0)
			{
				error = "empty";
				return list;
			}
			try
			{
				if (Directory.Exists(path))
				{
					foreach (string item in from x in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(IsAudio)
						orderby x
						select x)
					{
						string text = ImportFile(item);
						if (text != null)
						{
							list.Add(text);
						}
					}
					if (list.Count == 0)
					{
						error = "noaudio";
					}
					return list;
				}
				if (!File.Exists(path))
				{
					error = "notfound";
					return list;
				}
				if (!IsAudio(path))
				{
					error = "format";
					return list;
				}
				string text2 = ImportFile(path);
				if (text2 != null)
				{
					list.Add(text2);
				}
			}
			catch (Exception ex)
			{
				error = ex.Message;
				Plugin.Warn("Import failed: " + ex);
			}
			return list;
		}

		public static List<string> TakeFromImportFolder()
		{
			List<string> list = new List<string>();
			try
			{
				foreach (string item in from x in Directory.GetFiles(ImportDir, "*.*", SearchOption.AllDirectories).Where(IsAudio)
					orderby x
					select x)
				{
					string text = ImportFile(item);
					if (text != null)
					{
						list.Add(text);
						try
						{
							File.Delete(item);
						}
						catch
						{
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("Import folder failed: " + ex.Message);
			}
			return list;
		}

		private static string ImportFile(string src)
		{
			string fullPath = Path.GetFullPath(src);
			if (string.Equals(Path.GetDirectoryName(fullPath), Path.GetFullPath(LibraryDir), StringComparison.OrdinalIgnoreCase))
			{
				return Path.GetFileName(fullPath);
			}
			long length = new FileInfo(fullPath).Length;
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
			string text = Path.GetExtension(fullPath).ToLowerInvariant();
			for (int i = 1; i < 1000; i++)
			{
				string text2 = ((i == 1) ? (fileNameWithoutExtension + text) : (fileNameWithoutExtension + " (" + i + ")" + text));
				string text3 = FullPath(text2);
				if (!File.Exists(text3))
				{
					File.Copy(fullPath, text3);
					Plugin.Log("Imported " + fullPath + " -> " + text3);
					Invalidate();
					return text2;
				}
				if (new FileInfo(text3).Length == length)
				{
					return text2;
				}
			}
			return null;
		}

		public static bool Delete(string libName)
		{
			try
			{
				File.Delete(FullPath(libName));
				Invalidate();
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Warn("Delete failed: " + ex.Message);
				return false;
			}
		}

		public static void OpenFolder(string dir)
		{
			try
			{
				Application.OpenURL(new Uri(dir).AbsoluteUri);
			}
			catch
			{
			}
		}
	}
	public static class PlaylistStore
	{
		public static PlaylistDb Db = new PlaylistDb();

		public static void Load()
		{
			try
			{
				if (File.Exists(Storage.DbPath))
				{
					Db = PlaylistJson.Read(File.ReadAllText(Storage.DbPath)) ?? new PlaylistDb();
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("playlists.json is broken, a backup was made: " + ex.Message);
				try
				{
					File.Copy(Storage.DbPath, Storage.DbPath + ".broken", overwrite: true);
				}
				catch
				{
				}
				Db = new PlaylistDb();
			}
			if (Db.playlists == null)
			{
				Db.playlists = new List<Playlist>();
			}
			foreach (Playlist playlist in Db.playlists)
			{
				if (playlist.tracks == null)
				{
					playlist.tracks = new List<string>();
				}
			}
			Plugin.Log("Playlists loaded: " + Describe(Db));
		}

		private static string Describe(PlaylistDb db)
		{
			return (db.playlists.Count == 0) ? "none" : string.Join(", ", db.playlists.Select((Playlist p) => p.biome + "=" + p.tracks.Count));
		}

		public static void Save(PlaylistDb db)
		{
			db.playlists.RemoveAll((Playlist p) => p.tracks.Count == 0 && p.enabled && p.shuffle && p.continuous && Mathf.Approximately(p.volume, 1f));
			Db = db.Clone();