function removeAuthor(authorId) {
	api.removeAuthor(authorId, () => {
		showAudio(showAudio.settingsAuthors, showAudio.settingsAudio);
	});
}

function editAuthor(authorId) {
	const name = document.getElementById(`input-author-name-${authorId}`).value;
	api.editAuthor(authorId, name, (res) => {
		if (res !== undefined) removeAuthorEditor(authorId, name);
	});
}

function removeAuthorEditor(authorId, authorName) {
	document.getElementById(
		`author-info-${authorId}`,
	).innerHTML = `<h3>${authorName} <button class="btn btn-primary" id="edit-author-${authorId}" onclick="showAuthorEditor(${authorId}, '${authorName}');">Редактировать</button></h3>`;
	setTimeout(() => {
		document.getElementById(`edit-author-${authorId}`).onclick = () =>
			showAuthorEditor(authorId, authorName);
	}, 5);
}

function showAuthorEditorButtonInit(authorId) {
	const authorName = document.getElementById(
		`author-info-${authorId}`,
	).lastValue;
	document.getElementById(`cancel-edit-author-${authorId}`).onclick = () =>
		removeAuthorEditor(authorId, authorName);
	document.getElementById(`remove-author-${authorId}`).onclick = () =>
		removeAuthor(authorId);
	document.getElementById(`edit-author-${authorId}`).onclick = () =>
		editAuthor(authorId);
	// document.getElementById(`add-author-button`).onclick = addAuthor;
}

function showAuthorEditor(authorId, lastValue) {
	document.getElementById(`author-info-${authorId}`).lastValue = lastValue;
	document.getElementById(
		`author-info-${authorId}`,
	).innerHTML = `<h3><input id="input-author-name-${authorId}" class="form-control" type="text", value=${JSON.stringify(
		lastValue,
	)}/>
	<button class="btn btn-primary" id="edit-author-${authorId}">Сохранить</button>
	<button class="btn btn-secondary" id="cancel-edit-author-${authorId}">Отмена</button>
	<button class="btn btn-danger" id="remove-author-${authorId}">Удалить</button>
	</h3>`;
	setTimeout(() => showAuthorEditorButtonInit(authorId), 5);
}

function addAuthor() {
	const name = document.getElementById(`author-name-input`).value;
	document.getElementById("add-author").innerHTML =
		"<center><p>Добавляем..</center></p>";
	api.createAuthor(name, () => {
		showAudio(showAudio.settingsAuthors, showAudio.settingsAudio);
	});
}

function rmAuthorMenuButtonInit() {
	document.getElementById(`add-author-button`).onclick = addAuthorMenu;
}

function removeAuthorMenu() {
	document.getElementById(
		"add-author",
	).innerHTML = `<center><button class="btn btn-primary" id="add-author-button">Добавить исполнителя</button></center>`;
	setTimeout(rmAuthorMenuButtonInit, 5);
}

function authorMenuButtonInit() {
	document.getElementById(`cancel-add-author`).onclick = removeAuthorMenu;
	document.getElementById(`add-author-button`).onclick = addAuthor;
}

function addAuthorMenu() {
	document.getElementById(
		"add-author",
	).innerHTML = `<center><p><input class="form-control" type="text" placeholder="Введите название исполнителя" id="author-name-input" style="width: 90%"></p>
	<button class="btn btn-primary" id="add-author-button">Добавить исполнителя</button>
	<button class="btn btn-danger" id="cancel-add-author">Отменить</button></p></center>`;

	setTimeout(authorMenuButtonInit, 5);
}

function selectFile(musicId) {
	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(`edit-attach-file-${musicId}`).filedata =
					arrayBufferToBase64(reader.result);
				document.getElementById(`edit-attach-file-${musicId}`).innerText =
					"Загружен файл: " + file.name;
				document.getElementById(`delete-attach-${musicId}`).disabled = false;
			}
			// console.log(arrayBufferToBase64(reader.result));
		};
	};
}

function editMusic(musicId, musicName) {
	api.editMusic(
		musicId,
		musicName,
		document.getElementById(`edit-attach-file-${musicId}`).filedata,
		undefined,
		(res) => {
			showAudio(showAudio.settingsAuthors, showAudio.settingsAudio);
		},
	);
}

function removeMusic(musicId) {
	api.deleteMusic(musicId, (res) => {
		showAudio(showAudio.settingsAuthors, showAudio.settingsAudio);
	});
}

function bindShowEditMusicButtons(musicId, musicName, dataExists) {
	document.getElementById(`cancel-edit-music-${musicId}`).onclick = () => {
		document.getElementById(`music-item-${musicId}`).innerHTML = dataExists
			? `<h6><button class="btn btn-secondary" id="edit-music-item-${musicId}" onclick='showEditMusic(${musicId}, ${JSON.stringify(
					musicName,
			  )}, ${dataExists});'><i class="bi bi-pencil-square"></i></button> ${musicName}</h6>
					<button class="btn btn-primary play-button" onclick="playMusic(${musicId})" id="play-${musicId}">Прослушать</button>
					<button class="btn btn-primary pause-button" onclick="" id="pause-${musicId}" disabled>Пауза</button>
					<input class="road-music" type="range" id="road-${musicId}" name="stop" min="0" max="0" value="0" step="0.01" style="width: 70%;"/>`
			: `<p><div id="music-item-${musicId}">
					<h6>${musicName}</h6>
					<button class="btn btn-secondary" onclick='showEditMusic(${musicId}, ${JSON.stringify(
						musicName,
					)}, ${dataExists});' id="add-file-${musicId}" id="edit-music-item-${musicId}">Добавить звуковой файл</button>
				</div></p>`;
	};
	document.getElementById(`edit-attach-file-${musicId}`).onclick = () =>
		selectFile(musicId);
	document.getElementById(`delete-attach-${musicId}`).onclick = () => {
		document.getElementById(`edit-attach-file-${musicId}`).innerText =
			"Добавить файл (.mp3)";
		document.getElementById(`edit-attach-file-${musicId}`).filedata = null;
		document.getElementById(`delete-attach-${musicId}`).disabled = true;
	};
	document.getElementById(`edit-music-${musicId}`).onclick = () =>
		editMusic(musicId, document.getElementById(`music-edit-name-input-${musicId}`).value);
	document.getElementById(`delete-music-${musicId}`).onclick = () =>
		removeMusic(musicId);
}

function showEditMusic(musicId, musicName, dataExists) {
	document.getElementById(
		`music-item-${musicId}`,
	).innerHTML = `<p><input class="form-control" type="text" placeholder="Введите название произведения" value=${JSON.stringify(
		musicName,
	)} id="music-edit-name-input-${musicId}" style="width: 90%"></p>
	<p><button class="btn btn-primary" id="edit-attach-file-${musicId}">${
		dataExists ? "Сменить файл (.mp3)" : "Добавить файл (.mp3)"
	}</button>
	<button class="btn btn-danger" id="delete-attach-${musicId}"${
		dataExists ? "" : " disabled"
	}>Удалить файл</button>
	<button class="btn btn-primary" id="edit-music-${musicId}">Редактировать произведение</button>
	<button class="btn btn-secondary" id="cancel-edit-music-${musicId}">Отменить</button>
	<button class="btn btn-danger" id="delete-music-${musicId}">Удалить произведение</button></p>`;

	setTimeout(() => bindShowEditMusicButtons(musicId, musicName, dataExists), 5);
}
