// Si vous modifiez ce fichier, exécutez "npm run build" pour que votre server utilise la nouvelle version. Sinon le navigateur conserve l'ancienne version en cache.
window.addEventListener("load", function()
{
    document.querySelectorAll("button.login").forEach(function(element)
    {
        element.addEventListener("click", function()
        {
            emailForm = formLogin.elements["email"].value.trim();
            passwordForm = formLogin.elements["password"].value.trim();

            if (emailForm.length > 0 && passwordForm.length > 0)
            {
                fetch("/api/v1/auth/login", {
                    method: "POST",
                    headers: {
                        "Accept": "application/json",
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        email: emailForm,
                        password: passwordForm
                    })
                }).then(function()
                {
                    location.reload();
                })
            }
            else
            {
                alert("email et/ou password est vide");
            }
        });
    });
});

function ajouterCours(group_id) {
    fetch("/api/v1/cours", {
        method: "POST",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            group_id: group_id,
        })
    }).then(function()
    {
        location = `/cours/${group_id}`
    })
}

function retirerCours(group_id) {
    fetch("/api/v1/cours/" + group_id, {
        method: "DELETE",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            group_id: group_id,
        })
    }).then(() => {
        location = '/cours'
    }).catch(err => {
        console.error(err)
    })
}

function retirerDevoir(cours_id, devoir_id) {
    fetch("/devoir/devoir/" + cours_id + "/" +  devoir_id, {
        method: "DELETE",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            devoir_id: devoir_id,
            cours_id: cours_id,
        })
    }).then(() => {
        location = '/devoir/devoirs/' + cours_id
    }).catch(err => {
        console.error(err)
    })
}
