class EbayLink {

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

        this.url = (url.trim().endsWith('/')) ? url.slice(0, -1) : url;

        this.proxy = proxy;
        this.platform = 'eBay';
        this.program  = 'eBay';
        
        this.itm  = this.getItm();
        this.epid = this.getEPID();
    }

    isLink() {

        return this.url.includes('ebay');
    }


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


    addTag( tag ) {

        if( this.url.includes( 'sch' ) ) {
        
            return `${this.url}&mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=${tag}`;
        }

        let url = this.url.split('?')[0];

        return `${url}?mkevt=1&toolid=10001&mkcid=1&mkrid=724-53478-19255-0&siteid=101&campid={campaign-id}&customid=${tag}`;
    }

    
    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;
    }



    /**
     * 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.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 };
    }
}