var customParserId = document.currentScript.getAttribute("id");
jQl.ready(document).ready(function () {
    const CustomParser = (function () {

        var id;
        var locale = "";
        var functionName;
        var variableName;
        var contextVariable;
        const localeRegex = '^\\/[a-z]{2}-[a-z]{2}|\\/[a-z]{2}-[0-9]{2}';

        const thizz = {
            defineFunctionAndCallIfNeeded: function () {

                if (customParserId == null) {
                    console.warn("No ID attribute defined for the custom parser!");
                    return;
                }

                functionName = customParserId + "Function";
                variableName = customParserId + "Variable";

                defineFunction();

                extractLocale();

                if (contextVariableIsDefined()) {
                    thizz.parse();
                }
            },

            parse: function () {
                window.onload = function () {
                    const matches = document.querySelectorAll('div[data-component-path]');
                    if (matches.length === 0) {
                        return;
                    }

                    const requestParameters = extractParameters();
                    matches.forEach(function (match) {
                        handleComponentWithCsrfToken(match, requestParameters);
                    });
                }
            }
        };

        const defineFunction = function () {
            window[functionName] = thizz.parse;
        };

        const extractLocale = function () {
            const currentPath = window.location.pathname;
            if (currentPath == null || currentPath.length === 0) {
                return;
            }

            const localeMatches = currentPath.match(localeRegex);
            if (localeMatches == null || localeMatches.length === 0) {
                return;
            }

            const firstMatch = localeMatches[0];
            if (currentPath.startsWith(firstMatch)) {
                locale = firstMatch;
            }
        };

        const contextVariableIsDefined = function () {
            contextVariable = window[variableName];
            return typeof contextVariable === "object";
        };


        const extractParameters = function () {
            const requestParameters = [];
            const googleAdsKey = "gclid=";
            const emailKey = "utm_medium=email";
            var referer;
            if (window.location.search.includes(googleAdsKey)) {
                referer = "google-ads";
            } else if (window.location.search.includes(emailKey)) {
                referer = "email";
            }
            requestParameters.push("renderType=render-aware");
            if (referer !== undefined) {
                requestParameters.push("referer=" + referer);
            }
            for (let key in contextVariable) {
                if (contextVariable.hasOwnProperty(key)) {
                    //If both google/email key and refer header are received, the header one is ignored.
                    if (key !== 'referer' || referer === undefined) {
                        requestParameters.push(key + "=" + contextVariable[key]);
                    }
                }
            }

            return '?' + requestParameters.join('&');
        };

        const handleComponentWithCsrfToken = function (match, requestParameters) {

            handleComponentWithCsrfTokenRetryable(function () {
                const visitorCookie = Commons.getCookieValue("visitorNewReturning");
                if (typeof visitorCookie === 'undefined') {
                    Commons.userContextWithCsrfToken(handleComponent(match, requestParameters));
                    return;
                }
                handleComponent(match, requestParameters);
            }, 500);
        };


        const maxRetries = 10;
        var retries = 0;
        const handleComponentWithCsrfTokenRetryable = function (callback, delay) {
            if (typeof Commons === 'undefined' && retries < maxRetries) {
                console.warn("Commons.js was not loaded yet, retry render aware components loading after " + delay + " ms.");
                retries++;
                setTimeout(function() {
                    handleComponentWithCsrfTokenRetryable(callback, delay);
                }, delay);
                return;
            }
            callback();
        };

        const handleComponent = function (match, requestParameters) {
            const componentPath = match.getAttribute("data-component-path");
            if (componentPath == null) {
                return;
            }

            BLC.get({
                headers: {
                    "Accept": "text/html"
                },
                dataType: "html",
                url: locale + componentPath + requestParameters,
                error: function (data) {
                    handleError(data, componentPath);
                }
            }, function (response) {
                addComponentContent(response, match);
            });
        };

        const handleError = function (data, componentName) {
            if (data.status === 404) {
                console.warn("Could not find " + componentName + " while parsing!");
                return;
            }

            console.error("Encountered an error while parsing for " + componentName + "!");
        };

        const addComponentContent = function (response, match) {
            if (response == null || response.length === 0) {
                return;
            }

            $(match).html(response);
        };

        return thizz;
    });


    const customParser = CustomParser();
    customParser.defineFunctionAndCallIfNeeded();
});