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

;(
    function (_, $, wfcScripts) {

        "use strict";

        /**
         * POPToFattureInCloud.api
         *
         * @type {{copyClipBoard: POPToFattureInCloud.api.copyClipBoard, setPaymentAccount: POPToFattureInCloud.api.setPaymentAccount, oAuthExchange: POPToFattureInCloud.api.oAuthExchange, Connected: null, localized: *, deleteEndpoint: string, oAuthEndpoint: string, construct: POPToFattureInCloud.api.construct, oAuth: POPToFattureInCloud.api.oAuth, removeParam: (function(*, *): string), sendEndpoint: string, closePoUP: POPToFattureInCloud.api.closePoUP, verifyEInvoice: POPToFattureInCloud.api.verifyEInvoice, modalContent: Element, settingsPaymentAccountEndpoint: string, refreshOAuthTokenEndpoint: string, settingsMappingGatewayEndpoint: string, oAuthDevice: POPToFattureInCloud.api.oAuthDevice, ajaxRequest: POPToFattureInCloud.api.ajaxRequest, createInvoiceEndpoint: string, loginActionWrap: Element, reduce: POPToFattureInCloud.api.reduce, init: POPToFattureInCloud.api.init, sendEInvoice: POPToFattureInCloud.api.sendEInvoice, deleteInvoice: POPToFattureInCloud.api.deleteInvoice, refreshOAuthToken: POPToFattureInCloud.api.refreshOAuthToken, settingsCompanyEndpoint: string, settingsMappingPaymentEndpoint: string, syncEInvoice: POPToFattureInCloud.api.syncEInvoice, mappingPayGatewayAndPayMethod: POPToFattureInCloud.api.mappingPayGatewayAndPayMethod, mappingPayMethodAndPayAccount: POPToFattureInCloud.api.mappingPayMethodAndPayAccount, getParameterByName: ((function(*, string=): (string|null))|*), createInvoice: POPToFattureInCloud.api.createInvoice, modalContainer: Element, syncEInvoiceEndpoint: string, verifyEndpoint: string, responseMessage: POPToFattureInCloud.api.responseMessage, setCompanyId: POPToFattureInCloud.api.setCompanyId, oAuthExchangeEndpoint: string}}
         */
        WooPoPToFattureInCloud.api = {

            /**
             * localized
             */
            localized: wfcScripts,

            /**
             * Endpoint
             */
            oAuthEndpoint: 'OAuthFlow',
            oAuthExchangeEndpoint: 'oAuthExchange',
            refreshOAuthTokenEndpoint: 'refreshOAuthToken',
            settingsCompanyEndpoint: 'settingsCompany',
            settingsPaymentAccountEndpoint: 'settingsPaymentAccount',
            settingsMappingPaymentEndpoint: 'settingsMappingPayment',
            settingsMappingGatewayEndpoint: 'settingsMappingGateway',
            createInvoiceEndpoint: 'createInvoice',
            verifyEndpoint: 'verifyEInvoice',
            sendEndpoint: 'sendInvoice',
            syncEInvoiceEndpoint: 'syncEInvoice',
            deleteEndpoint: 'deleteInvoice',

            /**
             * Modal Container
             */
            modalContainer: document.querySelector('.wfc_ajax_modal'),

            /**
             * Modal Content
             */
            modalContent: document.querySelector('.wfc_ajax_modal .modal_content .modal_card'),

            /**
             * Login Wrap
             */
            loginActionWrap: document.querySelector('.wfc_login .wfc_login_wrap'),

            /**
             * Connected
             */
            Connected: null,

            notifyDialog: function (message, options) {
                options = options || {};

                if (!window.Swal || 'function' !== typeof window.Swal.fire) {
                    window.alert(message);
                    return Promise.resolve();
                }

                return window.Swal.fire({
                    title: options.title || '',
                    text: message,
                    icon: options.icon || 'info',
                    timer: options.timer || 2200,
                    timerProgressBar: true,
                    showConfirmButton: false,
                }).then(function () {
                    return true;
                });
            },

            /**
             * copyClipBoard
             */
            copyClipBoard: function () {
                let copyTrigger = document.getElementById('copy_trigger');
                let copyText = document.getElementById('user_code');
                if (copyText && copyTrigger) {
                    copyTrigger.addEventListener('click', () => {
                        console.log(copyText);
                        copyText.select();
                        copyText.setSelectionRange(0, 99999); /* For mobile devices */
                        navigator.clipboard.writeText(copyText.value);
                        copyText.style.backgroundColor = "#cce6cc";
                    })
                }
            },

            /**
             * getParameterByName
             * @param name
             * @param url
             * @returns {string|null}
             */
            getParameterByName: function (name, url = window.location.href) {
                name = name.replace(/[\[\]]/g, '\\$&');
                let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                    results = regex.exec(url);
                if (!results) {
                    return null;
                }
                if (!results[2]) {
                    return '';
                }
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            },

            /**
             * removeParam
             * @param key
             * @param sourceURL
             * @returns {string}
             */
            removeParam: function (key, sourceURL) {
                let rtn = sourceURL.split("?")[0],
                    param,
                    params_arr = [],
                    queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
                if (queryString !== "") {
                    params_arr = queryString.split("&");
                    for (let i = params_arr.length - 1; i >= 0; i -= 1) {
                        param = params_arr[i].split("=")[0];
                        if (param === key) {
                            params_arr.splice(i, 1);
                        }
                    }
                    if (params_arr.length) {
                        rtn = rtn + "?" + params_arr.join("&");
                    }
                }
                return rtn;
            },

            /**
             * Init
             */
            init: function () {
                this.loginAction = document.querySelector('.wfc_login .api-action');
                this.actions = document.querySelectorAll('.actions .api-action');
                this.Connected = WooPoPToFattureInCloud.api.localized.fcConnected;

                // Logged user
                if (this.loginAction && this.Connected) {
                    this.loginAction.setAttribute('disabled', 'disabled');
                }

                if (this.actions && !this.Connected) {
                    this.actions.forEach(function (action) {
                        action.setAttribute('disabled', 'disabled');
                    })
                }

                this.oAuth();
                this.oAuthDevice();
                this.oAuthExchange();
                this.refreshOAuthToken();
                this.setCompanyId();
                this.setPaymentAccount();
                this.mappingPayMethodAndPayAccount();
                this.mappingPayGatewayAndPayMethod();
                this.createInvoice();
                this.verifyEInvoice();
                this.syncEInvoice();
                this.sendEInvoice();
                this.deleteInvoice();
            },

            /**
             * Close
             */
            closePoUP: function (type) {
                let closeBtn = document.querySelector('.wfc_ajax_modal.success .modal_content .close');
                if (closeBtn) {
                    closeBtn.addEventListener('click', function () {
                        WooPoPToFattureInCloud.api.modalContainer.classList.add('close');
                        WooPoPToFattureInCloud.api.modalContainer.classList.remove('open');
                        WooPoPToFattureInCloud.api.modalContainer.classList.remove('success');
                        WooPoPToFattureInCloud.api.modalContent.classList.add('close');
                        WooPoPToFattureInCloud.api.modalContent.classList.remove('open');

                        if ('oauth' === type) {
                            let exchange = WooPoPToFattureInCloud.api.getParameterByName('oauth_exchange');
                            if (exchange) {
                                window.location.href = WooPoPToFattureInCloud.api.removeParam(
                                    "oauth_exchange",
                                    window.location.href
                                );
                            }
                        }

                        setTimeout(function () {
                            window.location.reload(true);
                        }, 500)
                    })
                }
            },

            /**
             * OAuth Request
             */
            oAuth: function () {
                let action = document.getElementById('api_oauth');
                let fcApiUrl = document.getElementById('wfc_api_url');
                let fcApiUid = document.getElementById('wfc_api_uid');
                let fcApiKey = document.getElementById('wfc_api_key');
                let permissionInv = document.getElementById('wfc_api_scope_invoice');
                let permissionOrd = document.getElementById('wfc_api_scope_order');
                let permissionCre = document.getElementById('wfc_api_scope_credit_note');
                let permissionRec = document.getElementById('wfc_api_scope_receipt');
                let permissionCli = document.getElementById('wfc_api_scope_clients');
                let permissionStock = document.getElementById('wfc_api_scope_stock');

                // Choice doc type
                if (permissionInv && permissionOrd) {
                    permissionInv.addEventListener('change', (evt) => {
                        if (evt.target.checked) {
                            permissionOrd.checked = false;
                        } else {
                            permissionInv.checked = true;
                        }
                    })
                    permissionOrd.addEventListener('change', (evt) => {
                        if (evt.target.checked) {
                            permissionInv.checked = false;
                        } else {
                            permissionOrd.checked = true;
                        }
                    })
                }

                if (action) {
                    action.addEventListener('click', function () {

                        if (fcApiKey) {
                            fcApiKey.setAttribute('type', 'password');
                        }

                        let response = [
                            // Request
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.oAuthEndpoint,
                                            'ajaxAction': 'fcOAuthRequest',
                                            'type': 'OAuth',
                                            'apiUrl': fcApiUrl.value,
                                            'apiUid': fcApiUid ? fcApiUid.value : '',
                                            'apiKey': fcApiKey ? fcApiKey.value : '',
                                            'permissionInv': permissionInv.checked ? 1 : 0,
                                            'permissionOrd': permissionOrd.checked ? 1 : 0,
                                            'permissionCre': permissionCre.checked ? 1 : 0,
                                            'permissionRec': permissionRec.checked ? 1 : 0,
                                            'permissionCli': permissionCli.checked ? 1 : 0,
                                            // Manage Stock addon
                                            'permissionStock': permissionStock && permissionStock.checked ? 1 : 0,
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("OAuth request... complete");
                                })
                            },
                            // Response
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'oauth');
                                    if (!fcApiUid && !fcApiKey) {
                                        if (200 === response.code) {
                                            WooPoPToFattureInCloud.api.oAuthDevice(response.oauth_device, response.interval);
                                        }
                                    }
                                })
                            }
                        ]

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

            /**
             * OAuth Request for Device Code
             */
            oAuthDevice: function (oauth_device, interval) {
                let modalCard = document.querySelector('.wfc_ajax_modal .modal_content .modal_card');
                if (modalCard && oauth_device && interval) {
                    setTimeout(() => {
                        let loaderUrl = WooPoPToFattureInCloud.api.localized.plugin_url + "assets/images/loader.png";
                        modalCard.insertAdjacentHTML('beforeend',
                            "<p class='wait'><img alt='loader' src=" + loaderUrl + ">" + WooPoPToFattureInCloud.api.localized.wait + "</p>"
                        );
                    }, 1500);
                }
                let time = 1;
                let intervalVar = setInterval(function () {
                    if (time <= 20) {
                        if (!oauth_device) {
                            return false;
                        }

                        let response = [
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.oAuthExchangeEndpoint,
                                            'ajaxAction': 'fcOAuthDeviceRequest',
                                            'type': 'OAuthDevice',
                                            'device_code': oauth_device,
                                            'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("OAuth Device Exchange request number (" + time + "), wait...");
                                })
                            },
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    if (200 === response.code) {
                                        clearInterval(intervalVar);
                                        console.log("OAuth Device Exchange response... complete");
                                        $(WooPoPToFattureInCloud.api.modalContent).empty();
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'oauth');
                                        time = 30;
                                        return true;
                                    }
                                })
                            }
                        ];
                        WooPoPToFattureInCloud.api.reduce(response);

                        time++;
                    } else {
                        clearInterval(intervalVar);
                        WooPoPToFattureInCloud.api.notifyDialog(
                            WooPoPToFattureInCloud.api.localized.wait_timeout,
                            {icon: 'warning', timer: 2600}
                        );
                        return false;
                    }
                }, Number(interval * 1000));
            },

            /**
             * OAuth Request Exchange
             */
            oAuthExchange: function () {
                let oAuthExchange = document.getElementById('api_oauth_token');
                if (oAuthExchange) {
                    oAuthExchange.addEventListener('click', function () {
                        let code = oAuthExchange.getAttribute('data-code');
                        let cid = oAuthExchange.getAttribute('data-cid');
                        let secret = oAuthExchange.getAttribute('data-secret');

                        let response = [
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.oAuthExchangeEndpoint,
                                            'ajaxAction': 'fcOAuthExchangeRequest',
                                            'type': 'OAuth',
                                            'code': code,
                                            'cid': cid,
                                            'secret': secret,
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("OAuth Exchange request... complete");
                                })
                            },
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("OAuth Exchange response... complete");
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'oauth');
                                })
                            }
                        ];

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

            /**
             * refreshOAuthToken
             */
            refreshOAuthToken: function () {
                let refreshOAuthToken = document.getElementById('api_refresh_oauth_token');
                if (refreshOAuthToken) {
                    refreshOAuthToken.addEventListener('click', function () {
                        let refresh = refreshOAuthToken.getAttribute('data-refresh');

                        let response = [
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.refreshOAuthTokenEndpoint,
                                            'ajaxAction': 'fcOAuthExchangeRequest',
                                            'type': 'OAuth',
                                            'refresh': refresh,
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("Refresh OAuth Token request... complete");
                                })
                            },
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("Refresh OAuth Token response... complete");
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'oauth');
                                })
                            }
                        ];

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

            /**
             * setCompanyId
             */
            setCompanyId: function () {
                let selectCompanies = document.getElementById('wfc_company_id');
                if (selectCompanies) {
                    selectCompanies.addEventListener('change', function () {
                        let id = this.value;
                        if ('' === id) {
                            return;
                        }

                        let response = [
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.settingsCompanyEndpoint,
                                            'ajaxAction': 'fcSettingsCompanyRequest',
                                            'type': 'Settings',
                                            'companyID': id,
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("Settings Company ID request... complete");
                                })
                            },
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("Settings Company ID response... complete");
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'settings');
                                })
                            }
                        ];

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

            /**
             * setPaymentAccount
             */
            setPaymentAccount: function () {
                let selectPaymentAccounts = document.getElementById('wfc_payment_methods');
                if (selectPaymentAccounts) {
                    selectPaymentAccounts.addEventListener('change', function () {
                        let id = this.value;
                        if ('' === id) {
                            return;
                        }

                        let response = [
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureInCloud.api.ajaxRequest({
                                            'action': WooPoPToFattureInCloud.api.settingsPaymentAccountEndpoint,
                                            'ajaxAction': 'fcSettingsPaymentAccountRequest',
                                            'type': 'Settings',
                                            'accountID': id,
                                            'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("Settings Payment account request... complete");
                                })
                            },
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("Settings Payment account response... complete");
                                    WooPoPToFattureInCloud.api.responseMessage(response, 'settings');
                                })
                            }
                        ];

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

            /**
             * mappingPayMethodAndPayAccount
             */
            mappingPayMethodAndPayAccount: function () {
                let selectMapping = document.querySelectorAll('select[name="mapping_payment_methods"]');
                if (selectMapping) {
                    selectMapping.forEach((select) => {
                        select.addEventListener('change', function () {
                            let idSelectKey = select.getAttribute('id');
                            let mappingData = this.value;

                            if ('' === mappingData) {
                                return;
                            }

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.settingsMappingPaymentEndpoint,
                                                'ajaxAction': 'fcSettingsMappingPaymentRequest',
                                                'type': 'Settings',
                                                'mappingData': mappingData,
                                                'idSelectKey': idSelectKey,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Settings mapping Payment request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Settings mapping Payment response... complete");
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'settings');
                                    })
                                }
                            ];

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

            /**
             * mappingPayGatewayAndPayAccount
             */
            mappingPayGatewayAndPayMethod: function () {
                let selectMappingGateway = document.querySelectorAll('select[name="mapping_payment_gateways"]');
                if (selectMappingGateway) {
                    selectMappingGateway.forEach((select) => {
                        select.addEventListener('change', function () {
                            let idSelectKey = select.getAttribute('id');
                            let mappingData = this.value;

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.settingsMappingGatewayEndpoint,
                                                'ajaxAction': 'fcSettingsMappingGatewayRequest',
                                                'type': 'Settings',
                                                'mappingData': mappingData,
                                                'idSelectKey': idSelectKey,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Settings mapping Gateway request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Settings mapping Gateway response... complete");
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'settings');
                                    })
                                }
                            ];

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

            /**
             * Create Invoice
             */
            createInvoice: function () {
                let actionsImport = document.querySelectorAll('[id*="api_import_"]');
                if (actionsImport) {
                    actionsImport.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let id = action.getAttribute('data-id');
                            let oType = action.getAttribute('data-otype');
                            let cType = action.getAttribute('data-ctype');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.createInvoiceEndpoint,
                                                'ajaxAction': 'fcImportRequest',
                                                'type': 'import',
                                                'orderID': id,
                                                'choiceType': cType,
                                                'orderType': oType,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Import request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Import response... complete");
                                        console.log(response);
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'import');
                                    })
                                }
                            ];

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

            /**
             * Verify E Invoice
             */
            verifyEInvoice: function () {
                let actionsVerify = document.querySelectorAll('[id*="api_verify_"]');
                if (actionsVerify) {
                    actionsVerify.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let docID = action.getAttribute('data-docid');
                            let id = action.getAttribute('data-id');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.verifyEndpoint,
                                                'ajaxAction': 'fcVerifyRequest',
                                                'type': 'verify',
                                                'docID': docID,
                                                'id': id,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Verify request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Verify response... complete");
                                        console.log(response);
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'verify');
                                    })
                                }
                            ];

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

            /**
             * Sync Invoice
             * - number
             */
            syncEInvoice: function () {
                let actionsSync = document.querySelectorAll('[id*="api_sync_"]');
                if (actionsSync) {
                    actionsSync.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let docID = action.getAttribute('data-docid');
                            let id = action.getAttribute('data-id');
                            let provider = action.getAttribute('data-provider');
                            let icon = action.querySelector('.dashicons');
                            if (icon) {
                                icon.classList.add('spin');
                            }

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.syncEInvoiceEndpoint,
                                                'ajaxAction': 'fcSyncRequest',
                                                'type': 'sync',
                                                'docID': docID,
                                                'id': id,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Sync request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Sync response... complete");
                                        console.log(response);
                                        WooPoPToFattureInCloud.api.modalContainer.remove();
                                        let tdNumber = action.closest('tr').querySelector('td.invoice_number');
                                        if (response.prefix && response.invNumber) {
                                            tdNumber.innerHTML = "<span class='fic_number'>(#" + response.invNumber + response.prefix + ")</span>";
                                        }
                                    })
                                }
                            ];

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

            /**
             * Send E Invoice
             */
            sendEInvoice: function () {
                let actionsSend = document.querySelectorAll('[id*="api_send_"]');
                if (actionsSend) {
                    actionsSend.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let docID = action.getAttribute('data-docid');
                            let id = action.getAttribute('data-id');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.sendEndpoint,
                                                'ajaxAction': 'fcSendRequest',
                                                'type': 'send',
                                                'docID': docID,
                                                'id': id,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Send request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Send response... complete");
                                        console.log(response);
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'send');
                                    })
                                }
                            ];

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

            /**
             * Delete Invoice
             */
            deleteInvoice: function () {
                let actionsDelete = document.querySelectorAll('[id*="api_delete_"]');
                if (actionsDelete) {
                    actionsDelete.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let docID = action.getAttribute('data-docid');
                            let id = action.getAttribute('data-id');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureInCloud.api.ajaxRequest({
                                                'action': WooPoPToFattureInCloud.api.deleteEndpoint,
                                                'ajaxAction': 'fcDeleteRequest',
                                                'type': 'delete',
                                                'docID': docID,
                                                'id': id,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureInCloud.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Delete request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Delete response... complete");
                                        console.log(response);
                                        WooPoPToFattureInCloud.api.responseMessage(response, 'delete');
                                    })
                                }
                            ];

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

            /**
             * Response Message
             *
             * @param response
             * @param type
             */
            responseMessage: function (response, type) {
                let message = '';
                let overquotaPayload = typeof window.wcElInvExtractPopApiOverquotaPayload === 'function'
                                       ? window.wcElInvExtractPopApiOverquotaPayload(response)
                                       : null;

                if (overquotaPayload && typeof window.wcElInvShowPopApiOverquotaDialog === 'function') {
                    WooPoPToFattureInCloud.api.modalContainer.classList.add('close');
                    WooPoPToFattureInCloud.api.modalContainer.classList.remove('open');
                    WooPoPToFattureInCloud.api.modalContainer.classList.remove('success');
                    WooPoPToFattureInCloud.api.modalContent.classList.add('close');
                    WooPoPToFattureInCloud.api.modalContent.classList.remove('open');
                    window.wcElInvShowPopApiOverquotaDialog(overquotaPayload);
                    return;
                }

                console.table(response);

                // Not found
                if (!response) {
                    message += "<h4>" + WooPoPToFattureInCloud.api.localized.messageLabel + " " + "Error" + "</h4>";
                } else {
                    if (response.body) {
                        let jsonObject = response.body;

                        delete response.body
                        console.table(response);
                        console.log('Response body');
                        console.table(jsonObject);
                        if (response.title && '' !== response.title) {
                            message += "<h4>" + response.title + "</h4>";
                        }
                        message += "<p>" + response.message + "</p>";
                    } else {
                        message = response.message;
                        if (0 === response.code) {
                            console.log('bodyRequest: ', JSON.parse(response.bodyRequest));
                        }
                    }
                }

                // Set message
                WooPoPToFattureInCloud.api.modalContent.innerHTML = message;
                WooPoPToFattureInCloud.api.closePoUP(type);
                WooPoPToFattureInCloud.api.copyClipBoard();
            },

            /**
             * Ajax Request
             * @param data
             * @param append
             * @param resolve
             */
            ajaxRequest: function (data, append, resolve) {
                let ajaxResponse = '';

                $.ajax({
                    url: WooPoPToFattureInCloud.api.localized.ajaxUrl,
                    method: 'POST',
                    cache: false,
                    data: data,
                    /**
                     * Before Send
                     */
                    beforeSend: function (jqXHR, settings) {
                        // Container
                        WooPoPToFattureInCloud.api.modalContainer.classList.remove('close');
                        WooPoPToFattureInCloud.api.modalContainer.classList.add('open');
                    }.bind(this),

                    /**
                     * Success
                     */
                    success: function (response, textStatus, jqXHR) {
                        if (append) {
                            ajaxResponse = response;
                            resolve(ajaxResponse);
                        }
                    }.bind(this),

                    /**
                     * Error
                     */
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error("error: " + errorThrown);
                    }.bind(this),

                    /**
                     * Complete
                     */
                    complete: function () {
                        // Container
                        WooPoPToFattureInCloud.api.modalContainer.classList.add('success');
                        WooPoPToFattureInCloud.api.modalContainer.classList.remove('close');
                        WooPoPToFattureInCloud.api.modalContainer.classList.add('open');
                        // Content
                        WooPoPToFattureInCloud.api.modalContent.classList.remove('close');
                        WooPoPToFattureInCloud.api.modalContent.classList.add('open');
                    }.bind(this)
                });
            },

            /**
             * Promise Reduce
             * @param data
             */
            reduce: function (data) {
                data.reduce((promise, func, index) => {
                    return promise.then(val => {
                        return func(val);
                    });
                }, Promise.resolve()).then(() => {
                    /* -- */
                }).catch(err => {
                    console.log(err);
                })
            },

            /**
             * Constructor
             */
            construct: function () {
                _.bindAll(this,
                    'oAuth',
                    'oAuthDevice',
                    'oAuthExchange',
                    'refreshOAuthToken',
                    'setCompanyId',
                    'setPaymentAccount',
                    'mappingPayMethodAndPayAccount',
                    'mappingPayGatewayAndPayMethod',
                    'createInvoice',
                    'verifyEInvoice',
                    'syncEInvoice',
                    'sendEInvoice',
                    'deleteInvoice',
                    'reduce',
                    'responseMessage',
                    'ajaxRequest',
                    'closePoUP',
                    'copyClipBoard',
                );

                this.init();
            },
        }

        window.addEventListener('load', function (evt) {
            WooPoPToFattureInCloud.api.construct();
            console.log('POP to FattureInCloud - load');
        });

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