<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <!-- Fragment du head -->
    <th:block th:include="fragments.html :: head(#{menu.inventory}, null)"></th:block>

    <!-- Style de la page -->
    <style>
        td:not(.iconsColumn), th:not(.iconsColumn) {
            min-width: 100px;
        }

        table {
            margin: 50px auto;
            text-align: left;
            border-collapse: collapse;
        }

        section {
            text-align: center;
        }

        .materialRow {
            background-color: #fafafa;
        }

        .materialRow:nth-child(even) {
            background-color: #f5f5f5;
        }

        .materialRow:hover td {
            background-color: #e6e6e6;
        }

        .hidden, .hiddenWrongType {
            display: none;
        }

        .researchEnabled .materialRow:not(.researchResult) {
            display: none;
        }

        .options {
            padding-top: 80px !important;
            text-align: left;
        }

        .options div {
            padding: 20px 0;
        }

        .iconsColumn {
            padding: 0 20px;
        }

        .iconsColumn img {
            margin-top: 5px;
        }
    </style>
</head>
<body>

<!-- Fragment de l'entête -->
<header th:include="fragments.html :: header(false)"></header>
<!-- Corps de la page -->
<section>
    <th:block th:each="materialType : ${materialTypes}"
              th:if="${materialType.name.equalsIgnoreCase('aucun')}">
        <input id="anyTypeId" th:value="${materialType.id}" type="hidden"/>
    </th:block>

    <h1 th:text="#{menu.inventory}"></h1>

    <div id="researchBoxContainer">
        <input type="text" id="researchBox" class="noStyle" th:placeholder="#{keyword.search}"
               onkeyup="performSearch(this.value)"/>
    </div>

    <div th:include="fragments.html :: messages"></div>

    <div class="content">
        <div class="flexContent">
            <table class="materialsContainer" th:if="${!materials.empty}">
                <!--Titres des colonnes et options de recherche-->
                <tr>
                    <th th:text="#{keyword.material}"></th>
                    <th th:text="#{keyword.quantity}"></th>

                    <!--Unités de la quantité-->
                    <th th:text="#{keyword.units}"></th>

                    <th th:text="#{keyword.type}"></th>
                    <th></th>
                    <th class="iconsColumn"></th>
                </tr>

                <!--Produits-->
                <tr class="materialRow" th:each="material : ${materials}"
                    th:data-materialType="${material.materialType.id}"
                    th:data-materialId="${material.id}">
                    <td class="materialCode" th:data-materialId="${material.id}"
                        th:text="${material.name}"></td>
                    <td class="inventoryQuantity" th:data-quantityML="${material.inventoryQuantity}"
                        th:text="${material.inventoryQuantity}"></td>
                    <td><span class="inventoryQuantityUnits">mL</span></td>
                    <td class="materialType" th:text="${material.materialType.name}"></td>
                    <td>
                        <button class="modifyMaterial" th:data-materialId="${material.id}" type="button"
                                th:text="#{keyword.edit}"></button>
                    </td>
                    <td class="iconsColumn"></td>
                </tr>

            </table>
            <b th:if="${materials.empty}" class="error" th:text="#{material.error.anyFound}"></b>
        </div>
        <div class="flexContent options" style="display: flex; flex-direction: column">
            <div>
                <label for="lowQuantity" th:text="#{inventory.lowQuantity} + ':'"></label>
                <input id="lowQuantity" min="0" onkeyup="checkLowQuantity(this.value)" step="0.01"
                       style="width: 65px" type="number"/>
                <br/>
                <input id="hideOthers" onchange="hide(this.checked)" type="checkbox"/><label for="hideOthers"
                                                                                             th:text="#{inventory.hideOthers}"></label>
            </div>

            <div>
                <label for="materialTypeSelect" th:text="#{inventory.showOnly} + ':'"> </label>
                <select id="materialTypeSelect" name="materialTypeSelect" onchange="hideMaterialTypes(this)">
                    <th:block th:each="materialType : ${materialTypes}">
                        <option th:text="${materialType.name}"
                                th:value="${materialType.id}"></option>
                    </th:block>
                </select>
            </div>

            <div>
                <label for="units" th:text="#{keyword.units} + ':'"></label>
                <select id="units" name="units"
                        onchange="changeUnits(this, '.inventoryQuantity', '.inventoryQuantityUnits')">
                    <option selected value="mL" th:text="#{units.milliliters}"></option>
                    <option value="L" th:text="#{units.liters}"></option>
                    <option value="gal" th:text="#{units.gallons}"></option>
                </select>
            </div>
        </div>
    </div>


</section>
<!-- Fragment du pied de page -->
<footer th:include="fragments.html :: footer(null, true)"></footer>

<script th:include="fragments.html :: iconsPath"></script>
<script>
    /*<![CDATA[*/

    const defaultLowQuantity = 100;

    const materialRows = $(".materialRow");

    $(() => {
        // Rajoute un événement sur les boutons pour modifier les produits pour rediriger l'utilisateur vers la page de modification
        $(".modifyMaterial").on({
            click: function () {
                window.location.href = `/material/editor/${$(this).data("materialid")}`;
            }
        });

        $("#lowQuantity").val(defaultLowQuantity);
        checkLowQuantity(defaultLowQuantity);
    });

    // Ajoute la classe "lowQuantity" au produits qui ont une quantité en inventaire inférieur à la quantité limite définie
    function checkLowQuantity(value) {
        materialRows.each(function () {
            if (parseFloat($(this).find(".inventoryQuantity").text()) < value) {
                $(this).addClass("lowQuantity");
                const iconsColumn = $(this).find(".iconsColumn");
                if (iconsColumn.find("img").length === 0) {
                    const icon = $("<img />")
                        .attr({src: materialLowQuantityIconPath});
                    iconsColumn.append(icon);
                }
            } else {
                $(this).removeClass("lowQuantity");
                const iconsColumn = $(this).find(".iconsColumn");
                if (iconsColumn.find("img").length !== 0) {
                    console.log(iconsColumn.find("img"))
                    iconsColumn.find("img").remove();
                }
            }
        });

        hide($("#hideOthers").is(":checked"));
    }

    // Cache ou dévoile les produits qui ont la classe "lowQuantity", dépendamment du paramètre "checked"
    function hide(checked) {
        if (checked) {
            materialRows.each(function () {
                if (!$(this).hasClass("lowQuantity")) $(this).addClass("hidden");
                else $(this).removeClass("hidden");
            });
        } else {
            $(".hidden").each(function () {
                $(this).removeClass("hidden");
            });
        }
    }

    // Cache les produits qui ne sont pas du type de produit spécifié dans le paramètre "select", si le type de produit n'est pas "Aucun"
    function hideMaterialTypes(select) {
        select = $(select);

        const value = parseInt(select.val());
        const anyValue = parseInt($("#anyTypeId").val());

        materialRows.each(function () {
            if (value !== anyValue && parseInt($(this).data("materialtype")) !== value) $(this).addClass("hiddenWrongType");
            else $(this).removeClass("hiddenWrongType");
        });
    }

    function performSearch(searchString) {
        let found = false;

        const materialsContainer = $(".materialsContainer:not(.researchEnabled)");
        if (materialsContainer) {
            materialsContainer.addClass("researchEnabled");
        }

        $(".researchResult").each(function () {
            $(this).removeClass("researchResult");
        });

        materialRows.each(function () {
            if (!searchString || !searchString.replace(/\s/g, '').length) {
                $(this).addClass("researchResult");
                found = true;
            } else {
                const materialCode = $(this).find(".materialCode").text();
                const materialType = $(this).find(".materialType").text();

                if (searchIn(searchString, materialCode) || searchIn(searchString, materialType)) {
                    $(this).addClass("researchResult");
                    found = true;
                }
            }
        });

        if (!found) showMessage(warningMsg, researchNotFound, false);
        else hideMessage(warningMsg);
    }

    /*]]>*/
</script>

</body>
</html>
