<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Ajout d'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>

<section>
    <p class="error" th:text="${error}"></p>
    <h1>Ajout d'un mélange pour<br>la recette <span th:text="${recipe.recipeCode}"></span></h1>

    <div class="form">
        <form action="/mix/creator" class="requireAuth" method="POST">
            <label for="mixType">Type de mélange: </label><input id="mixType" name="mixType" placeholder="ex: Teinture"
                                                                 required type="text"/>

            <!-- Information nécessaire à la création des mélanges -->
            <input id="recipeID" name="recipeID" th:value="${recipe.recipeID}" type="hidden"/>

            <table>
                <tr>
                    <td>
                        <!-- Produits -->
                        <table id="products">
                            <tr>
                                <th>Produit</th>
                                <th>Quantité
                                    <button type="button">+</button>
                                </th>
                            </tr>
                            <tr id="row_0">
                                <td><select class="materialList" name="product_0">
                                    <th:block th:each="material : ${materials}">
                                        <option th:class="'material_' + ${material.materialID}"
                                                th:classappend="${material.materialType.getUsePercentages()} ? usePercents"
                                                th:text="${!material.materialType.materialTypeName.equalsIgnoreCase('aucun')} ? '[' + ${material.materialType.prefix} + '] ' + ${material.materialCode} : ${material.materialCode}"
                                                th:value="${material.materialID}">
                                        </option>
                                    </th:block>
                                </select></td>
                                <td><input class="quantity" min="0" name="userQuantity" step="0.01" type="number"/>
                                    <span class="quantityUnit">mL</span></td>
                                <td>
                                    <button data-remove="0" onclick="removeRow(this)" type="button">Retirer</button>
                                </td>
                            </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
        let productNbr = 1;

        // Récupère les matériaux sous forme JSON depuis le thymeleaf et le valide.
        const productsText = "[[${materialsJson}]]";
        const products = JSON.parse(productsText.replace(/&quot;/g, '"'));

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

            products.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 productSelection = document.createElement("td");
            productSelection.appendChild(select);

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

            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(productSelection);
            row.appendChild(quantity);
            row.appendChild(removeColumn);

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

            productNbr++;
        });

        document.querySelectorAll(".materialList").forEach(e => {
            e.addEventListener("change", () => {

            });
        });
    })();

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

    function switchUnits(unitSelect) {
        document.querySelectorAll(".")
    }

    /*]]*/
</script>
</body>
</html>