/**
 * =============================================================================
 *  Copyright (c) 2022 excentos Software GmbH, Potsdam, Germany.
 *  All rights reserved. Do not redistribute. Strictly confidential.
 * =============================================================================
 */

/* Decide if startWidget or advisor should be loaded based on existance of a param for startWidget */

// it's either xcStartWidget=teaser or just xcStartWidget (defaults to 'teaser') or any other file that may be specified for a
// custom startWidget

/**
 * if (startWidgetEnabled)
 *  load starWidgetInit.js
 * else
 *  load jsinit (default loadadvisor)
 * */

(function (win, doc) {
    function getScript(searchRegex, type = 'script') {
        var scripts = doc.getElementsByTagName(type);
        for (var i = 0, l = scripts.length; i < l; ++i) {
            if (searchRegex.test(scripts[i].src)) {
                return scripts[i];
            }
        }

        return null;
    }

    function getCurrentScript() {
        const findExcentosScriptRegex = /(excentos\.com|localhost).*loadadvisor/;
        return getScript(findExcentosScriptRegex);
    }

    /**
     *  returns true if xcStartWidget is part of the url parameters, false else
     * @param script script object
     * @returns {boolean}
     */
    function withStartWidget(script) {
        const tmp = script && script.src && script.src.split('?');
        const params = tmp && tmp.length > 1 && tmp[1];
        const paramsArr = params && params.split('&');
        const startWidgetParam = paramsArr && paramsArr.find(param => {
            const pArr = param.split('=')
            return pArr && pArr[0] && pArr[0] === 'xcStartWidget';
        });
        return !!startWidgetParam;
    }

    const scriptTag = getCurrentScript();

    const newNode = document.createElement('script');
    newNode.type = 'text/javascript';

    if (withStartWidget(scriptTag)) {
        // load startWidgetInit
        newNode.id='xc_start-widget__init-script'
        newNode.src = scriptTag.src.replace('loadadvisor', 'startWidgetInit')
    } else {
        // load jsinit
        newNode.id='xc_init-script'
        newNode.src = scriptTag.src.replace('loadadvisor', 'jsinit')
    }
    const body = document.getElementsByTagName('body')[0];

    body.appendChild(newNode);
}(window,document));
