import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';

//Code copied from https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/projects/angular-google-tag-manager/src/lib/angular-google-tag-manager.service.ts
@Injectable()
export class GoogleTagManagerService {
    private isLoaded = false;
    private gtmId: string;

    private browserGlobals = {
        windowRef(): any {
            return window;
        },
        documentRef(): any {
            return document;
        }
    };

    constructor(
    ) {
        this.gtmId = environment.gtmKey;
    }

    public getDataLayer() {
        const window = this.browserGlobals.windowRef();
        window['dataLayer'] = window['dataLayer'] || [];
        return window['dataLayer'];
    }

    private pushOnDataLayer(obj: object) {
        const dataLayer = this.getDataLayer();

        if(obj) {
            obj['gtm.start'] = new Date().getTime(),
            obj['event'] = 'gtm.js'
        }
        dataLayer.push(obj);
    }

    public addGtmToDom() {
        const doc = this.browserGlobals.documentRef();

        const gtmScript = doc.createElement('script');
        gtmScript.id = 'GTMscript';
        gtmScript.async = true;
        gtmScript.src = '//www.googletagmanager.com/gtm.js?id=' + this.gtmId;
        doc.head.insertBefore(gtmScript, doc.head.firstChild);

        const ifrm = doc.createElement('iframe');
        ifrm.setAttribute('src', '//www.googletagmanager.com/ns.html?id=' + this.gtmId);
        ifrm.style.width = '0';
        ifrm.style.height = '0';
        ifrm.style.display = 'none';
        ifrm.style.visibility = 'hidden';

        const noscript = doc.createElement('noscript');
        noscript.id = 'GTMiframe';
        noscript.appendChild(ifrm);

        doc.body.insertBefore(noscript, doc.body.firstChild);
        this.isLoaded = true;
    }

    public pushTag(item: object) {        
        this.pushOnDataLayer(item);
        
        if (!this.isLoaded) {
            this.addGtmToDom();
        }
    }
}