<!DOCTYPE html>
<html lang="fr" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="fragments.html :: head(#{recipe.explore.title(${recipe.name})}, null)"></th:block>

    <link rel="stylesheet" href="/css/explore.css"/>
</head>
<body>

<!-- Fragment de l'entête -->
<header th:include="fragments.html :: header(true)"></header>
<!-- Corps de la page -->
<section>
    <div th:include="fragments.html :: messages"></div>

    <h1 th:text="#{recipe.explore.title(${recipe.name})}"></h1>
    <button id="modifyRecipe" type="button" th:text="#{menu.edit}"></button>
    <button id="useSubmit" type="button" th:text="#{keyword.use}"></button>
    <select id="unitsSelect"
            onchange="changeUnits(this, '.inventoryQuantity', '.inventoryQuantityUnits'); changeCustomizersUnits(this); changeCalculations(this)">
        <option selected="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>
    <br/>
    <br/>
    <button th:onclick="'location.href=\'' + @{|${baseUrl}/recipe/xls/__${recipe.id}__|} + '\''"
            th:text="#{recipe.xlsVersion}">
    </button>

    <input id="recipeId"
           name="recipeId"
           type="hidden"
           th:value="${recipe.id}"/>

    <!-- Formulaires sans autocomplétion pour éviter que le navigateur cache des valeurs lors d'un rafraichissement-->
    <form action="#" autocomplete="off">
        <div class="content">
            <div class="flexContent recipeDescription">
                <div>
                    <b th:text="#{recipe.color} + ':'"></b>
                    <p th:text="${recipe.name}">
                </div>
                <div>
                    <b th:text="#{keyword.company} + ':'"></b>
                    <p th:text="${recipe.company.name}">
                </div>
                <div>
                    <b th:text="#{recipe.description} + ':'"></b>
                    <p th:text="${recipe.description}">
                </div>
                <div>
                    <b th:text="#{recipe.sample} + ':'"></b>
                    <p th:text="${recipe.sample}">
                </div>
                <div>
                    <b th:text="#{recipe.approbationDate} + ':'"></b>
                    <p th:if="${recipe.approbationDate != ''}" th:text="${recipe.approbationDate}">
                    <p th:if="${recipe.approbationDate == ''}" th:text="#{recipe.warning.notApproved.short}">
                </div>
                <div th:if="${!recipe.remark.empty}">
                    <b th:text="#{recipe.remark} + ':'"></b>
                    <p th:text="${recipe.remark}">
                </div>
                <div>
                    <b th:text="#{recipe.notice} + ':'"></b>
                    <textarea class="rawInput toSave"
                              id="note"
                              cols="20"
                              rows="2"
                              name="note"
                              placeholder="N/A"
                              th:text="${recipe.note}" style="margin: 0"></textarea>
                </div>
                <button id="formSubmit"
                        type="button"
                        th:text="#{keyword.save}"
                        style="margin-top: 20px"></button>
            </div>
            <div th:if="${mixes.size() > 0}"
                 class="flexContent">
                <th:block th:each="mix : ${mixes}">
                    <div class="mixContainer">
                        <div class="mixInfo">
                            <b th:text="${mix.mixType.name} + ':'"></b><br/><br/>
                            <label th:for="'location' + ${mix.id}"
                                   th:text="' ' + #{mix.location} + ': '">

                            </label>
                            <input class="recipeLocation rawInput toSave"
                                   th:id="'location' + ${mix.id}"
                                   name="location"
                                   th:data-mixId="${mix.id}"
                                   th:value="${mix.location}"
                                   placeholder="N/A"
                                   type="text"/>
                        </div>
                        <div>
                            <table class="mix"
                                   th:id="'mix-' + ${mix.id}"
                                   th:data-mixId="${mix.id}">
                                <tr>
                                    <th th:text="#{keyword.material}"></th>
                                    <th th:text="#{keyword.type}"></th>
                                    <th style="min-width: auto !important;">
                                        <button
                                                type="button"
                                                data-hidden="true"
                                                onclick="hideQuantities(this)">
                                            ->
                                        </button>
                                    </th>
                                    <!-- Changement des quantités -->
                                    <th></th>
                                    <th th:text="#{keyword.units}"></th>
                                    <th th:text="#{keyword.calculation}"></th>
                                </tr>
                                <!-- Produits -->
                                <tr th:each="mixQuantity : ${mix.mixQuantities}"
                                    th:with="material = ${mixQuantity.material}"
                                    class="materialRow"
                                    th:data-materialtypename="${material.materialType.name}"
                                    th:id="'material-' + ${material.id}">
                                    <td class="materialCodeColumn materialCode"
                                        th:classappend="${material.isMixType()} ? '' : name"
                                        th:data-materialId="${material.id}"
                                        th:text="${material.name}"></td>
                                    <td th:text="${material.materialType.name}"></td>
                                    <td class="inventoryQuantityColumn">
                                        <p class="inventoryQuantity"
                                           th:data-quantityML="${mixQuantity.quantity}"
                                           th:text="${mixQuantity.quantity}"></p>
                                    </td>
                                    <td class="quantityColumn">
                                        <input
                                                class="quantityCustomizer noStyle"
                                                min="0.001" step="0.001"
                                                th:data-materialId="${material.id}"
                                                th:data-mixId="${mix.id}"
                                                th:data-quantityML="${mixQuantity.quantity}"
                                                th:data-usePercentages="${material.materialType.usePercentages}"
                                                th:data-isMixType="${material.isMixType()}"
                                                th:data-defaultvalue="${mixQuantity.quantity}"
                                                th:value="${mixQuantity.quantity}"
                                                th:readonly="${material.materialType.usePercentages}"
                                                type="number"/></td>
                                    <td class="unitsColumn">
                                        <p class="inventoryQuantityUnits"
                                           th:unless="${material.materialType.usePercentages}">mL</p>
                                        <p th:if="${material.materialType.usePercentages}">%</p>
                                    </td>
                                    <td class="calculationColumn">
                                        <p class="calculation" th:data-mixId="${mix.id}"
                                           th:data-materialId="${material.id}"></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="totalQuantityLabel" colspan="3">
                                        Total:
                                    </td>
                                    <td>
                                        <input
                                                class="totalQuantityCustomizer noStyle"
                                                type="number"
                                                min="0.001"
                                                step="0.001"
                                                th:data-mixId="${mix.id}"
                                        />
                                    </td>
                                    <td>
                                        <p class="inventoryQuantityUnits">mL</p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="mixActionsContainer">
                            <button class="useMixSubmit" type="button" th:text="#{keyword.use}"></button>
                            <button type="button" class="printButton" th:text="#{keyword.print}"></button>
                        </div>
                    </div>
                </th:block>
            </div>
            <div th:with="steps = ${recipe.recipeSteps}"
                 th:if="${recipe.recipeSteps.size() > 0}"
                 class="flexContent steps">
                <!-- Étapes -->
                <div style="min-width: 300px">
                    <div class="subtitle">
                        <h3 th:text="#{recipe.steps}"></h3>
                    </div>
                    <ol>
                        <li th:each="step : ${steps}"
                            th:text="${step.message}"></li>
                    </ol>
                </div>
            </div>
            <div th:if="${images.size() > 0}"
                 class="flexContent imagesContainer">
                <!-- Images -->
                <img th:each="image : ${images}"
                     th:alt="#{recipe.image.corrupted}"
                     th:src="@{|${baseUrl}/images/${image}|}"
                     class="recipeImage"
                     width="400px"
                     onmouseenter="startHovering()" onmouseleave="endHovering()"/>
            </div>
        </div>
    </form>
</section>
<!-- Fragment du pied de page -->
<footer th:include="fragments.html :: footer(null, true)"></footer>
<script th:include="fragments.html :: printStrings"></script>

<script>
    /*<![CDATA[*/
    $(() => {
        $("#modifyRecipe").on({
            click: function () {
                window.location.href = `/recipe/editor/${$("#recipeId").val()}`;
            }
        });

        $(".quantityCustomizer").each(function () {
            if ($(this).data("usepercentages")) {
                const parentQuantity = $(this).parents(".mixContainer").find(".quantityCustomizer").eq(0).data("quantityml");
                $(this).data({quantityml: percentageOf($(this).val(), parentQuantity)});
            }
        });

        $(".quantityCustomizer").on({
            keyup: function () {
                computeQuantities($(this));
            }
        });

        $(".totalQuantityCustomizer").on({
            keyup: function () {
                const mix = $(this).parents(".mixContainer");

                const value = $(this).val();
                const defaultValue = $(this).data("defaultvalue");

                const firstMaterial = mix.find(".quantityCustomizer").eq(0);
                const firstDefaultValue = firstMaterial.data("defaultvalue");
                const firstNewValue = (firstDefaultValue * value) / defaultValue;
                firstMaterial.val(round(firstNewValue));

                computeQuantities(firstMaterial, false);
            }
        });

        $("#formSubmit").on({
            click: function () {
                let formData = {};
                formData.recipeId = $("#recipeId").val();

                formData.locations = {};
                $(".recipeLocation").each(function () {
                    formData.locations[$(this).data("mixid")] = $(this).val();
                });

                formData.note = $("#note").val();

                sendPost(formData, "/recipe/explore", () => showMessage(errorMsg, generalErrorText));
            }
        });

        $("#useSubmit").on({
            click: function () {
                showConfirm(formatMessage("[[#{inventory.askUseRecipe}]]"), false, () => {
                    let formData = [];

                    let i = 0;
                    $(".mixContainer").each(function () {
                        formData[i++] = getMixQuantities($(this));
                    });

                    clearNotEnoughClasses();
                    sendPost(formData, "/inventory/use", r => displayNotEnoughReason(r));
                });
            }
        });

        $(".useMixSubmit").on({
            click: function () {
                showConfirm(formatMessage("[[#{inventory.askUseMix}]]"), false, () => {
                    let formData = [getMixQuantities($(this).parents(".mixContainer"))];

                    clearNotEnoughClasses();
                    sendPost(formData, "/inventory/use", r => displayNotEnoughReason(r));
                });
            }
        });

        $(".mix").each(function () {
            doCalculations(this)
        });

        const flashAmount = 3;
        $(".toSave").on({
            keyup: () => {
                const input = $("#formSubmit");
                input.stop(true, true)

                for (let i = 0; i < flashAmount; i++) {
                    input
                        .animate({backgroundColor: "#fff59d"}, 500)
                        .animate({backgroundColor: "#d7dedc"}, 500)
                }
            }
        });
    });

    function changeCustomizersUnits() {
        $(".quantityCustomizer").each(function () {
            const node = $(this);
            if (node.data("usepercentages") === "false") $(this).val(convertMlToUnit($(this).data("quantityml")));
        });
    }

    function clearNotEnoughClasses() {
        $(".notEnough").removeClass("notEnough");
    }

    function displayNotEnoughReason(reason) {
        const splitReason = reason.split("_");
        $(`#mix-${splitReason[0]}`).find(`#material-${splitReason[1]}`).addClass("notEnough");
    }

    function hideQuantities(button) {
        button = $(button);

        // Récupère la valeur, la convertit en bool, puis l'inverse
        let hiddenString = button.data("hidden");
        let hidden = hiddenString || hiddenString === "true";
        hidden = !hidden;

        button.parents(".mix").find(".inventoryQuantity").each(function () {
            const node = $(this);
            let css;

            if (hidden) {
                css = {minWidth: "auto"};
                node.parent().css(css);
                button.parent().css(css);

                node.hide();
                button.text("->");
            } else {
                css = {minWidth: 75};
                node.parent().css(css);
                button.parent().css(css);

                node.show();
                button.text("[[#{keyword.quantity}]]");
            }
        });

        button.data({hidden: hidden});
    }

    function sendPost(data, url, errorCallback) {
        axios.post(url, data)
            .then(r => {
                const data = r.data;

                if (data.success !== undefined) {
                    showMessage(successMsg, data.success.message);
                    return true;
                } else if (data.error !== undefined) {
                    showMessage(errorMsg, data.error.message);

                    if (typeof errorCallback !== 'undefined') {
                        errorCallback(data.reason);
                    }

                    return false;
                }
            })
            .catch(e => {
                console.log(e);
                showMessage(errorMsg, generalErrorText);
                return false;
            });
    }

    function getMixQuantities(mixContainer) {
        mix = $(mixContainer).find(".mix");

        const mixId = mix.data("mixid");
        const materials = [];
        const quantities = [];

        let j = 0;
        mix.find(".quantityCustomizer").each(function () {
            if (!$(this).data("ismixtype")) {
                materials[j] = $(this).data("materialid");
                quantities[j] = $(this).data("quantityml");

                j++;
            }
        });

        return {
            mixId: mixId,
            materials: materials,
            quantities: quantities
        };
    }

    function computeQuantities(customizer, computeTotal) {
        const mix = customizer.parents(".mixContainer");
        const mixCustomizers = mix.find(".quantityCustomizer");
        const firstInput = mixCustomizers.eq(0);

        const value = customizer.val();
        const defaultValue = customizer.data("defaultvalue");
        customizer.data("blabla", "balbla");

        mixCustomizers.each(function () {
            if (!$(this).data("usepercentages")) {
                const currentDefaultValue = $(this).data("defaultvalue");
                const newValue = (currentDefaultValue * value) / defaultValue;

                $(this).val(round(newValue));
                $(this).data({
                    quantityml: convertUnitToMl(newValue)
                });
            } else {
                $(this).data({
                    quantityml: percentageOf($(this).val(), firstInput.data("quantityml"))
                })
            }
        });

        doCalculations(mix, computeTotal);
    }

    function doCalculations(parent, computeTotal = true) {
        let lastQuantity = 0;
        parent = $(parent);

        parent.find(".quantityCustomizer").each(function () {
            const node = $(this);
            const materialId = node.data("materialid");
            const mixId = node.data("mixid");
            const quantity = round(convertMlToUnit(node.data("quantityml")));
            const p = parent.find(`.calculation[data-materialid='${materialId}'][data-mixid='${mixId}']`);
            const totalQuantity = round(lastQuantity + parseFloat(quantity));
            p.data({
                quantity: quantity,
                totalQuantity: totalQuantity
            });

            p.html(`<span>+${quantity}</span> (${totalQuantity})`);

            lastQuantity = totalQuantity;
        });

        if (computeTotal) {
            const totalQuantityCustomizer = parent.find(".totalQuantityCustomizer");
            totalQuantityCustomizer.val(lastQuantity);
            totalQuantityCustomizer.data({
                defaultvalue: lastQuantity
            });
        }
    }

    function changeCalculations() {
        const node = $(".calculation");
        const initialQuantity = node.data("quantity");

        node.each(function () {
            node.data({
                quantity: convertMlToUnit(initialQuantity),
                totalQuantity: convertMlToUnit(initialQuantity)
            });
        });

        $(".mix").each(e => doCalculations(e));
    }

    startHovering = () => $(".imagesContainer").addClass("hovering");
    endHovering = () => $(".imagesContainer").removeClass("hovering");

    /*]]>*/
</script>
<script type="module">
    /*<![CDATA[*/

    import {PtouchPrinter} from "/js/ptouchPrint.js";

    const recipeCode = "[[${recipe.name}]]";
    const banner = "[[${recipe.company.name}]]";
    const description = "[[${recipe.description}]]";

    async function printMix(printButton) {
        const mixContainer = $(printButton).parents(".mixContainer");
        const allBases = $(mixContainer).find(".materialRow[data-materialtypename='[[${T(dev.fyloz.trial.colorrecipesexplorer.config.Preferences).baseMaterialTypeName}]]']");
        console.log(allBases.length + " bases trouvées");
        if (allBases.length <= 0) {
            showMessage(errorMsg, noBaseError);
            return;
        }
        const baseName = allBases.eq(0).find(".materialCodeColumn").text();

        const printer = new PtouchPrinter({
            template: "Couleur",
            lines: [
                {name: "color", value: recipeCode},
                {name: "banner", value: banner},
                {name: "base", value: baseName},
                {name: "description", value: description}
            ]
        });
        const errorCode = await printer.print();
        switch (errorCode) {
            case -1:
                showMessage(errorMsg, bpacNotInstalledError);
                break;
            case 99:
                showMessage(errorMsg, printError);
                break;
            case 1:
                showMessage(successMsg, printingMessage);
                break;
            default:
                showMessage(errorMsg, generalErrorText);
                break;
        }
    }

    $('.printButton').on({
        click: function () {
            const node = $(this);
            showConfirm(confirmPrintMessage, false, () => {
                setTimeout(() => {
                    printMix(node);
                }, 300);
            });
        }
    });

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