import { deleteCookie } from './common';

/**
 * TO BE DONE: Disables tracking via google tag manager
 */
export const disableGTag = () => {
    deleteCookie('_gid');
    deleteCookie('_ga');
};

/**
 * Enables tracking via google analytics by resetting the opt-out cookie
 */
export const enableGTag = settings => {
    /* eslint-disable */
    var script = document.createElement('script');
    script.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=',  settings.id);
    document.body.appendChild(script);
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', settings.id);
    /* eslint-enable */
};

export const initGTag = settings => {
    if (!settings.gtag.id) {
        console.warn('Site Tracking: No tag manager ID specified');
        return;
    }

    // in opt-out mode, inject and initialize google tag manager right away
    if (settings.mode === 'opt-out' || settings.gtag.persist === 1) {
        enableGTag(settings.gtag);
    }

    // in opt-in mode, wait for event to allow injection
    document.addEventListener('cookie-consent-status-change', event => {
        if (event.detail.status === 'allow') {
            enableGTag(settings.gtag);
        } else {
            disableGTag();
        }
    });
};