/**
 * 2007-2021 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2021 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 *
 * Don't forget to prefix your containers with your own identifier
 * to avoid any conflicts with others containers.
 */
(function ($) {
    var checkExpireThreshold = 60000;

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelector('body').addEventListener('checkout_error', function (e) {
            console.error(e);
        });

        var vault = document.getElementById('addonpayments-' + addonpayments.instance);

        if ('undefined' === (typeof vault) || null === vault) {
            return;
        }

        window.addEventListener('message', function (e) {
            if ('undefined' === (typeof e.data)) {
                return;
            }

            try{
                var data = JSON.parse(e.data);
                switch (data.action) {
                    case 'regisered':
                        registerAccountCallback(data);
                        break;
                    default:
                        console.debug(e);
                }
            }
            catch (e) {
                // Just catch any errors since data may be invalid JSON.
            }
        });

        checkTokenExpiration(parseInt(vault.getAttribute('data-valid-until')));
        var token = vault.getAttribute('data-token');
        var theme = 'string' === typeof addonpayments.style ? EPGJS_STYLE[addonpayments.style] : addonpayments.style;
        EPGJS_COMM.setEpgBaseUrl(vault.getAttribute('data-api-base'));
        EPGJS_STYLE.setCssTheme(theme);
        EPGJS_COMM.setShowOnlyCardRegister(true);
        EPGJS_COMM.setOnlyRegisteredAccounts(true);
        EPGJS_COMM.setMerchantRegisterAccountCallback(registerAccountCallback);
        EPGJS_COMM.setRegisterAccountErrorCallback(registerAccountErrorCallback);
        EPGJS_I18N.setLang(addonpayments.langcode);
        EPGJS_I18N.setI18n(addonpayments.i18n);
        EPGJS.renderCashier(token, 'addonpayments-form-' + addonpayments.instance);
    });

    function registerAccountCallback(payload) {
        var info = document.getElementById('addonpayments-info-' + addonpayments.instance);
        info.classList.remove('hidden');
        info.classList.remove('hidden-sm-up');
        info.classList.remove('hidden-lg-down');
        var vault = document.getElementById('addonpayments-' + addonpayments.instance);
        var registerId = 'addonpayments-register-' + addonpayments.instance;
        var registerForm = document.createElement('form');
        registerForm.setAttribute('id', registerId);
        registerForm.setAttribute('method', 'post');
        registerForm.setAttribute('action', vault.getAttribute('data-register-callback'));

        var responseElement = document.createElement('input');
        responseElement.setAttribute('id', registerId + '__response');
        responseElement.setAttribute('type', 'hidden');
        responseElement.setAttribute('name', 'registerResponse');
        payload.customer = vault.getAttribute('data-customer');
        responseElement.value = JSON.stringify(payload);
        registerForm.appendChild(responseElement);
        vault.parentNode.appendChild(registerForm);
        registerForm.submit();
    }

    function registerAccountErrorCallback(data) {
        try {
            switch (true) {
                case (data.message.indexOf('expired') !== -1):
                    var expired = document.getElementById('addonpayments-expired-' + addonpayments.instance);
                    expired.classList.remove('hidden');
                    expired.classList.remove('hidden-sm-up');
                    expired.classList.remove('hidden-lg-down');
                    setTimeout(doReload, 2500);
                    break;
                case (data.message.indexOf('Reached limit accounts for the paysol') !== -1):
                    var error = document.getElementById('addonpayments-error-' + addonpayments.instance);
                    error.textContent = addonpayments.translations.reachedPaysolLimit;
                    error.classList.remove('hidden');
                    error.classList.remove('hidden-sm-up');
                    error.classList.remove('hidden-lg-down');
                    break;
                default:
                    var error = document.getElementById('addonpayments-error-' + addonpayments.instance);
                    error.textContent = addonpayments.translations.unknownError;
                    error.classList.remove('hidden');
                    error.classList.remove('hidden-sm-up');
                    error.classList.remove('hidden-lg-down');
                    console.debug(data);
            }
        }
        catch (e) {
            console.error(e);
        }
    }

    function checkTokenExpiration(expiresOn) {
        setTimeout(function () {
            var aboutToExpire = document.getElementById('addonpayments-timeout-' + addonpayments.instance);
            var expired = document.getElementById('addonpayments-expired-' + addonpayments.instance);
            var currentTime = Date.now();
            var unit = (60 * 1000);
            var expiration = ((expiresOn - currentTime) / unit).toFixed(0);

            if (expiresOn <= (currentTime + checkExpireThreshold)) {
                aboutToExpire.classList.add('hidden');
                aboutToExpire.classList.add('hidden-sm-up');
                aboutToExpire.classList.add('hidden-lg-down');
                expired.classList.remove('hidden');
                expired.classList.remove('hidden-sm-up');
                expired.classList.remove('hidden-lg-down');
                setTimeout(doReload, 2500);
                return;
            }

            if ((expiration * unit) - (checkExpireThreshold * 2) <= checkExpireThreshold) {
                aboutToExpire.classList.remove('hidden');
                aboutToExpire.classList.remove('hidden-sm-up');
                aboutToExpire.classList.remove('hidden-lg-down');
            }

            checkTokenExpiration(expiresOn);
        }, checkExpireThreshold);
    }

    function doReload(e) {
        if (null !== e && 'undefined' !== (typeof e)) {
            e.preventDefault();
        }

        window.location.reload(true);
    }
})();
