/*
 * Récupération d'un produit par scan et affichage des informations du produits.
 * Les informations actuellements récupérées sont :
 *  - Stock théorique
 *
 * Les informations actuellement modifiables sont :
 *  - Stock théorique
 */

var products = [],
    products_table = null;

function init(products) {
    // create table, show panel
    products_table = $('#products_table').DataTable({
        data: products,
        columns: [
            {data: "id", title: "id", visible: false},
            {
                data: "name",
                title: "Produit",
                width: "50%",
                render: function (data, type, full, meta) {
                    // Add tooltip with barcode over product name
                    let display_barcode = "Aucun";

                    if ('barcode' in full) {
                        display_barcode = full.barcode;
                    }

                    return '<div class="tooltip">' + data
                        + ' <span class="tooltiptext tt_twolines">Code barre : '
                        + display_barcode + '</span> </div>';
                }
            },
            {
                data: "uom_id.1",
                title: "Unité de vente",
                className: "dt-body-center",
                orderable: false
            },
            {
                data: "qty_available",
                title: "Stock théorique",
                className: "dt-body-center",
                render: function (data, type, full, meta) {
                    return '<input type="number" class="stock_edit_input" value="' + data + '">'
                        + ' <button type="button" class="stock_edit_button btn--primary"><i class="fas fa-lg fa-check"></i></button>';
                }
            }
        ],
        order: [
            [
                0,
                "asc"
            ]
        ],
        pageLength: 10,
        deferRender: true,
        processing: true,
        searching: true,
        language: {url: '/static/js/datatables/french.json'},
        dom: 'lrtip', // Remove the search input from that table
    });
    /* In order to remove the accents in the input, we could attach a keyup event to the default
     * search field generated by datatables, but then two search events would be triggered on keyup :
     * the default datatable event, and ours.
     * To fix this problem we create our own input search so that only our event fires.
     */
    $(document).on('keyup', '#custom_products_table_filter input[type="search"]', function() {
        products_table
            .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
            .draw();
    });

    // Listener on 'Update product stock' button
    $('#products_table tbody').on('click', 'button.stock_edit_button', function () {
        var row = products_table.row($(this).parents('tr'));
        var row_data = row.data();

        // Data validation
        qty = $(this).parents('tr')
            .find('input')
            .val();
        if (row_data.uom_id[0] == 1) {
            if (qty != 0 && qty / parseInt(qty) != 1) {
                $.notify(
                    "Ce produit est vendu à l'unité : la valeur doit être un nombre entier !",
                    {
                        globalPosition: "top left",
                        className: "error"
                    }
                );

                return 0;
            }

            qty = parseInt(qty); // product by unit
        } else {
            qty = parseFloat(qty);
        }

        // Value is valid
        if (!isNaN(qty)) {
            row_data.qty = $(this).parents('tr')
                .find('input')
                .val();

            if (row_data.qty != row_data.qty_available) {
                update_product_stock(row_data);
            } else {
                $.notify(
                    "Valeur inchangée.",
                    {
                        globalPosition: "top left",
                        className: "info"
                    }
                );
                $("#products_table_filter input").focus()
            }
        } else {
            $.notify(
                "Valeur invalide.",
                {
                    globalPosition: "top left",
                    className: "error"
                }
            );
            $("#products_table_filter input").focus()
        }
    });
}

function update_product_stock(p_data) {
    openModal();
    $.ajax({
        type: "POST",
        url: "/products/update_product_stock",
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(p_data),
        success: function(data) {
            p_data.qty_available = p_data.qty;
            delete p_data.qty;

            closeModal();
            $("#products_table_filter input").focus()
            $.notify(
                "Stock mis à jour !",
                {
                    globalPosition:"top left",
                    className: "success"
                }
            );
        },
        error: function(data) {
            // server error
            err = {msg: "erreur serveur lors de la maj du stock", ctx: 'update_product_stock'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }

            console.error(err);
            report_JS_error(err, 'produits');

            closeModal();
            reset_focus();
        }
    });
}

// Fetch a product when barcode is read
function fetch_products() {
    openModal();
    $.ajax({
        url: "/products/get_all_active_products",
        success: function(data) {
            init(data.products)
            closeModal();
            // Attendre que le DOM soit complètement prêt avant de donner le focus
            setTimeout(function() {
                // Vérifier si l'input de la recherche est disponible
                var searchInput = $("#products_table_filter input");
                if (searchInput.length) {
                    searchInput.focus();  // Mettre le focus sur le champ de recherche
                }
            }, 100);  // Attendre un court instant pour s'assurer que DataTables est complètement initialisé
        },
        error: function(data) {
            closeModal();
            if (data.status == 404) {
                // Product not found (shouldn't rise)
                $.notify(
                    "Aucun produit trouvé !",
                    {
                        globalPosition:"top left",
                        className: "error"
                    }
                );
                reset_focus();
            } else {
                // server error
                err = {msg: "erreur serveur lors de la récupération du produit", ctx: 'fetch_products'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
                console.error(err);
                report_JS_error(err, 'produits');
                reset_focus();
            }
        }
    });
}

$(document).ready(function() {
    $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
    fetch_products('');
});
