import GDPRHandler from "./GDPRHandler";

export default () => {
    if (document.body.aa_disable_gdpr === true) {
        return;
    }

    let sections = {}

    sections.analytics = {
        enable: () => {
            const body = document.querySelector('body');
            let analyticsId = body.getAttribute('data-analytics-id');
            let analyticsConfig = body.getAttribute('data-analytics-config');
            const defaultAnalyticsConfig = {
                'cookie_expires': 13 * 30 * 24 * 60 * 60,  // 13 months/390 days in seconds
                'anonymize_ip': true
            };

            if (!analyticsId) {
                return;
            }

            global.dataLayer = global.dataLayer || [];

            function gtag() {
                dataLayer.push(arguments);
            }

            let config = defaultAnalyticsConfig;
            if (analyticsConfig) {
                config = {
                    ...defaultAnalyticsConfig,
                    ...JSON.parse(analyticsConfig)
                }
            }

            gtag('js', new Date());
            gtag('config', analyticsId, config);

            let script = document.createElement('script');
            script.classList.add('analytics-script');
            script.innerHTML = "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n" +
                "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n" +
                "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n" +
                "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n" +
                "})(window,document,'script','dataLayer','" + analyticsId + "');";

            document.head.appendChild(script);

            let noScript = document.createElement('noscript');
            let iFrame = document.createElement('iframe');
            iFrame.src = "https://www.googletagmanager.com/ns.html?id=" + analyticsId;
            iFrame.style.display = 'none';
            iFrame.style.visibility = 'hidden';
            iFrame.style.height = '0px';
            iFrame.style.width = '0px';

            noScript.appendChild(iFrame);
            body.prepend(noScript);
        },
        disable: () => {
            let scripts = [...document.querySelectorAll('.analytics-script')];
            scripts.forEach((s) => s.remove());
        }
    };

    let handler = new GDPRHandler({
        sections: sections,
    });

    handler.init();
}

