window.WooPoPToFattureAruba = window.WooPoPToFattureAruba || {};

;(
    function (_, $, wafScripts) {

        "use strict";

        /**
         * POPToFattureAruba.api
         */
        WooPoPToFattureAruba.api = {

            /**
             * localized
             */
            localized: wafScripts,

            /**
             * Endpoint
             */
            oAuthEndpoint: 'authSignIn',
            refreshOAuthTokenEndpoint: 'refreshOAuthToken',
            uploadInvoiceEndpoint: 'uploadInvoice',
            getDocumentStateEndpoint: 'getDocumentState',
            getDocumentNotifyEndpoint: 'getDocumentNotify',

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

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

            /**
             * Login Wrap
             */
            loginActionWrap: document.querySelector('.waf_login .waf_login_wrap'),

            /**
             * Connected
             */
            Connected: null,

            /**
             * 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('.waf_login .api-action');
                this.actions = document.querySelectorAll('.actions .api-action');
                this.Connected = WooPoPToFattureAruba.api.localized.feConnected;

                // 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.refreshOAuthToken();
                this.uploadInvoice();
                this.getDocumentState();
                this.sendInvoicePDF();
                this.getDocumentNotify();
                this.afterLogOut();
            },

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

                        if ('state' !== type) {
                            setTimeout(function () {
                                window.location.reload(true);
                            }, 500)
                        }
                    })
                }
            },

            /**
             * OAuth Request
             */
            oAuth: function () {
                let action = document.getElementById('api_oauth');
                if (action) {
                    action.addEventListener('click', function () {
                        let feApiUrl = document.getElementById('waf_api_url');
                        let feApiUid = document.getElementById('waf_api_uid');
                        let feApiKey = document.getElementById('waf_api_key');
                        feApiKey.setAttribute('type', 'password');
                        let response = [
                            // Request
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToFattureAruba.api.ajaxRequest({
                                            'action': WooPoPToFattureAruba.api.oAuthEndpoint,
                                            'ajaxAction': 'feOAuthRequest',
                                            'type': 'OAuth',
                                            'apiUrl': feApiUrl.value,
                                            'apiUid': feApiUid.value,
                                            'apiKey': feApiKey.value,
                                            'nonce': WooPoPToFattureAruba.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("OAuth request... complete");
                                })
                            },
                            // Response
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("OAuth Token response... complete");
                                    WooPoPToFattureAruba.api.responseMessage(response, 'oauth');
                                })
                            }
                        ]

                        WooPoPToFattureAruba.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) {
                                    WooPoPToFattureAruba.api.ajaxRequest({
                                            'action': WooPoPToFattureAruba.api.refreshOAuthTokenEndpoint,
                                            'ajaxAction': 'feOAuthExchangeRequest',
                                            'type': 'OAuth',
                                            'refresh': refresh,
                                            'nonce': WooPoPToFattureAruba.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");
                                    WooPoPToFattureAruba.api.responseMessage(response, 'oauth');
                                })
                            }
                        ];

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

            /**
             * Upload Invoice
             */
            uploadInvoice: function () {
                let actionsUpload = document.querySelectorAll('[id*="api_import_"]');
                if (actionsUpload) {
                    actionsUpload.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) {
                                        WooPoPToFattureAruba.api.ajaxRequest({
                                                'action': WooPoPToFattureAruba.api.uploadInvoiceEndpoint,
                                                'ajaxAction': 'feUploadRequest',
                                                'type': 'upload',
                                                'orderID': id,
                                                'choiceType': cType,
                                                'orderType': oType,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureAruba.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Upload request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Upload response... complete");
                                        WooPoPToFattureAruba.api.responseMessage(response, 'upload');
                                    })
                                }
                            ];

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

            /**
             * Invoice State
             */
            getDocumentState: function () {
                let actionsState = document.querySelectorAll('[id*="api_state_"]');
                if (actionsState) {
                    actionsState.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let id = action.getAttribute('data-id');
                            let docName = action.getAttribute('data-docname');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureAruba.api.ajaxRequest({
                                                'action': WooPoPToFattureAruba.api.getDocumentStateEndpoint,
                                                'ajaxAction': 'feGetDocumentStateRequest',
                                                'type': 'state',
                                                'orderID': id,
                                                'docName': docName,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureAruba.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("State request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("State response... complete");
                                        WooPoPToFattureAruba.api.responseMessage(response, 'state');
                                    })
                                }
                            ];

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

            /**
             * Send Invoice PDF
             */
            sendInvoicePDF: function () {
                let actionsSendPdf = document.querySelectorAll('[id*="api_send_pdf_"]');
                if (actionsSendPdf) {
                    actionsSendPdf.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let id = action.getAttribute('data-id');
                            let docName = action.getAttribute('data-docname');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureAruba.api.ajaxRequest({
                                                'action': WooPoPToFattureAruba.api.getDocumentStateEndpoint,
                                                'ajaxAction': 'feGetDocumentStateRequestForSendPdf',
                                                'type': 'send_pdf',
                                                'orderID': id,
                                                'docName': docName,
                                                'includePdfFile': 1,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureAruba.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Send PDF request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Send PDF response... complete");
                                        WooPoPToFattureAruba.api.responseMessage(response, 'send_pdf');
                                    })
                                }
                            ];

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

            /**
             * Invoice Notify
             */
            getDocumentNotify: function () {
                let actionsNotify = document.querySelectorAll('[id*="api_notify_"]');
                if (actionsNotify) {
                    actionsNotify.forEach(function (action) {
                        action.addEventListener('click', function () {
                            let id = action.getAttribute('data-id');
                            let docName = action.getAttribute('data-docname');
                            let provider = action.getAttribute('data-provider');

                            let response = [
                                function () {
                                    return new Promise(function (resolve, reject) {
                                        WooPoPToFattureAruba.api.ajaxRequest({
                                                'action': WooPoPToFattureAruba.api.getDocumentNotifyEndpoint,
                                                'ajaxAction': 'feGetDocumentNotifyRequest',
                                                'type': 'notify',
                                                'orderID': id,
                                                'docName': docName,
                                                'provider': provider,
                                                'nonce': WooPoPToFattureAruba.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Notify request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Notify response... complete");
                                        WooPoPToFattureAruba.api.responseMessage(response, 'notify');
                                    })
                                }
                            ];

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

            /**
             * Log out
             */
            afterLogOut: function () {
                let logout = WooPoPToFattureAruba.api.getParameterByName('waf_reset_login');
                if (logout) {
                    window.location.href = WooPoPToFattureAruba.api.removeParam(
                        "waf_reset_login",
                        window.location.href
                    );
                }
            },

            /**
             * 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') {
                    WooPoPToFattureAruba.api.modalContainer.classList.add('close');
                    WooPoPToFattureAruba.api.modalContainer.classList.remove('open');
                    WooPoPToFattureAruba.api.modalContainer.classList.remove('success');
                    WooPoPToFattureAruba.api.modalContent.classList.add('close');
                    WooPoPToFattureAruba.api.modalContent.classList.remove('open');
                    window.wcElInvShowPopApiOverquotaDialog(overquotaPayload);
                    return;
                }

                // Not found
                if (!response) {
                    message += "<h4>" + WooPoPToFattureAruba.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.message) {
                            message += "<h4>" + response.message + "</h4>";
                        }

                        if ('notify' === type && response.notificationMessages) {
                            Object.keys(response.notificationMessages).forEach(function (typeNotify, index) {
                                let dateTime = response.notificationMessages[typeNotify].date;
                                let date = dateTime.replace('T', ' ');
                                date = date.replace('.000+00:00', '');
                                message += "<div class='notify_message-" + typeNotify + "'><p>";
                                if (dateTime) {
                                    message += "<span class='date'>" + WooPoPToFattureAruba.api.localized.dateLabel + date + "</span>";
                                }
                                message += response.notificationMessages[typeNotify].message + "</p></div>";
                            });
                        }

                        if ('state' === type && response.messageState) {
                            message += "<div class='state_message'><p>" +
                                       response.messageState +
                                       "</p></div>";
                        }

                        if ('dev' === WooPoPToFattureAruba.api.localized.mode) {
                            message += "<ul class='message_list'>";
                            Object.keys(jsonObject).forEach(function (name, key) {
                                // Sub items
                                if (Array.isArray(jsonObject[name])) {
                                    jsonObject[name].forEach((item) => {
                                        let entries = Object.entries(item);
                                        if (Array.isArray(entries)) {
                                            message += "<li class='sub_list_li'><ul class='sub_list'>";
                                            entries.forEach((entry) => {
                                                message += "<li><code class='light'>" + entry[0] + ": " + entry[1] + "</code></li>"
                                            })
                                            message += "</ul></li>";
                                        }
                                    })
                                } else {
                                    message += "<li><code class='light'>" + name + ": " + JSON.stringify(jsonObject[name]) + "</code></li>";
                                }
                            });
                            message += "</ul>";
                        }

                    } else {
                        console.table(response);
                        message = response.message;
                        if (0 === response.code) {
                            console.log('bodyRequest: ', JSON.parse(response.bodyRequest));
                        }
                    }
                }

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

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

                $.ajax({
                    url: WooPoPToFattureAruba.api.localized.ajaxUrl,
                    method: 'POST',
                    cache: false,
                    data: data,
                    /**
                     * Before Send
                     */
                    beforeSend: function (jqXHR, settings) {
                        // Container
                        WooPoPToFattureAruba.api.modalContainer.classList.remove('close');
                        WooPoPToFattureAruba.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
                        WooPoPToFattureAruba.api.modalContainer.classList.add('success');
                        WooPoPToFattureAruba.api.modalContainer.classList.remove('close');
                        WooPoPToFattureAruba.api.modalContainer.classList.add('open');
                        // Content
                        WooPoPToFattureAruba.api.modalContent.classList.remove('close');
                        WooPoPToFattureAruba.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',
                    'refreshOAuthToken',
                    'uploadInvoice',
                    'sendInvoicePDF',
                    'getDocumentState',
                    'getDocumentNotify',
                    'reduce',
                    'responseMessage',
                    'ajaxRequest',
                    'closePoUP',
                    'afterLogOut',
                );

                this.init();
            },
        }

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

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