function get_field(e, el) {
    return e.form.elements[el].value
}

// EDIT ENTRY

function edit_entry(e) {
    e.preventDefault();
    let data = new URLSearchParams();
    data.append("message", get_field(e.target, "message"));
    data.append("name", get_field(e.target, "name"));
    data.append("website", get_field(e.target, "website"));
    data.append("hide_website", get_field(e.target, "hide_website"));
    fetch(`/api/guestbook/${get_field(e.target, "entry_id")}`, {method: "PATCH", body: data})
        .catch(e => console.log(e))
        .then(() => window.location = "/guestbook/admin");
}

for (const edit_entry_button of document.getElementsByName("edit-entry"))
    edit_entry_button.addEventListener("click", edit_entry);

// DELETE ENTRY

function delete_entry(e) {
    e.preventDefault();
    fetch(`/api/guestbook/${get_field(e.target, "entry_id")}`, {method:"DELETE"})
        .catch(e => console.log(e))
        .then(() => window.location = "/guestbook/admin");
}

for (const delete_entry_button of document.getElementsByName("delete-entry"))
    delete_entry_button.addEventListener("click", delete_entry);

// EDIT REPLY

function edit_reply(e) {
    e.preventDefault();
    let data = new URLSearchParams();
    data.append("message", get_field(e.target, "message"));
    fetch(`/api/guestbook/${get_field(e.target, "entry_id")}/reply`, {method: "PATCH", body: data})
        .catch(e => console.log(e))
        .then(() => window.location = "/guestbook/admin");
}

for (const edit_reply_button of document.getElementsByName("edit-reply"))
    edit_reply_button.addEventListener("click", edit_reply);

// DELETE REPLY

function delete_reply(e) {
    e.preventDefault();
    fetch(`/api/guestbook/${get_field(e.target, "entry_id")}/reply`, {method:"DELETE"})
        .catch(e => console.log(e))
        .then(() => window.location = "/guestbook/admin");
}

for (const delete_reply_button of document.getElementsByName("delete-reply"))
    delete_reply_button.addEventListener("click", delete_reply);

// NEW REPLY

function send_reply(e) {
    e.preventDefault();
    let data = new URLSearchParams();
    data.append("message", get_field(e.target, "message"));
    fetch(`/api/guestbook/${get_field(e.target, "entry_id")}/reply`, {method: "POST", body: data})
        .catch(e => console.log(e))
        .then(() => window.location = "/guestbook/admin");
}

for (const reply_button of document.getElementsByName("reply"))
    reply_button.addEventListener("click", send_reply);