window.WooPoPToFattureInCloud = window.WooPoPToFattureInCloud || {};

;(
    function (_, $, wfcScripts) {

        function getProducts() {
            let action = document.querySelector('.products .products-list-action #api_get_products');
            if (action) {
                action.addEventListener('click', function (evt) {
                    let response = [
                        function () {
                            return new Promise(function (resolve, reject) {
                                WooPoPToFattureInCloud.api.ajaxRequest({
                                        'action': 'updateProductsList',
                                        'ajaxAction': 'fcUpdateProductsList',
                                        'type': 'get',
                                        'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                    }, true, resolve
                                )
                                console.log("Get Products request... complete");
                            })
                        },
                        function (response) {
                            return new Promise(function (resolve, reject) {
                                console.log("Get Products response... complete");
                                console.log(response);
                                if (response.body) {
                                    let jsonObject = JSON.parse(response.body);
                                    delete response.body
                                    let message = '';
                                    message += "<h4>" + response.message + "</h4>";
                                    message += "<ul class='state_list fic_product_list'>";
                                    jsonObject.forEach(function (data) {
                                        console.log(data);
                                        message += "<li><code class='light'>" + data.name + "<br>stock:" + data.current_stock + "<br>category: " + data.category + "</code></li>"
                                    });
                                    message += "</ul>";

                                    WooPoPToFattureInCloud.api.modalContent.innerHTML = message;
                                    WooPoPToFattureInCloud.api.closePoUP();
                                } else {
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'update');
                                }
                            })
                        }
                    ];

                    WooPoPToFattureInCloud.api.reduce(response);
                })
            }
        }

        getProducts();

    }(_, window.jQuery, window.wfcScripts)
);