<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Inserisci un Bottone Parse&Render </title>
        <script type="text/javascript" src="/wp/wp-includes/js/tinymce/tiny_mce_popup.js"></script>
        <script type="text/javascript" src="{{base_url}}/lib/AmazonLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/EbayLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/AwinLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/TradeTrackerLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/PartnerizeLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/PrimeVideoLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/LinkPreview.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/ImpactLink.js?{{renewcache}}"></script>
        <link rel="stylesheet" href="{{base_url}}/css/forms.css">
        <link rel="stylesheet" href="{{base_url}}/css/grid.css">

        <script>
            const formatProvider   = '{{ApiFormatProvider}}';
            const renderingManager = '{{ApiRenderingManager}}';
            const linksProvider    = '{{ApiLinkProvider}}';

            class FieldsManager {

                constructor() {

                    this.data = {};
                    
                    this.cta = document.getElementById('cta');

                    this.submitConditions = [];

                    this.marketplaceLink = null;

                    this.initDataShow();

                    this.initLanding();

                    this.submit = this.submit.bind( this );

                    document.getElementById('submit').addEventListener( 'click', this.submit );
                }


                setSubmitCondition( callback ) {

                    this.submitConditions.push( callback );
                }


                initDataShow() {
                    this.dataShow = document.getElementById('data_show');
                    this.dataShow.style.display = 'none';
                }


                initLanding() {

                    this.landingUrl    = document.getElementById('landing_url');
                    this.landingLoader = document.getElementById('landing_loader');

                    //this.landingSubmit = document.getElementById('landing_submit');

                    this.checkLanding = this.checkLanding.bind(this);

                    // this.landingSubmit.addEventListener('click', this.checkLanding );      
                    this.landingUrl.addEventListener('change', this.checkLanding );                    
                }


                async checkLanding( evt ) {

                    this.amazonLink         = new AmazonLink( this.landingUrl.value );
                    this.ebayLink           = new EbayLink( this.landingUrl.value );
                    this.awinLink           = new AwinLink( this.landingUrl.value );
                    this.tradeTrackerLink   = new TradeTrackerLink( this.landingUrl.value );
                    this.partnerizeLink     = new PartnerizeLink( this.landingUrl.value );
                    this.primeVideoLink     = new PrimeVideoLink( this.landingUrl.value );
                    this.impactLink         = new ImpactLink( this.landingUrl.value , linksProvider );

                    if( this.amazonLink.isValid() ) { this.show('amazon'); return; }
                    if( this.ebayLink.isValid()   ) { this.show('ebay');   return; }
                    //if( this.awinLink.isValid()  ) { this.show('awin');   return; }

                    this.marketplaceLink = this.amazonLink.isLink()        ? this.amazonLink         : this.marketplaceLink; 
                    this.marketplaceLink = this.ebayLink.isLink()          ? this.ebayLink           : this.marketplaceLink;
                    this.marketplaceLink = this.awinLink.isLink()          ? this.awinLink           : this.marketplaceLink;
                    this.marketplaceLink = this.tradeTrackerLink.isLink()  ? this.tradeTrackerLink   : this.marketplaceLink;
                    this.marketplaceLink = this.partnerizeLink.isLink()    ? this.partnerizeLink     : this.marketplaceLink;
                    this.marketplaceLink = this.primeVideoLink.isLink()    ? this.primeVideoLink     : this.marketplaceLink;
                    this.marketplaceLink = await this.impactLink.isLink()  ? this.impactLink         : this.marketplaceLink;
                    
                    if( this.marketplaceLink != null ) {

                        this.showGeneric();

                        return ;
                    }
                    
                    tinyMCEPopup.alert("Inserire un link valido"); 

                    return;
                }


                async showGeneric( platformName ) {

                    let codeLabel = document.getElementById('mktplace_code_label');
                    let code      = document.getElementById('mktplace_code');
                    let price     = document.getElementById('price');
                    let link      = document.getElementById('link');

                    codeLabel.textContent = this.marketplaceLink.platform == 'Awin' ? `Link ad un prodotto awin` : `Il link non rimanda ad un prodotto`;
                    code.textContent      = this.data.title;
                    price.innerHTML       = ``;

                    link.value            = this.marketplaceLink.addTag('booBLZTRKood');

                    this.link             = link.value;
                    this.program          = this.marketplaceLink.platform;

                    this.dataShow.style.display = 'block';
                }
                
                async show( platformName ) {

                    let platform = {

                        'amazon' : {
                            'link'    : this.amazonLink,
                            'apiCall' : `${renderingManager}amazon_product_api/get_item/${this.amazonLink.asin}`,
                            'program' : 'Amazon',
                            'mktCode' : 'ASIN',
                            'code'    : this.amazonLink.asin

                        },
                        'ebay' : {
                            'link'    : this.ebayLink,
                            'apiCall' : `${renderingManager}ebay_browse_api/get_item/${this.ebayLink.itm}`,
                            'program' : 'eBay',
                            'mktCode' : 'ITM',
                            'code'    : this.ebayLink.itm
                        }

                    }[ platformName ];

                    this.showLoader();

                    this.data = await platform.link.getData( platform.apiCall+'?a' );

                    this.program  = platform.program;
                    this.mkt_code = platform.mktCode;
                    this.code     = platform.code;
                    this.price    = this.data.price;
                    this.link     = this.data.link;

                    this.showData();

                    this.loaderFound();
                }

               
                showLoader() {
                    this.landingLoader.innerHTML = "<span style=\"bigger\">⏱🤔 cerco...</span>";                    
                }

                loaderFound() {
                    this.landingLoader.innerHTML = "<span style=\"bigger\">🤓👍 trovato!</span>";                    
                }

                showData() {

                    let codeLabel = document.getElementById('mktplace_code_label');
                    let code      = document.getElementById('mktplace_code');
                    let price     = document.getElementById('price');
                    let link      = document.getElementById('link');


                    codeLabel.textContent = `${this.program} ${this.mkt_code} : ${this.code}`;
                    code.textContent      = this.data.title;
                    price.innerHTML     = `<strong>&euro; ${this.price}</strong>`;
                    link.value            = this.link;

                    this.dataShow.style.display = 'block';
                }

                submit( event ) {

                    let content = this.cta.value; // tinymce.activeEditor.selection.getContent();

                    /// caso di uscita
                    if ( content.trim()  == '') { 

                        tinyMCEPopup.alert("Inserire un testo (CTA)" );
                        return;
                    }

                    /// verifica che non ci siano condizioni di errore
                    if( this.verifyErrors() ) return;
                
                    /// inserisce lo shortcode
                    let shortcode = `[parse_button link="${this.link}" program="${this.program}" format_id="{{formatId}}"]${content}[/parse_button]`;

                    tinyMCE.activeEditor.execCommand( 'mceInsertContent', 0, shortcode );

                    tinyMCEPopup.close();
                }
                

                /**
                 * verifica che non ci siano condizioni di errore
                 * 
                 * @return {boolean} true se ci sono errori, false altrimenti
                 */
                verifyErrors() {
                    
                    let errors = this.submitConditions.filter( item => !item.condition() );

                    if( errors.length ) {
                        tinyMCEPopup.alert( errors.shift().message );
                        return true;
                    }

                    return false;
                }
            }


            window.addEventListener( 'DOMContentLoaded', function() { 
                                
                const fieldsManager = new FieldsManager();                

                const preview = new LinkPreview('#preview', document.querySelector( '#link' ) );

                /*
                fieldsManager.setSubmitCondition( { 
                    condition : () => preview.clicked,
                    message   : 'Cliccare prima sul pulsante "preview"'
                });
                */

            }.bind(this));

        </script>
    </head>

    <body onload="tinyMCEPopup.executeOnLoad('init();')">
        
        <div class="landing_url_container">
            <div class="col1">
                <legend for="landing_url">Inserisci la URL della landing page dell'offerta e premi invio</legend>
            </div>
            <div class="col2"></div>
            <div class="col1">                
                <input type="text" id="landing_url">
            </div>    
            <div class="col2">
                <span id="landing_loader"></span>
            </div>
            <!--div class="col2">
                <button id="landing_submit">Elabora</button>
            </div-->    
        </div>

        <input type="hidden" id="link">

        <div id="data_show">

            <legend>Inserisci il testo (CTA) del bottone</legend>
            <input type="text" id="cta">

            <div class="landing_url_container" style="margin:30px">
                <div class="col1">
                    <span id="mktplace_code_label"></span>
                </div>
                <div class="col2">Prezzo</div>
                <div class="col1">          
                    <span id="mktplace_code"></span>
                </div>    
                <div class="col2">
                    <span id="price"></span>
                </div>    
            </div>

            <div id="preview" class="btn-container">
                <a class="btn" href="javascript:void(0)">Preview</a>
                <small>Abilitare le popup sul sito per visualizzare la preview</small>
            </div>

            <input type="button" id="submit" value="Inserisci"/>   

        </div>
        
    
        <!--button>Usa una chiave di ricerca ( sconsigliato )</button>

            <span id="container_non_custom">

                <legend>keyword</legend>
                <input type="text" id="keyword">

                <legend>Min Price (Inserire un valore intero senza valuta, se omesso il default è 20 euro)</legend>
                <input type="text" id="min_price" placeholder="20">

            </span>

        </div--> 
    
        
        
    </body>
</html>