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

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

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

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

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

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

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

	audio = new Audio(`/api/v/1.0/muzic?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;
		}, 750);
		audio.muzTimer = interval;
		document.getElementById(`play-${id}`).onclick = () =>
			stopMuzic(id, interval);
		document.getElementById(`pause-${id}`).onclick = () => pauseMuzic(id);

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