import { deleteCookie } from './common';

/**
 * Disables tracking via google analytics by resetting the value and
 * expiry date of the cookies.
 */
// eslint-disable-next-line no-inner-declarations
export const disableGoogleAnalytics = settings => {
    deleteCookie('gaCookie');
    deleteCookie('_gat');
    deleteCookie(`_gat_gtag_${settings.id}`);
    deleteCookie('gaCookie_gid');
};

/**
 * Enables tracking via google analytics by resetting the opt-out cookie
 */
export const enableGoogleAnalytics = settings => {
    /* eslint-disable */
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', settings.id, {
        'cookieName': 'gaCookie',
        'cookieExpires': 60 * 60 * 24 * 90,
    });
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');
    /* eslint-enable */
};

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

    // in opt-out mode, inject and initialize google analytics right away
    if (settings.mode === 'opt-out') {
        enableGoogleAnalytics(settings.analytics);
    }

    // in opt-in mode, wait for event to allow injection
    document.addEventListener('cookie-consent-status-change', event => {
        if (event.detail.status === 'allow') {
            enableGoogleAnalytics(settings.analytics);
            console.log("test2");
        } else {
            disableGoogleAnalytics(settings.analytics);
        }
    });
};
