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

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

function removeMuzic(muzicId) {
	api.deleteMuzic(muzicId, (res) => {
		showAudio(showAudio.settingsAuthors, showAudio.settingsAudio);
	});
}

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

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

	setTimeout(() => bindShowEditMuzicButtons(muzicId, muzicName, dataExists), 5);
}
