(function() {
    const injectComponent = function(componentName, params, initiatingScriptTag) {
        if (componentName === 'cssoverride')  {
            const cssHref = initiatingScriptTag.getAttribute('src').replace('pn-marketweb-inject.js', 'pn-marketweb-cssoverride.css');
            const link = document.createElement('link');
            link.setAttribute('href', cssHref);
            link.setAttribute('rel', 'stylesheet');
            document.head.append(link);
            return;
        }

        if (componentName.indexOf('pn-') !== 0) {
            console.warn('Not a postnord component')
            return;
        }
        const component = document.createElement(componentName);
        const ignoredParameters = ['inject', 'domlocation'];
        params.forEach((paramVal, paramKey) => {
            if (ignoredParameters.indexOf(paramKey) !== -1) {
                return;
            }
            component.setAttribute(paramKey, paramVal);
        });
        const placement = params.get('domlocation') ?? 'self';
        switch(placement) {
            case 'top':
                document.body.insertBefore(component, document.body.firstElementChild);
                break;
            case 'bottom':
                document.body.appendChild(component);
                break;
            case 'self':
            default:
                initiatingScriptTag.parentElement.insertBefore(component, initiatingScriptTag);
                break;
        }
    };
    const checkParameters = function(injectionScriptTag) {
        const src = injectionScriptTag.getAttribute('src');
        if (!src.indexOf('?')) {
            return;
        }
        const queryString = src.substring(src.indexOf('?') + 1);
        const params = new URLSearchParams(queryString);
        const inject = params.get('inject').split(',');
        inject.forEach(function(value) { injectComponent(value.trim(), params, injectionScriptTag) });
    }
    const injectionScriptTags = [...document.querySelectorAll('script[src*="pn-marketweb-inject.js"]')];
    
    injectionScriptTags.forEach(function (injectionScriptTag) {
        if (injectionScriptTag.hasAttribute('data-initiated')) {
            return;
        }
        injectionScriptTag.setAttribute('data-initiated', true);
        checkParameters(injectionScriptTag);
    });

})();
