<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="'Couleur ' + ${recipe.recipeCode}"></title>

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

    <style>
        td, th {
            width: 200px;
        }

        table {
            margin: auto;
            text-align: left;
        }

        section {
            text-align: center;
        }

        p {
            display: inline;
        }

        .mixes {
            margin: 0;
            border: 1px solid black;
            border-collapse: collapse;
        }

        .mixes td, .mixes th {
            border: 1px solid black;
            min-width: 100px;
        }

        .recipeLocation {
            width: 30px;
        }

        .notEnough td {
            background-color: #ffb3b3;
        }
    </style>
</head>
<body>

<section>
    <p class="error" th:text="${error}"></p>
    <p class="success" th:text="${success}"></p>

    <h1 th:text="'Couleur ' + ${recipe.recipeCode}"></h1>
    <button id="modifyRecipe" type="button">Modifier</button>
    <button id="useSubmit" type="button">Utiliser</button>
    <br/>
    <select id="unitsSelect"
            onchange="changeUnits(this, '.inventoryQuantity', '.inventoryQuantityUnits'); changeCustomizersUnits(this)">
        <option selected value="mL">Millilitres</option>
        <option value="L">Litres</option>
        <option value="gal">Gallons</option>
    </select>

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

    <table class="mainTable">
        <tr>
            <td>
                <table>
                    <tr>
                        <td><b>Couleur: </b></td>
                        <td th:text="${recipe.recipeCode}"></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Bannière: </b></td>
                        <td th:text="${recipe.company.companyName}"></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Description: </b></td>
                        <td th:text="${recipe.recipeDescription}"></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Échantillon: </b></td>
                        <td th:text="${recipe.sample}"></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Date d'approbation: </b></td>
                        <th:block th:if="${recipe.approbationDate != ''}">
                            <td th:text="${recipe.approbationDate}"></td>
                        </th:block>
                        <th:block th:if="${recipe.approbationDate == ''}">
                            <td>Non approuvée</td>
                        </th:block>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Remarque: </b></td>
                        <td th:text="${recipe.remark}">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <hr/>
                        </td>
                    </tr>
                    <tr>
                        <td><b>Note: </b></td>
                        <td>
                            <textarea cols="30" id="note" name="note" rows="10" th:text="${recipe.note}"></textarea>
                        </td>
                    </tr>
                </table>
            </td>
            <td>
                <table style="border-spacing: 20px;">
                    <th:block th:each="mix : ${mixes}">
                        <tr>
                            <td><b th:text="${mix.mixType.typeName} + ':'"></b><br><br>
                                <label for="location"> Position: </label><input class="recipeLocation" id="location"
                                                                                name="location"
                                                                                th:data-mixID="${mix.mixID}"
                                                                                th:value="${mix.location}"
                                                                                type="text"/></td>
                            <td>
                                <table class="mixes" th:id="'recipe-' + ${mix.mixID}">
                                    <tr>
                                        <th>Produit</th>
                                        <th>Type</th>
                                        <th>Quantité</th>
                                        <!-- Changement des quantités -->
                                        <td></td>
                                        <td>Unités</td>
                                    </tr>
                                    <!-- Produits -->
                                    <th:block th:each="mixQuantity : ${mix.mixQuantities}"
                                              th:with="material = ${mixQuantity.material}">
                                        <tr th:id="'material-' + ${material.materialID}">
                                            <td th:classappend="${material.isMixType()} ? '' : materialCode"
                                                th:data-materialID="${material.materialID}"
                                                th:text="${material.materialCode}"></td>
                                            <td>
                                                <p th:text="${material.materialType.materialTypeName}"></p>
                                            </td>
                                            <td>
                                                <p class="inventoryQuantity"
                                                   th:data-quantityML="${mixQuantity.quantity}"
                                                   th:text="${mixQuantity.quantity}"></p>
                                            </td>
                                            <th:block th:if="${!material.isMixType()}">
                                                <td><input class="quantityCustomizer" min="0" step="0.01"
                                                           th:data-quantityML="${mixQuantity.quantity}"
                                                           th:data-materialID="${material.materialID}"
                                                           th:data-mixID="${mix.mixID}"
                                                           th:value="${mixQuantity.quantity}" type="number"/></td>
                                            </th:block>
                                            <td>
                                                <p class="inventoryQuantityUnits">mL</p>
                                            </td>
                                        </tr>
                                    </th:block>
                                </table>
                            </td>
                            <td>
                                <button class="useMixSubmit" type="button">Utiliser</button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <hr/>
                            </td>
                        </tr>
                    </th:block>
                    <!-- Étapes -->
                    <th:block th:if="${!recipe.recipeSteps.isEmpty()}">
                        <tr>
                            <td>
                                <b>Étapes: </b>
                            </td>
                            <td>
                                <ol>
                                    <th:block th:each="step : ${recipe.recipeSteps}">
                                        <li th:text="${step.stepMessage}"></li>
                                    </th:block>
                                </ol>
                            </td>
                        </tr>
                    </th:block>
                </table>
            </td>
        </tr>
        <tr class="mainTableEndButtons">
            <td>
                <button id="formSubmit" type="button">Sauvegarder</button>
            </td>
        </tr>
        <!-- Images -->
        <th:block th:each="image : ${images}">
            <tr>
                <td colspan="2" style="text-align: center;">
                    <img alt="Image supprimée ou corrompue" th:src="'/images/' + ${image}" width="400px"/>
                </td>
            </tr>
        </th:block>
    </table>
</section>

<script src="/js/main.js"></script>
<script>
    (() => {
        document.querySelector("#modifyRecipe").addEventListener("click", () => {
            const recipeID = document.querySelector("#recipeID").value;
            document.location.href = `/recipe/editor/${recipeID}`;
        });

        document.querySelectorAll(".quantityCustomizer").forEach((e) => {
            e.addEventListener("change", () => {
                const value = e.valueAsNumber;
                const oldValue = e.defaultValue;
                const currentUnit = document.querySelector("#unitsSelect").value;

                // Modifie les quantités de tous les produits
                // Les 3 parentElement récupèrent la table dans laquelle le produit se trouve
                // TODO simplifier ?
                e.parentElement.parentElement.parentElement.querySelectorAll(".quantityCustomizer").forEach((elem) => {
                    const defaultValue = elem.defaultValue;
                    const newValue = (defaultValue * value) / oldValue;

                    elem.value = round(newValue);

                    // Recalcule la quantité en millilitres de chaque produit
                    elem.dataset.quantityml = convertUnitToMl(currentUnit, newValue);
                });
            });
        });

        // Fait que toutes les tables de mélange soit de la même largeur
        // TODO Voir si nécessaire, semble être fait par défault
        // const mixes = document.querySelectorAll(".mixes");
        // let maxWidth = 0;
        // mixes.forEach((e) => {
        //     const width = e.style.width;
        //
        //     if (width > maxWidth) {
        //         maxWidth = width;
        //     }
        // });
        // mixes.forEach((e) => {
        //     e.style.width = maxWidth;
        // });

        document.querySelector("#formSubmit").addEventListener("click", () => {
            let formData = {};

            // Identifiant de la recette
            formData['recipeID'] = document.querySelector("#recipeID").value;

            // Position
            formData['locations'] = {};
            document.querySelectorAll(".recipeLocation").forEach((e) => {
                formData['locations'][e.dataset.mixid] = e.value;
            });

            formData['note'] = document.querySelector("#note").value;

            sendPost(formData, "/recipe/explore");
        });

        document.querySelector("#useSubmit").addEventListener("click", () => {
            let formData = {};

            document.querySelectorAll(".quantityCustomizer").forEach(e => {
                const materialID = e.dataset.materialid;
                const mixID = e.dataset.mixid;

                if (formData[mixID] === undefined) {
                    formData[mixID] = {};
                }

                formData[mixID][materialID] = e.dataset.quantityml;
            });

            clearNotEnoughClasses();

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

        document.querySelectorAll(".useMixSubmit").forEach(e => {
            e.addEventListener("click", () => {
                let formData = {};

                e.parentElement.parentElement.querySelectorAll(".quantityCustomizer").forEach(elem => {
                    const materialID = elem.getAttribute("data-materialID");
                    const mixID = elem.getAttribute("data-mixID");

                    if (formData[mixID] === undefined) {
                        formData[mixID] = {};
                    }

                    formData[mixID][materialID] = elem.dataset.quantityml;
                });

                clearNotEnoughClasses();

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

    function changeCustomizersUnits(unitSelect) {
        const unit = unitSelect.value;

        document.querySelectorAll(".quantityCustomizer").forEach(e => {
            const originalValue = e.dataset.quantityml;

            e.value = convertMlToUnit(unit, originalValue);
        });
    }

    function clearNotEnoughClasses() {
        document.querySelectorAll(".notEnough").forEach(elem => {
            elem.classList.remove("notEnough");
        });
    }

    function displayNotEnoughReason(reason) {
        const splitReason = reason.split("-");
        const mixID = splitReason[0];
        const materialID = splitReason[1];

        document.querySelector(`#recipe-${mixID}`).querySelector(`#material-${materialID}`).classList.add("notEnough");
    }

    function sendPost(data, url, errorCallback) {
        const successP = document.querySelector(".success");
        const errorP = document.querySelector(".error");

        successP.innerHTML = "";
        errorP.innerHTML = "";

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

                if (data['success'] !== undefined) {
                    successP.innerHTML = data['success'];
                } else if (data['error'] !== undefined) {
                    errorP.innerHTML = data['error'];

                    if (typeof errorCallback !== 'undefined') {
                        errorCallback(data['reason']);
                    }
                }
            })
            .catch(e => {
                console.log(e);
                errorP.innerHTML = "Une erreur est survenue lors de l'envoie des informations vers le serveur.";
            });
    }
</script>
</body>
</html>
