<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Inserisci una card Awin</title>
    <script type="text/javascript" src="/wp/wp-includes/js/tinymce/tiny_mce_popup.js"></script>
    <script type="text/javascript" src="{{base_url}}/lib/Form.js?{{renewcache}}"></script>
    <script type="text/javascript" src="{{base_url}}/lib/LinkPreview.js?{{renewcache}}"></script>    
    <script type="text/javascript" src="{{base_url}}/lib/ComboSearchLive.js?{{renewcache}}"></script>
    <link rel="stylesheet" href="{{base_url}}/css/forms.css">

    <script>

        class FieldsManager extends Form {

            initFields() {
                let apiCall = `${this.apiBase}v2/awin/merchants/merchantId/products`;
                this.addDropdown( 'merchants', `${this.apiBase}v2/awin/merchants`, '#merchants', 'merchantId', 'merchantName' );
                this.addDropdown( 'products', '', '#products', 'id', 'value' );

                this.combo = new ComboSearchLive(this.fields.products, apiCall);
                
                this.combo.dependsOn('merchantId', this.fields.merchants , true);
            }
            
            submit( event ) {
                
                let link  = this.fields.products.payload();

                /// casi di uscita

                /// verifica che non ci siano condizioni di errore
                if( this.verifyErrors() ) return;

                let shortcode = `[parse_card link="${link.url}" program="awin" format_id="{{formatId-awin}}"]${link.value}[/parse_card]`;

                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 fieldManager = new FieldsManager(`{{ApiLinkProvider}}`);

        }.bind(this));

    </script>
</head>
<body onload="tinyMCEPopup.executeOnLoad('init();')">
    
    
    <legend>Seleziona il Merchant</legend>
    <select name="merchants" id="merchants"><option value="">-- scegli --</option></select>

    <legend>Seleziona il Prodotto</legend>
    <select name="products" id="products"><option value="">-- scegli --</option></select>           

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