import { deleteCookie } from './common';

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

/**
 * Enables tracking via google analytics by resetting the opt-out cookie
 */
export const enableGoogleTagManager = settings => {
    /* eslint-disable */
    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer',settings.id);
    /* eslint-enable */
};

export const initGoogleTagManager = settings => {
    if (!settings.tagManager.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.tagManager.persist === 1) {
        enableGoogleTagManager(settings.tagManager);
    }

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