(function ($) {

    const bnplBanner = {
        jsonData: {},
        checkExpireThreshold: 60000,
        token: '',
        tokenValidity: 0,
        tokenPromise: null,
        init: function() {
            let that = this;
            const $body = $('body');

            $body.on('updated_cart_totals', function (e) {
                const div = document.getElementById('addon-payments-widget');
                that.jsonData.amount = parseFloat(div.getAttribute('data-amount')) * 100;
                that.checkOnUpdate();
                that.renderOnUpdated();
            });

            $(document).on('found_variation', 'form.cart', function( event, variation ) {
                const div = document.getElementById('addon-payments-widget');
                var price = variation.display_price;
                that.jsonData.amount = price * 100;
                $(div).attr('data-amount', price);
                that.checkOnUpdate();
                that.renderOnUpdated();
            });

            this.token = addonpayments.authToken.token;
            this.tokenValidity = addonpayments.authToken.token_validity;
            this.jsonData = this.getJsonData();
            this.render();
        },
        render: function() {
            /** @var {object} NEMURUWIDGET */
            NEMURUWIDGET.setEpgBaseUrl(addonpayments.baseUrl);
            NEMURUWIDGET.renderSimulationWidget(this.token, this.jsonData, 'addon-payments-widget', 'Nemuru');
        },
        checkOnUpdate: function() {
            var currentTime = Date.now();
            if (this.tokenValidity <= (currentTime + this.checkExpireThreshold)) {
                this.tokenPromise = this.requestAuthorizationToken();
           }
        },
        renderOnUpdated: function () {
            var that = this;
            if(null !== this.tokenPromise) {
                this.tokenPromise.then(function (data) {
                    that.token = data.token;
                    that.tokenValidity = data.token_validity;
                    that.render();
                    that.tokenPromise = null;

                }).catch(function (err) {
                    console.error(err);
                });
            }else {
                this.render();
            }
        },
        requestAuthorizationToken: function () {
            return new Promise(function (resolve, reject) {
                let ajaxExecutor = new XMLHttpRequest();

                ajaxExecutor.onreadystatechange = function () {

                    if (ajaxExecutor.readyState !== 4) return;

                    if (ajaxExecutor.status >= 200 && ajaxExecutor.status < 300) {
                        var data;

                        try {
                            data = JSON.parse(ajaxExecutor.response);
                        } catch (error) {
                            reject('Invalid authorization response');
                        }

                        if (data.hasOwnProperty('error')) {
                            reject(data.error.message);
                        }

                        resolve(data);
                    }

                    if (ajaxExecutor.status >= 400) {
                        reject('Authorization failed 1');
                    }
                };

                ajaxExecutor.addEventListener('timeout', function (e) {
                    reject('Authorization timed out');
                });

                ajaxExecutor.open('POST', addonpayments.url + '?action=' + addonpayments.action);
                ajaxExecutor.setRequestHeader('Accept', 'application/json');
                ajaxExecutor.send();
            });
        },
        getJsonData: function() {
            /** @var {Object} addonpayments */
            // let [decimalSeparator, thousandSeparator] = addonpayments.currency.specifications.symbol;

            return {
                "amount": addonpayments.amount * 100,
                "product": addonpayments.banner.product,
                "styleColor": addonpayments.banner.styleColor,
                "styleVariant": addonpayments.banner.styleVariant,
                "styleBranding": addonpayments.banner.styleBranding,
                "style": "width: 100%",
                "clientId": addonpayments.customerId,
                "currency": addonpayments.currency,
                "locale": addonpayments.locale,
                "decimalSeparator": '.',
                "thousandSeparator": ','
            }
        }
    };

     document.addEventListener('DOMContentLoaded', function () {
        bnplBanner.init();
     });

})(jQuery);