class EbayLink {

    constructor( url, proxy = `/wp-json/api/v1/proxy/` ) {

        this.urlObj = this.cleanUrl( url ); 
        this.url = this.urlObj.toString(); 
        this.proxy = proxy;
        this.platform = 'eBay';
        this.program  = 'eBay';
        
        this.itm     = this.getItm();
        this.epid    = this.getEPID();
        this.var     = this.getVariant();
    }

    cleanUrl(url) {
        let urlObj = new URL(url);
        
        let varParam = urlObj.searchParams.get('var');
        let searchParam = urlObj.searchParams.get('sch');
        
        urlObj.search = '';

        if (varParam) {
            urlObj.searchParams.set('var', varParam);
        }
        
        if (searchParam) {
            urlObj.searchParams.set('sch', searchParam);
        }
        
        return urlObj;
    }

    isLink() {
        return this.urlObj.host.includes('ebay');
    }


    isValid() {
        return this.isLink() && this.itm || this.epid;
    }


    addTag(tag) {
        const obj = {
            mkevt: 1,
            toolid: 10001,
            mkcid: 1,
            mkrid: "724-53478-19255-0",
            siteid: 101,
            campid: '{campaign-id}',
            customid: tag
        };
    
        for (const key in obj) {
            this.urlObj.searchParams.set(key, obj[key]);
        }
    
        console.log('url', this.urlObj.toString());
        return this.urlObj.toString();
    }
    

    
    getItm() {

        /// se non trova nulla ritorna la url tale e quale
        let itm = this.url.replace(/.*ebay.*\/itm\/(\d+?)(\?.*$|$)/ , '$1' );

        this.itm = itm === this.url ? null : itm;

        return this.itm;
    }


    getEPID() {

        /// se non trova nulla ritorna la url tale e quale
        let epid = this.url.replace(/.*ebay\.it\/p\/(\d+?)(\?.*$|$)/ , '$1' );

        this.epid = epid === this.url ? null : epid;

        return this.epid;
    }

    
    /**
     * https://www.ebay.it/itm/235370812639?var=535612020464
     * 
     * il campo da intercettare per rilevare la variazione è ?var=X
     * @returns 
     */
    getVariant() {
            
        let variant = this.url.replace(/.*var=(\d+?)(\?.*$|$)/ , '$1' );
    
        this.variant = variant === this.url ? null : variant;

        return this.variant;
    }


    /**
     * effettua la chiamata e prende i dati del link     
     */
    async getData( api_call ) {

        let response = await fetch( `${this.proxy}${api_call}` )
        this.data = await response.json();
        
        if( typeof this.data.errors !== 'undefined' ) {


            this.data.errors[0].message

            this.data.link  = this.addTag('booBLZTRKood');
            this.data.title = "[!] Prodotto non reperibile da API. <br>Aggiungere il link dopo averne verificato a mano l'esistenza."
            this.data.price = '';
        }

        return this.data;
    }
    
    /**
     * effettua la chiamata e prende i dati del link     
     */
    async getProperties( apiBase ) {

        let apiCall = `${apiBase}ebay_browse_api/get_item/${this.itm}/${this.variant}?${this.uncache5min()}`;
    
        console.log('__apicall', apiCall);
    
        let response = await fetch( `${this.proxy}${apiCall}` )
        this.data = await response.json();
                
        return this.data;
    }


    uncache5min() {

        let now = new Date();
        return `${now.getMonth()}${now.getDate()}${now.getHours()}${now.getMinutes() % 5 }`;
    }

    getCode() {

        let name = (this.itm) ? 'ITM': 'EPID'
        let value = (this.getItm()) ? this.getItm() : this.getEPID()
 
        return { name : name, value : value };
    }
}