let audio = new Audio("/api/v/1.0/music");

function stopMusic(id, interval) {
	audio.pause();
	// pauseMusic(id);
	audio.currentTime = 0;
	document.getElementById(`play-${id}`).innerText = "Прослушать";
	document.getElementById(`play-${id}`).disabled = false;
	document.getElementById(`pause-${id}`).innerText = "Пауза";
	document.getElementById(`pause-${id}`).disabled = true;
	document.getElementById(`play-${id}`).onclick = () => playMusic(id);

	clearInterval(interval);
	document.getElementById(`road-${id}`).value = 0;
	document.getElementById(`road-${id}`).max = 0;
}

function pauseMusic(id) {
	document.getElementById(`play-${id}`).disabled = true;
	document.getElementById(`pause-${id}`).innerText = "Продолжить";
	document.getElementById(`pause-${id}`).onclick = () => resumeMusic(id);
	audio.pause();
}

function resumeMusic(id) {
	document.getElementById(`play-${id}`).disabled = false;
	document.getElementById(`pause-${id}`).innerText = "Пауза";
	document.getElementById(`pause-${id}`).onclick = () => pauseMusic(id);
	audio.play();
}

function changeTime(value, id) {
	audio.currentTime = value;
}

function playMusic(id) {
	audio.pause();
	audio.currentTime = 0;
	if (audio.muzId !== undefined) stopMusic(audio.muzId, audio.muzTimer);

	audio = new Audio(`/api/v/1.0/music?id=${id}`);
	audio.onloadedmetadata = function () {
		audio.muzId = id;
		document.getElementById(`play-${id}`).innerText = "Остановить";
		document.getElementById(`pause-${id}`).disabled = false;
		document.getElementById(`road-${id}`).max = audio.duration;
		audio.play();

		const interval = setInterval(() => {
			document.getElementById(`road-${id}`).value = audio.currentTime;
			if (audio.currentTime >= audio.duration && document.getElementById(`repeat-mode-${id}`).checked) {
				audio.currentTime = 0;
				audio.play();
			}
		}, 750);
		audio.muzTimer = interval;
		document.getElementById(`play-${id}`).onclick = () =>
			stopMusic(id, interval);
		document.getElementById(`pause-${id}`).onclick = () => pauseMusic(id);

		document.getElementById(`road-${id}`).onchange = function () {
			// console.log('value', this.value);
			changeTime(this.value, id);
		};
	};
}
