const artistID = document.getElementById("artist").dataset.id;
const nameInput = document.getElementById("name");
const avatarImg = document.getElementById("avatar");
const removeAvatarBtn = document.getElementById("remove-avatar");
const avatarInput = document.getElementById("avatar-file");
const websiteInput = document.getElementById("website");
const saveBtn = document.getElementById("save");
const deleteBtn = document.getElementById("delete");

saveBtn.addEventListener("click", () => {
    fetch("/api/v1/artist/" + artistID, {
        method: "PUT",
        body: JSON.stringify({
            name: nameInput.value,
            website: websiteInput.value,
            avatar: avatarImg.src,
        }),
        headers: { "Content-Type": "application/json" }
    }).then(res => {
        if (!res.ok) {
            res.text().then(error => {
                console.error(error);
                alert("Failed to update release: " + error);
            });
            return;
        }

        location = location;
    });
});

deleteBtn.addEventListener("click", () => {
    if (artistID != prompt(
        "You are about to permanently delete " + artistID + ". " +
        "This action is irreversible. " +
        "Please enter \"" + artistID + "\" to continue.")) return;
    fetch("/api/v1/artist/" + artistID, {
        method: "DELETE",
    }).then(res => {
        if (!res.ok) {
            res.text().then(error => {
                console.error(error);
                alert("Failed to delete release: " + error);
            });
            return;
        }

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

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

avatarImg.addEventListener("click", () => {
    avatarInput.addEventListener("change", () => {
        if (avatarInput.files.length > 0) {
            const reader = new FileReader();
            reader.onload = e => {
                const data = e.target.result;
                avatarImg.src = data;
                saveBtn.disabled = false;
            };
            reader.readAsDataURL(avatarInput.files[0]);
        }
    });
    avatarInput.click();
});

removeAvatarBtn.addEventListener("click", () => {
    avatarImg.src = "/img/default-avatar.png"
    saveBtn.disabled = false;
});
