document.getElementById("app-window").innerHTML =
	"<p><center>Загрузка произведений...</center></p>";

function toggleShow(authorId) {
	document.getElementById(`playlist-author-${authorId}`).hidden =
		!document.getElementById(`playlist-author-${authorId}`).hidden;
}

function showAudio(settingsAuthors, settingsAudio) {
	showAudio.settingsAuthors = settingsAuthors;
	showAudio.settingsAudio = settingsAudio;

	const step2 = (muzic) => {
		//console.log(muzic.items);
		const showedAuthors = [
			...new Set(muzic.items.map((i) => `author-${i.author_id}`)),
		];
		[...document.getElementsByClassName("author-element")].forEach((el) => {
			if (
				JSON.stringify(settingsAuthors) === "{}" &&
				JSON.stringify(settingsAudio) === "{}"
			) {
				if (!showedAuthors.includes(el.id)) {
					const id = el.id.slice(7);
					document.getElementById(`loader-muzic-${id}`).innerHTML =
						"<p><b>Пусто. Добавьте произведения</b></p>";
				}
				return;
			}
			el.hidden = !showedAuthors.includes(el.id);
		});

		muzic.items
			.sort((a, b) => a.date - b.date)
			.forEach((muzic) => {
				document.getElementById(
					`loader-muzic-${muzic.author_id}`,
				).hidden = true;
				if (muzic.is_data_exists)
					document.getElementById(
						`playlist-author-${muzic.author_id}`,
					).innerHTML += `<p><div id="muzic-item-${muzic.id}">
					<h6><button class="btn btn-secondary" id="edit-muzic-item-${
						muzic.id
					}" onclick='showEditMuzic(${muzic.id}, ${JSON.stringify(
						muzic.name,
					)}, ${
						muzic.is_data_exists
					});'><i class="bi bi-pencil-square"></i></button> ${muzic.name}</h6>
					<button class="btn btn-primary play-button" onclick="playMuzic(${
						muzic.id
					})" id="play-${muzic.id}">Прослушать</button>
					<button class="btn btn-primary pause-button" onclick="" id="pause-${
						muzic.id
					}" disabled>Пауза</button>
					<input class="road-muzic" type="range" id="road-${
						muzic.id
					}" name="stop" min="0" max="0" value="0" step="0.01" style="width: 70%;"/>
				</div></p>`;
				else
					document.getElementById(
						`playlist-author-${muzic.author_id}`,
					).innerHTML += `<p><div id="muzic-item-${muzic.id}">
					<h6>${muzic.name}</h6>
					<button class="btn btn-secondary" onclick='showEditMuzic(${
						muzic.id
					}, ${JSON.stringify(muzic.name)}, ${
						muzic.is_data_exists
					});' id="add-file-${muzic.id}" id="edit-muzic-item-${
						muzic.id
					}">Добавить звуковой файл</button>
				</div></p>`;
			});
	};
	api.getAuthors(settingsAuthors, (authors) => {
		document.getElementById("app-window").innerHTML = "";
		authors.items
			.sort((a, b) => a.date - b.date)
			.forEach((author) => {
				document.getElementById(
					"app-window",
				).innerHTML += `<div class="author-element" id="author-${author.id}">
			<div id="author-info-${author.id}"><h3>${author.name} <button class="btn btn-primary" id="edit-author-${author.id}" onclick="showAuthorEditor(${author.id}, '${author.name}');">Редактировать</button></h3></div>
			<p>Произведения</p>
			<hr/>
			<a href='#' onclick="toggleShow(${author.id})">Показать/Скрыть</a>
			<div id="playlist-author-${author.id}">
				<p id="loader-muzic-${author.id}">Загрузка..</p>
			</div>
			<div id="add-muzic-${author.id}" style="margin-bottom: 15px;"><center><button class="btn btn-primary" id="add-muzic-button-${author.id}">Добавить произведение</button></center></div>
		</div>`;
				const addMuzicButtonFunct = () =>
					setTimeout(
						() =>
							(document.getElementById(
								`add-muzic-button-${author.id}`,
							).onclick = async () => {
								// console.log('>>', author.id);
								document.getElementById(
									`add-muzic-${author.id}`,
								).innerHTML = `<p><input class="form-control" type="text" placeholder="Введите название произведения" id="muzic-name-input-${author.id}" style="width: 90%"></p>
	<p><button class="btn btn-primary" id="attach-file-${author.id}">Добавить файл (.mp3)</button>
	<button class="btn btn-primary" id="add-muzic-${author.id}">Добавить произведение</button>
	<button class="btn btn-danger" id="cancel-add-muzic-${author.id}">Отменить</button></p>`;
								setTimeout(() => {
									document.getElementById(
										`cancel-add-muzic-${author.id}`,
									).onclick = function () {
										document.getElementById(
											`add-muzic-${author.id}`,
										).innerHTML = `<center><button class="btn btn-primary" id="add-muzic-button-${author.id}">Добавить произведение</button></center>`;
										addMuzicButtonFunct();
									};

									document.getElementById(`add-muzic-${author.id}`).onclick =
										function () {
											if (
												document.getElementById(`muzic-name-input-${author.id}`)
													.value.length >= 2
											) {
												api.createMuzic(
													author.id,
													document.getElementById(
														`muzic-name-input-${author.id}`,
													).value,
													document.getElementById(`attach-file-${author.id}`)
														.filedata,
													() => {
														showAudio(settingsAuthors, settingsAudio);
													},
												);
												document.getElementById(
													`add-muzic-${author.id}`,
												).innerHTML = "Добавление файла...";
											}
										};

									document.getElementById(`attach-file-${author.id}`).onclick =
										function () {
											const input = document.createElement("input");
											input.type = "file";
											input.accept = "audio/mpeg";
											input.click();
											input.onchange = function (e) {
												function arrayBufferToBase64(buffer) {
													let binary = "";
													let bytes = new Uint8Array(buffer);
													let len = bytes.byteLength;
													for (let i = 0; i < len; i++) {
														binary += String.fromCharCode(bytes[i]);
													}
													return window.btoa(binary);
												}

												const file = e.target.files[0];
												// console.log(file);
												const reader = new FileReader();
												reader.readAsArrayBuffer(file);
												reader.onload = function () {
													// console.log('reader.result', reader.result);
													if (file.type === "audio/mpeg") {
														document.getElementById(
															`attach-file-${author.id}`,
														).filedata = arrayBufferToBase64(reader.result);
														document.getElementById(
															`attach-file-${author.id}`,
														).innerText = "Загружен файл: " + file.name;
													}
													// console.log(arrayBufferToBase64(reader.result));
												};
											};
										};
								}, 0);
							}),
						0,
					);
				addMuzicButtonFunct();
			});
		api.getMuzic(settingsAudio, step2);
		document.getElementById("app-window").innerHTML +=
			'<div id="add-author" style="margin-bottom: 15px;"><center><button class="btn btn-primary" id="add-author-button" onclick="addAuthorMenu();">Добавить исполнителя</button></center></div>';
	});
}

setTimeout(() => showAudio({}, {}), 0);

document.getElementById("search-input").onchange = function () {
	console.log(this.value);
	setTimeout(
		() =>
			showAudio(
				{},
				{
					q: this.value,
				},
			),
		0,
	);
};
