(() => {

    // Ajoute Axios
    const axiosElement = document.createElement("script");
    axiosElement.src = "/js/libs/axios.min.js";
    body.appendChild(axiosElement);

    // Ajoute jQuery
    const jqueryElement = document.createElement("script");
    jqueryElement.src = "/js/libs/jquery-3.4.1.min.js";
    body.appendChild(jqueryElement);

    const body = $("body");
    const errorP = $(".error");

    axiosElement.onload = () => {
        // Ajoute le header
        axios.get('/header.html')
            .then(r => {
                const header = document.createElement("header");
                header.innerHTML = r.data;
                body.insertBefore(header, document.querySelector("section"));
            })
            .catch(e => {
                console.log(e);
                errorP.innerHTML = "Une erreur est survenue lors de la récupération de l'entête";
            });

        // Vérifie si les SIMDUTs sont présents
        document.querySelectorAll(".materialCode").forEach(e => {
            const materialID = e.getAttribute("data-materialID");
            axios.get(`/simdut/${materialID}`)
                .catch(err => {
                    if (err.response.status === 404) {
                        e.parentElement.classList.add("nosimdut");
                        e.parentElement.title = "Aucun fichier SIMDUT trouvé";
                    } else {
                        console.log(e);
                    }
                });
        });
    };

    document.querySelectorAll(".returnIndex").forEach((e) => {
        e.addEventListener("click", () => {
            document.location.href = "/";
        });
    });

    document.querySelectorAll(".materialCode").forEach((e) => {
        const materialID = e.getAttribute("data-materialID");
        e.addEventListener("click", () => {
            window.open("/simdut/" + materialID, "_blank");
        });
    });

    document.querySelectorAll("img").forEach((e) => {
        e.addEventListener("click", () => {
            window.open(e.src, "_blank");
        });
    });

    document.querySelectorAll(".requireAuth").forEach((e) => {
        e.onsubmit = () => {
            checkPassword(e);
            return false;
        };
    });

    document.querySelectorAll(".requireAuth-remover").forEach((e) => {
        e.querySelectorAll(".remover").forEach(elem => {
            elem.addEventListener("click", () => {
                e.action += elem.getAttribute("data-recipeID");
                checkPassword(e);
            });
        });
    });

    document.querySelectorAll(".companyTabTitle").forEach(e => {
        e.addEventListener("click", () => {
            const companyName = e.getAttribute("data-companyName");
            const table = document.getElementById("recipes_" + companyName);

            if (table.style.display === "none") {
                table.style.display = "table";
            } else {
                table.style.display = "none";
            }
        });
    });

    // Ajoute le favicon
    let faviconElement = document.createElement("link");
    faviconElement.rel = "icon";
    faviconElement.href = "/favicon.png";
    document.querySelector("head").appendChild(faviconElement);

    function checkPassword(form) {
        errorP.innerHTML = "";

        const password = prompt("Quel est votre mot de passe?");

        let data = {};
        data.password = password;

        axios.post("/password/valid", data)
            .then(r => {
                console.log(r);
                if (r.data) {
                    form.submit();
                } else {
                    errorP.innerHTML = "Votre mot de passe n'est pas valide";
                }
            })
            .catch(e => {
                errorP.innerHTML = "Une erreur est survenue lors de l'envoie des informations vers le serveur.";
                console.log(e);
            });
    }
})();


const lTomL = 1000;
const galTomL = 3785.41;

// Change les unités selon la sélection de l'utilisateur
function changeUnits(unitSelect, quantitiesSelector, unitsSelector) {
    document.querySelectorAll(unitsSelector).forEach(e => {
        e.innerText = unitSelect.value;

        // Modifie la quantitée
        const quantityElem = e.parentElement.parentElement.querySelector(quantitiesSelector);
        const originalQuantity = parseInt(quantityElem.dataset.quantityml);

        switch (unitSelect.value) {
            case "L":
                quantityElem.innerText = originalQuantity / lTomL;
                break;
            case "gal":
                quantityElem.innerText = originalQuantity / galTomL;
                break;
            default:
                quantityElem.innerText = originalQuantity;
                break;
        }

        // Arrondi à deux décimaux
        quantityElem.innerText = Math.round(quantityElem.innerText * 100) / 100;
    });
}