// Compteurs des produits
let materialNbr = 0;
// Liste des produits
let materials;

let removeText;
let materialSelectorHtml;
let recipeID;

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

    const mixIDInput = $("#mixId");
    const mixID = mixIDInput.val() ? mixIDInput.val() : -1;

    axios.get(`/mix/selector/${recipeID}/${mixID}`)
        .then(r => {
            materialSelectorHtml = r.data;
            init();
        })
        .catch(e => {
            showMessage(errorMsg, generalErrorText);
            console.log(e);
        });

    onRowPositionChanged();
});

$(document).on("click", function () {
    hideMaterialList();
});

$(document).on("click", ".materialSelector", function (event) {
    event.stopPropagation();
    showMaterialList($(this)[0]);
});

$(document).on("click", ".removeMaterial", function () {
    const id = $(this).data("removerow");
    if ($(".materialListRow").length > 1) $(`#${id}`).remove();
});

$(document).on("click", ".upRow", function () {
    const row = $(this).parents(".materialListRow");
    row.insertBefore(row.prev());

    onRowPositionChanged();
});

$(document).on("click", ".downRow", function () {
    const row = $(this).parents(".materialListRow");
    row.insertAfter(row.next());

    onRowPositionChanged()
});

$(".mixMaterialListTitle button").on({
    click: function () {
        addMaterial(null, null);
    }
});

function onRowPositionChanged() {
    $(".materialListRow").each(function () {
        const node = $(this);
        const upRow = node.find(".upRow");
        const downRow = node.find(".downRow");

        let upRowHidden = false;
        let downRowHidden = false;

        if (node.is(":first-child")) {
            upRowHidden = true;
        } else if (node.is(":last-child")) {
            downRowHidden = true;
        }

        if (upRowHidden) upRow.css({opacity: 0});
        else upRow.css({opacity: 1});

        if (downRowHidden) downRow.css({opacity: 0});
        else downRow.css({opacity: 1});
    });
}

function addMaterial(materialCode, quantity) {
    const row = addRow(materialNbr);
    const positionColumn = $(addColumn("positionButtons", row));
    const materialColumn = $(addColumn("material", row));
    const quantityColumn = $(addColumn("quantity", row));
    const unitsColumn = $(addColumn("units", row));
    const removeButtonColumn = $(addColumn("removeButton", row));

    addPositionButtons(positionColumn);
    addQuantityInput(quantity, quantityColumn);
    addUnits(unitsColumn);
    addRemoveButton(materialNbr, removeButtonColumn);

    materialColumn.html(materialSelectorHtml);
    const materialSelector = materialColumn.find("input");
    if (materialCode) {
        const material = materialColumn.find(`.materialList p[data-materialcode="${materialCode}"]`);

        if (material) {
            materialSelector.val(material.data("materialcode"));
            materialSelector.data({
                usepercentages: material.data("usepercentages")
            });
        }
    }

    $(".mixMaterialList").append(row);

    checkUnits(materialSelector, row);
    onRowPositionChanged();
    materialNbr++;
}

function addRow(index) {
    return $("<div></div>")
        .attr({
            class: "materialListRow",
            id: `material_${index}`
        });
}

function addColumn(type, parent) {
    const column = $("<div></div>")
        .attr({class: type});

    $(parent).append(column);
    return column;
}

function addUnits(parent) {
    const units = $("<p></p>")
        .attr({class: "quantityUnits"})
        .text("mL");

    $(parent).append(units);
    return units;
}

function addRemoveButton(index, parent) {
    const button = $("<button></button>")
        .attr({
            type: "button",
            class: "removeMaterial"
        })
        .data({removerow: `material_${index}`})
        .text(removeText);

    $(parent).append(button);
    return button;
}

function addQuantityInput(quantity, parent) {
    if (quantity === undefined || quantity === null) quantity = 1;

    const input = $("<input/>")
        .attr({
            type: "number",
            name: "quantities",
            value: quantity,
            step: 0.001,
            min: 0.001,
            required: true,
            autocomplete: "off"
        });

    $(parent).append(input);
    return input;
}

function addPositionButtons(parent) {
    $(parent).append($("<button></button>")
        .attr({
            class: "upRow",
            type: "button"
        })
        .text("↑"));

    $(parent).append($("<button></button>")
        .attr({
            class: "downRow",
            type: "button"
        })
        .text("↓"));
}

function showMaterialList(input) {
    hideMaterialList();
    $(input).parent().find(".materialSelector .materialList").addClass("show");
}

function hideMaterialList() {
    const list = $(".materialSelector .materialList.show");
    if (list) list.removeClass("show");
}

function selectMaterial(material) {
    const materialName = $(material).data("materialcode");
    const input = $(material).parents(".materialSelector").find("input");

    input.val(materialName);

    checkUnits(material, input.parents(".materialListRow"));
}

function searchMaterial(input) {
    input = $(input);
    const filter = input.val();
    const materials = input.parent().find(".materialList p");

    materials.each(function () {
        const node = $(this);
        if (searchIn(filter, node.text()) || searchIn(filter, node.data("materialtype"))) node.show();
        else node.hide();
    });

    const found = input.parent().find(`.materialList p[data-materialcode="${filter}"]`);
    if (found) {
        input.data({
            usepercentages: found.data("usepercentages")
        });
    }

    checkUnits(input, input.parents(".materialListRow"));
}

function checkUnits(materialSelector) {
    const quantityUnits = $(materialSelector).parents(".materialListRow").find(".quantityUnits");
    if ($(materialSelector).data("usepercentages")) quantityUnits.text("%");
    else quantityUnits.text("mL");
}
