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

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

    <style>
        .content {
            flex-direction: row;
        }

        .mix {
            display: flex;
            flex-direction: row;
            width: 368px;
        }

        .mixInfo {
            display: flex;
            flex-direction: column;
            min-width: 150px;
            max-width: 200px;
            text-align: left;
        }

        .materialCodeColumn, .materialTypeColumn, .materialQuantityColumn {
            min-width: 112px;
        }

        .imageContainer {
            display: flex;
            flex-direction: column;
            padding: 10px;
        }

        #steps input {
            min-width: 300px;
            text-align: left;
        }
    </style>
</head>
<body>

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

    <h1 th:text="#{recipe.editing.title(${recipe.name})}"></h1>
    <button id="gotoRecipe" type="button" th:text="#{keyword.see}"></button>

    <form th:action="@{/recipe/editor}" th:object="${recipe}" class="requireAuth" method="POST">
        <div class="content">
            <!-- Informations -->
            <div class="flexContent" style="padding-top: 40px">
                <input type="hidden" name="recipe" id="recipeId" th:value="${recipe.id}"/>
                <div class="formWrap">
                    <div class="formColumn">
                        <div>
                            <label th:for="${#ids.next('id')}" th:text="#{keyword.id}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('name')}" th:text="#{recipe.color}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('banner')}" th:text="#{keyword.company}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('description')}" th:text="#{recipe.description}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('sample')}" th:text="#{recipe.sample}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('approbationDate')}" th:text="#{recipe.approbationDate}"></label>
                        </div>
                        <div>
                            <label th:for="${#ids.next('remark')}" th:text="#{recipe.remark}"></label>
                        </div>
                    </div>
                    <div class="formColumn">
                        <div>
                            <input type="number" th:field="*{id}" required readonly/>
                        </div>
                        <div>
                            <input type="text" th:field="*{name}" required/>
                        </div>
                        <div>
                            <select th:field="*{company}">
                                <option th:each="company : ${companies}"
                                        th:selected="${recipe.company.equals(company)}"
                                        th:text="${company.name}"
                                        th:value="${company.id}"></option>
                            </select>
                        </div>
                        <div>
                            <input type="text" th:field="*{description}"/>
                        </div>
                        <div>
                            <input type="number" th:field="*{sample}"/>
                        </div>
                        <div>
                            <input type="date" th:field="*{approbationDate}"/>
                        </div>
                        <div>
                            <textarea cols="20" rows="2" th:field="*{remark}"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Mélanges -->
            <div class="flexContent mixes">
                <div style="text-align: right">
                    <button id="newMix" type="button" th:text="#{recipe.edit.addMix}"></button>
                </div>
                <div th:each="mix : ${mixes}" class="mixContainer">
                    <div class="mixInfo">
                        <b th:text="${mix.mixType.name} + ':'"></b>
                        <button class="mixEditor" th:data-mixId="${mix.id}" type="button"
                                th:text="#{keyword.edit}" style="width: 75%"></button>
                    </div>
                    <div>
                        <table class="mix"
                               th:id="'mix-' + ${mix.id}">
                            <tr>
                                <th th:text="#{keyword.material}"></th>
                                <th th:text="#{keyword.type}"></th>
                                <th th:text="#{keyword.quantity}"></th>
                            </tr>
                            <!-- Produits -->
                            <tr th:each="mixQuantity : ${mix.mixQuantities}"
                                th:with="material = ${mixQuantity.material}"
                                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 class="materialTypeColumn"
                                    th:text="${material.materialType.name}"></td>
                                <td class="materialQuantityColumn"
                                    th:text="${mixQuantity.quantity} + ' ' + ${material.materialType.usePercentages ? '%' : 'mL'}"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <!-- Étapes -->
            <div class="flexContent" id="steps" style="display: flex; flex-direction: column">
                <div style="display: flex; flex-direction: row; justify-content: center">
                    <h3 th:text="#{recipe.steps}" style="margin: 0"></h3>
                    <button id="addStep" type="button" style="width: 20px; height: 20px; margin: 0 20px">+</button>
                </div>

            </div>
            <!-- Images -->
            <div class="flexContent" style="display: flex; flex-direction: column">
                <div style="display: flex; flex-direction: row; justify-content: center;">
                    <h3 th:text="#{keyword.images}" style="margin: 0"></h3>
                    <button id="addImage" type="button" style="width: 20px; height: 20px; margin: 0 20px;">+</button>
                </div>
                <div class="imagesContainer" style="width:100% !important">
                    <div th:each="image : ${images}" class="imageContainer">
                        <img th:alt="#{recipe.image.corrupted}"
                             th:src="@{|${baseUrl}/images/${image}|}"
                             width="400px"/>
                        <div>
                            <button class="deleteImg" th:data-image="${image}" type="button" style="width: 100%">
                                <span th:text="#{keyword.delete}"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div th:include="fragments.html :: formEndButtons" style="width: 100%; margin-bottom:50px"></div>
        </div>
    </form>
</section>
<!-- Fragment du pied de page -->
<footer th:include="fragments.html :: footer(null, true)"></footer>


<script>
    /*<![CDATA[*/
    const removeText = "[[#{keyword.remove}]]";

    let stepNbr = 0;

    $(() => {
        const recipeId = $("#id").val();

        $("#gotoRecipe").on({
            click: function () {
                window.open(`/recipe/explore/${recipeId}`, "_blank");
            }
        });

        $(".mixEditor").on({
            click: function () {
                const mixId = $(this).data("mixid");
                window.location.href = `/mix/editor/${mixId}`;
            }
        })

        $("#newMix").on({
            click: function () {
                window.location.href = `/mix/creator/${recipeId}`;
            }
        });

        $("#addStep").on({click: () => addStep()});

        $("#addImage").on({
            click: function () {
                showConfirm(askChangePage, false, () => window.location.href = `/images/add/${recipeId}`);
            }
        });

        $(".deleteImg").on({
            click: function () {
                showConfirm(askChangePage, false, () => {
                    checkPassword(null, () => {
                        const image = $(this).data("image");

                        axios.get("/images/delete/" + image)
                            .then(r => {
                                const responseData = r.data;

                                if (responseData.error) showMessage(errorMsg, responseData.error);
                                else window.location.reload();
                            })
                            .catch(e => {
                                console.log(e);
                                showMessage(errorMsg, generalErrorText);
                            });
                    })
                });
            }
        });

        const recipeText = "[[${recipeJson}]]";
        const recipeJSON = JSON.parse(recipeText.replace(/&quot;/g, '"').replace(/&#39;/g, '\'').replace(/\r\n/g, ""));

        // Ajoute les étapes déjà présentes dans la recette
        recipeJSON.recipeSteps.forEach(s => addStep(s.message));
    });

    function addStep(value) {
        const input = $("<input />")
            .attr({
                type: "text",
                id: `step_${stepNbr}`,
                name: "step",
                autocomplete: "off",
                value: value
            });

        const number = $("<label></label>")
            .attr({
                for: input.attr("id")
            })
            .text(`${stepNbr + 1}. `);

        const deleteButton = $("<button></button>")
            .attr({
                type: "button"
            })
            .text(removeText)
            .on({
                click: () => deleteStep(input.attr("id"))
            });

        const div = $("<div></div>")
            .append(number)
            .append(input)
            .append(deleteButton);

        $("#steps").append(div);

        stepNbr++;
    }

    function deleteStep(stepId) {
        // Supprime la rangée de l'étape
        $(`#${stepId}`).parent().remove();
    }

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