const body = $("body");
const errorMsg = $("#errorBox");
const warningMsg = $("#warningBox");
const successMsg = $("#successBox");
const confirmMsg = $("#confirmBox");
const promptMsg = $("#promptBox");

const messageBoxesAnimationTime = 200;
const messageBoxesFunctionsDelay = 300;

$(() => {
    $('.materialCode').each(function () {
        const row = $(this);
        const materialID = row.data("materialid");

        // SIMDUT
        checkSimdutAvailability(materialID, null, () => {
            row.parent().addClass("nosimdut");
            row.parent().title = simdutNotFoundText;
        });
    });
    $(".messageBox").each(function () {
        checkMessageBoxesDisplay($(this)[0])
    });
    $(".toSave").on({
        keyup: function () {
            showMessage(warningMsg, changesNotSavedText, false);
        }
    });
    $(".returnButton").on({click: () => window.location.href = referer});
    $(".materialCode").on({
        click: function () {
            window.open(`/simdut/${$(this).data("materialid")}`, "_blank");
        }
    });
    $("img").on({
        click: function () {
            if ($(this).attr("id") === "logo") return;
            window.open($(this).attr("src"), "_blank");
        }
    });
    $('input[type="text"], input[type="number"], input[type="date"], textarea').each(function () {
        $(this).addClass("rawInput");
    });
    $(".rawInput:not(.noPlaceholder)").each(function () {
        $(this).attr({placeholder: "N/A"});
    });

    // Formulaires protégés
    $(".requireAuth").on({
        submit: function () {
            return checkPassword(this);
        }
    });
    const removerForm = $(".requireAuth-remover");
    removerForm.find(".remover").on({
        click: function () {
            removerForm.attr({
                action: removerForm.attr("action") + $(this).data("entityid")
            });

            checkPassword(removerForm);
        }
    });

    // Favicon
    $("head").append($("<link/>").attr({
        rel: "icon",
        href: "/favicon.png"
    }));

    // Imprimante
    let src = `${baseUrl}/icons/printerError.svg`;
    let title = printErrorTitle;
    const intervalId = setInterval(() => {
        if ($(".bpac-extension-installed").length) {
            src = `${baseUrl}/icons/printer.svg`;
            title = printOkTitle;

            clearInterval(intervalId);
        }

        $("#printStatusIcon").attr({
            src: src,
            title: title
        });
    }, 500);
});

function checkSimdutAvailability(materialId, successCallback, notFoundCallback) {
    axios.post(`/simdut/${materialId}`)
        .then(d => {
            if (successCallback) successCallback();
        })
        .catch(function (err) {
            if (err.response.status === 404 && notFoundCallback) notFoundCallback();
        });
}

function confirmDatabaseExport() {
    showConfirm(exportAllWarningText, false, () => {
        window.location.href = "/recipe/xls";
    });
}

function checkPassword(form, callback = () => {
}) {
    let shouldContinue = false;

    promptMsg.find("input").attr({type: "password"});
    showConfirm(askPasswordText, true, async pwd => {
        let data = {};
        data.password = pwd;

        await axios.post("/password/valid", data)
            .then(r => {
                if (r.data === true) {
                    if (form != null) form.submit();
                    callback();
                    shouldContinue = true;
                } else {
                    showMessage(errorMsg, invalidPasswordText);
                }
            })
            .catch(e => {
                showMessage(errorMsg, generalErrorText);
                console.log(e);
            });

        promptMsg.find("input").attr({type: "text"});
    }, () => promptMsg.find("input").attr({type: "text"}));

    return shouldContinue;
}

const messageBoxesY = -20;
const headerY = 70;

function checkMessageBoxesDisplay(element) {
    const node = $(element);

    if (!node.find("p").text()) hideMessage(element);
    else showMessage(element);
}

function isMessageVisible(type) {
    return $(type).is(":visible");
}

function showMessage(type, value, autoHide = true, hideTimeout = 2000) {
    const node = $(type);
    const message = node.find("p");

    // Cache les autres boîtes de message sauf si une boîte de confirmation est active
    if (!$("#filter").is(":visible")) {
        $(`.messageBox:not(#${$(type).attr("id")}`).each(function () {
            hideMessage(this);
        });
    } else {
        return;
    }

    if (!isMessageVisible(type)) {
        message.text(value);
        node.show();
        node.animate({top: `${headerY}px`}, messageBoxesAnimationTime);

        if (autoHide) {
            setTimeout(() => {
                hideMessage(node);
            }, hideTimeout);
        }
    } else {
        if (message.text() !== value) hideMessage(type, () => showMessage(type, value, autoHide, hideTimeout));
    }
}

function hideMessage(type, callback = () => {
}) {
    const node = $(type);

    if (isMessageVisible(type)) {
        node.animate({top: `${messageBoxesY}px`}, messageBoxesAnimationTime, "swing", () => {
            node.hide();
            callback();
        });
    }
}

function showConfirm(value, prompt = false, continueCallback = () => {
}, cancelCallback = () => {
}) {
    const filter = $("#filter");
    const node = prompt ? $(promptMsg) : $(confirmMsg);
    const nodeInput = prompt ? node.find("#confirmInput") : undefined;

    if (prompt) nodeInput.val("");

    showMessage(node, value, false);
    filter.show();
    filter.animate({opacity: 0.5}, messageBoxesAnimationTime);

    setTimeout(() => {
        $("body").on({
            keyup: function (e) {
                if (e.which === 13) { // Enter
                    confirmContinue(node, continueCallback);
                } else if (e.which === 27) {
                    confirmCancel(node, cancelCallback)
                }
            }
        });
        node.find(".confirmContinue").one({
            click: () => {
                confirmContinue(node, continueCallback)
            }
        });
        node.find(".confirmCancel").one({
            click: () => {
                confirmCancel(node, cancelCallback)
            }
        });

        if (nodeInput) nodeInput.focus();
    }, 100);
}

function confirmContinue(node, continueCallback) {
    hideConfirm(node);

    setTimeout(function () {
        if (!prompt) continueCallback();
        else continueCallback(node.find("#confirmInput").val());
    }, messageBoxesFunctionsDelay);
}

function confirmCancel(node, cancelCallback) {
    hideConfirm(node);

    setTimeout(function () {
        cancelCallback();
    }, messageBoxesFunctionsDelay);
}

function hideConfirm(node) {
    hideMessage(node);

    const filter = $("#filter");
    filter.animate({opacity: 0}, messageBoxesAnimationTime + 100, "swing", () => {
        filter.hide();
        // Retire les callbacks des anciennes confirmations
        $(confirmMsg).find(".confirmContinue").unbind();
        $(confirmMsg).find(".confirmCancel").unbind();
    });
}

const lTomL = 1000;
const galTomL = 3785.41;

let currentUnit = "mL";

// Change les unités selon la sélection de l'utilisateur
function changeUnits(unitSelect, quantitiesSelector, unitsDisplay) {
    currentUnit = unitSelect.value;

    $(unitsDisplay).each(function () {
        $(this).text(currentUnit);

        const quantityElem = $(this).parents(".materialRow").find(quantitiesSelector);
        if (quantityElem) {
            const originalQuantity = parseInt(quantityElem.data("quantityml"));
            quantityElem.text(convertMlToUnit(originalQuantity));
        }
    });
}

// Convertit une quantité en millilitres vers une autre unité de volume
function convertMlToUnit(quantity) {
    let newQuantity = currentUnit === "L" ? quantity / lTomL : currentUnit === "gal" ? quantity / galTomL : quantity;
    return round(newQuantity);
}

// Convertit une quantité d'une autre unité vers des millilitres
function convertUnitToMl(quantity) {
    let newQuantity = currentUnit === "L" ? quantity * lTomL : currentUnit === "gal" ? quantity * galTomL : quantity;
    return round(newQuantity);
}

function round(x) {
    return Math.round(x * 1000) / 1000;
}

function percentageOf(percentage, number) {
    return (percentage / 100) * number;
}

function searchIn(searchString, str) {
    return str.toUpperCase().indexOf(searchString.toUpperCase()) > -1;
}

function formatMessage(message) {
    return message.replace(/&#39;/g, "'");
}
