<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Modifier un mélange</title>

    <link href="/css/main.css" rel="stylesheet"/>
    <link href="/css/forms.css" rel="stylesheet"/>

    <style>
        table {
            text-align: center;
        }
    </style>
</head>
<body th:with="nbrProducts = 0">
<th:block th:with="nbrSteps = 0">

    <section>
        <p class="error" th:text="${error}"></p>
        <h1>Modifier un mélange pour<br>la recette <span
                th:text="${recipeCode} + ' (' + ${mix.mixType.typeName} + ')'"></span></h1>
        <button id="removeMix" type="button">Supprimer</button>
        <br/>
        <br/>

        <div class="form">
            <form action="/mix/editor" class="requireAuth" method="POST">
                <!-- Information nécessaire à la création des mélanges -->
                <input name="mixID" th:value="${mix.mixID}" type="hidden"/>

                <table>
                    <tr>
                        <td colspan="2">
                            <table id="products">
                                <tr>
                                    <th>Produit</th>
                                    <th>Quantité
                                        <button type="button">+</button>
                                    </th>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <button class="returnIndex" type="button">Retour</button>
                        </td>
                        <td>
                            <button type="submit">Enregistrer</button>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </section>

    <script src="/js/main.js"></script>
    <script>
        /*<![CDATA[*/
        (() => {
            // Compteurs des produits et des étapes
            let productNbr = 0;

            const mixText = "[[${mixJson}]]";
            const mix = JSON.parse(mixText.replace(/&quot;/g, '"'));
            // Récupère les matériaux sous forme JSON depuis le thymeleaf et le valide.
            const materialsText = "[[${materialsJson}]]";
            const materials = JSON.parse(materialsText.replace(/&quot;/g, '"').replace(/&#39;/g, '\'').replace(/\r\n/g, ""));

            // Ajoute les produits déjà présents dans la recette
            mix.mixQuantities.forEach((q) => {
                let select = document.createElement("select");
                select.name = `product_${productNbr}`;

                materials.forEach(p => {
                    const materialID = p.materialID;
                    let option = document.createElement("option");
                    option.value = materialID;
                    option.selected = q.material.materialID === materialID;
                    // Rajoute le préfixe du type de produit si le type de produit n'est pas <<Aucun>>
                    option.innerHTML = (p.materialType.materialTypeName.toLowerCase() !== 'aucun' ? `[${p.materialType.prefix}] ` : "") + p.materialCode;

                    select.appendChild(option);
                });

                let input = document.createElement("input");
                input.type = "number";
                input.name = `quantity_${productNbr}`;
                input.value = q.quantity;
                input.step = 0.01;

                let product = document.createElement("td");
                product.appendChild(select);

                let quantity = document.createElement("td");
                quantity.appendChild(input);

                let removeButton = document.createElement("button");
                removeButton.type = "button";
                removeButton.dataset.remove = productNbr;
                removeButton.innerHTML = "Retirer";
                removeButton.onclick = removeRow(removeButton);

                let removeColumn = document.createElement("td");
                removeColumn.appendChild(removeButton);

                let row = document.createElement("tr");
                row.id = `row_${productNbr}`;
                row.appendChild(product);
                row.appendChild(quantity);
                row.appendChild(removeColumn);

                document.querySelector("#products tbody").appendChild(row);

                productNbr++;
            });

            document.querySelector("#products button").addEventListener("click", () => {
                let select = document.createElement("select");
                select.name = `product_${productNbr}`;

                materials.forEach(p => {
                    let option = document.createElement("option");
                    option.value = p.materialID;
                    // Rajoute le préfixe du type de produit si le type de produit n'est pas <<Aucun>>
                    option.innerHTML = (p.materialType.materialTypeName.toLowerCase() !== 'aucun' ? `[${p.materialType.prefix}] ` : "") + p.materialCode;
                    select.appendChild(option);
                });

                let input = document.createElement("input");
                input.type = "number";
                input.name = `quantity_${productNbr}`;
                input.step = 0.01;

                let product = document.createElement("td");
                product.appendChild(select);

                let quantity = document.createElement("td");
                quantity.appendChild(input);

                let removeButton = document.createElement("button");
                removeButton.type = "button";
                removeButton.dataset.remove = productNbr;
                removeButton.innerHTML = "Retirer";
                removeButton.onclick = removeRow(removeButton);

                let removeColumn = document.createElement("td");
                removeColumn.appendChild(removeButton);

                let row = document.createElement("tr");
                row.appendChild(product);
                row.appendChild(quantity);
                row.appendChild(removeButton);

                document.querySelector("#products tbody").appendChild(row);

                productNbr++;
            });

            document.querySelector("#removeMix").addEventListener("click", () => {
                let errorP = document.querySelector(".error");
                errorP.innerHTML = "";

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

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

                axios.post("/password/valid", data)
                    .then(r => {
                        if (r.data) {
                            document.location.href = `/mix/remover/${mix.mixID}`;
                        } 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);
                    });
            });
        })();

        function removeRow(e) {
            e.addEventListener("click", () => {
                document.querySelector(`#row_${e.dataset.remove}`).remove();
            });
        }

        /*]]*/
    </script>
</th:block>
</body>
</html>