console.log('this is a Paid post');

/**
 * Deve verificare se esiste il gclid in querystring
 * in caso affermativo 
 * - recupera tutti i link che hanno l'attributo 'data-bmaff-paid-link'
 * - recupera un codice associato al gclid ( lo scrive in una lookuptable )
 * - aggiunge al tracking id il riferimento al gclid
 * - copia nel campo href il contenuto di data-bmaff-paid-link ( link in chiaro ) con  il nuovo trackingid 
 */
class PaidManager {

    constructor( api_base = 'http://127.0.0.1:8000/api/') {

        this.api_base = api_base;

        this.gclid    = this.getGclid();
        this.gclid_id = 0;

        if( this.gclid == '' ) return;

        this.links = this.getPaidLinks();
        

        this.addGclidToTrackingId = this.addGclidToTrackingId.bind(this);

        this.getGclidId( this.addGclidToTrackingId );
    }

    getGclid(){

        return window.location.search.replace(/.*gclid=(.*?)(&.*$|$)/g,'$1');
    }


    /**
     * @return array - elementi che hanno il link in chiaro
     */
    getPaidLinks() {

        return [].map.call( document.querySelectorAll('[data-bmaff-trackingid]'), i=>i );
    }


    getGclidId( callback ) {

        let api_call = `${this.api_base}gclid-code/${this.gclid}/`;

        fetch( api_call )
        .then( response => response.json() )
        .then( data => {

            let results = data ? data : null;

            if ( results ) { 

                callback( results.gclid_id );
            }
        });

    }


    addGclidToTrackingId( gclidID ) {

        this.links.forEach( link => {
            
            if( typeof link.dataset.bmaffPaidLink != 'undefined' ) {

                let newTrackingID = this.getNewTrackingID( link.dataset.bmaffTrackingid, gclidID );

                link.href = link.href.replace( link.dataset.bmaffTrackingid, newTrackingID);
                link.dataset.bmaffTrackingid = newTrackingID;
                
                //delete(link.dataset.bmaffPaidLink)
            }
        });
        
    }

    getNewTrackingID( trackingID, gclidID ) {

        return trackingID.replace(/(.*?)(-21|$)/,`$1gclid${gclidID}$2`);        
    }




}

document.addEventListener("DOMContentLoaded", () => {

    const blzPaidManager = new PaidManager(BLZ_API_RENDERING_MANAGER);
});

