const trackID = document.getElementById("track").dataset.id;
const titleInput = document.getElementById("title");
const descInput = document.getElementById("description");
const lyricsInput = document.getElementById("lyrics");
const saveBtn = document.getElementById("save");
const deleteBtn = document.getElementById("delete");

saveBtn.addEventListener("click", () => {
    fetch("/api/v1/track/" + trackID, {
        method: "PUT",
        body: JSON.stringify({
            title: titleInput.value,
            description: descInput.value,
            lyrics: lyricsInput.value,
        }),
        headers: { "Content-Type": "application/json" }
    }).then(res => {
        if (!res.ok) {
            res.text().then(error => {
                console.error(error);
                alert("Failed to update track: " + error);
            });
            return;
        }

        location = location;
    });
});

deleteBtn.addEventListener("click", () => {
    if (!confirm(
        "You are about to permanently delete \"" + titleInput.value + "\".\n" +
        "This action is irreversible. Do you wish to continue?")) return;

    fetch("/api/v1/track/" + trackID, {
        method: "DELETE",
    }).then(res => {
        if (!res.ok) {
            res.text().then(error => {
                console.error(error);
                alert("Failed to delete track: " + error);
            });
            return;
        }

        location = "/admin";
    });
});

[titleInput, descInput, lyricsInput].forEach(input => {
    input.addEventListener("change", () => {
        saveBtn.disabled = false;
    });
    input.addEventListener("keypress", () => {
        saveBtn.disabled = false;
    });
});

