window.WooPoPToSdIPec = window.WooPoPToSdIPec || {};

;(
    function (_, $, wsdipecScripts) {

        "use strict";

        /**
         * POPToSdIPec.api
         */
        WooPoPToSdIPec.api = {

            /**
             * localized
             */
            localized: wsdipecScripts,

            /**
             * Endpoint
             */
            smtpSaveEndpoint: 'smtpSave',
            uploadInvoiceEndpoint: 'uploadInvoice',

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

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

            /**
             * Login Wrap
             */
            loginActionWrap: document.querySelector('.wsdipec_login .wsdipec_login_wrap'),

            /**
             * Configured
             */
            Configured: 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('.wsdipec_login .api-action');
                this.actions = document.querySelectorAll('.actions .api-action');
                this.Configured = WooPoPToSdIPec.api.localized.feConfigured;

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

                this.smtpSave();
                this.uploadInvoice();
            },

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

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

            /**
             * Smtp Save Request
             */
            smtpSave: function () {
                let action = document.getElementById('api_smtp');
                if (action) {
                    action.addEventListener('click', function () {
                        let feSmtpHost = document.getElementById('wsdipec_smtp_host');
                        let feSmtpSecure = document.getElementById('wsdipec_smtp_secure');
                        let feSmtpUser = document.getElementById('wsdipec_smtp_user');
                        let feSmtpPass = document.getElementById('wsdipec_smtp_pass');
                        let feSmtpExpiredPass = document.getElementById('wsdipec_smtp_pass_expiration');

                        let response = [
                            // Request
                            function () {
                                return new Promise(function (resolve, reject) {
                                    WooPoPToSdIPec.api.ajaxRequest({
                                            'action': WooPoPToSdIPec.api.smtpSaveEndpoint,
                                            'ajaxAction': 'feSmtpSaveRequest',
                                            'smtpHost': feSmtpHost.value,
                                            'smtpSecure': feSmtpSecure.value,
                                            'smtpUser': feSmtpUser.value,
                                            'smtpPass': feSmtpPass.value,
                                            'smtpExpiredPass': feSmtpExpiredPass.value,
                                            'nonce': WooPoPToSdIPec.api.localized.ajaxNonce,
                                        }, true, resolve
                                    )
                                    console.log("SMTP Save request... complete");
                                })
                            },
                            // Response
                            function (response) {
                                return new Promise(function (resolve, reject) {
                                    console.log("SMTP Save response... complete");
                                    WooPoPToSdIPec.api.responseMessage(response, 'smtp');
                                })
                            }
                        ]

                        WooPoPToSdIPec.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) {
                                        WooPoPToSdIPec.api.ajaxRequest({
                                                'action': WooPoPToSdIPec.api.uploadInvoiceEndpoint,
                                                'ajaxAction': 'feUploadRequest',
                                                'type': 'upload',
                                                'orderID': id,
                                                'choiceType': cType,
                                                'orderType': oType,
                                                'provider': provider,
                                                'nonce': WooPoPToSdIPec.api.localized.ajaxNonce,
                                            }, true, resolve
                                        )
                                        console.log("Upload request... complete");
                                    })
                                },
                                function (response) {
                                    return new Promise(function (resolve, reject) {
                                        console.log("Upload response... complete");
                                        WooPoPToSdIPec.api.responseMessage(response, 'upload');
                                    })
                                }
                            ];

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

                // Not found
                if (!response) {
                    message += "<h4>" + WooPoPToSdIPec.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 ('dev' === WooPoPToSdIPec.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
                WooPoPToSdIPec.api.modalContent.innerHTML = message;
                WooPoPToSdIPec.api.closePoUP(type);
            },

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

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

                this.init();
            },
        }

        window.addEventListener('load', function (evt) {
            WooPoPToSdIPec.api.construct();
            console.log('POP to SdI via PEC - load');
        });

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