<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Inserisci una Promo Card</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/ComboSearch.js?{{renewcache}}"></script>
        <link rel="stylesheet" href="{{base_url}}/css/forms.css">

        <script>

            class FieldsManager extends Form {

                initFields() {
                    
                    this.addDropdown( 'subject', `${this.apiBase}subjects/`, '#subject', 'id' );
                
                    this.fields.table = new DropDown( `${this.apiBase}promos/subject_id/{{domain}}`, '#tables',  'id', 'title' );

                    this.combo = new ComboSearch( this.fields.table.container , this.addPreviewLink.bind(this) );
                    
                    this.fields.table.populate();

                    this.fields.table.dependsOn( 'subject_id', this.fields.subject );
                }

                addPreviewLink() {

                    let table_select = this.fields.table.container

                    let payload = table_select.selectedOptions[0].dataset.payload;

                    if( typeof payload == 'undefined') return;

                    let json = JSON.parse(decodeURIComponent( payload ));
                    
                    table_select.link = json.link;
                }

                submit( event ) {
                    
                    let table_id = this.fields.table.value();

                    /// casi di uscita                    
                    if( table_id  == '') { tinyMCEPopup.alert( "Selezionare una promo" );  return; }
                    
                    if( this.verifyErrors() ) return ;

                    /// adesso invece c'è questo
                    let shortcode = `[affiliate_promo promo_id="${table_id}"]`;

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

                    tinyMCEPopup.close();
                }

                enableCreateTable() {
                    
                    let createTableBtn = document.querySelector( '#create-table a' );

                    createTableBtn.addEventListener('click', event => {

                        let win = window.open( '{{FormatProvider}}', 'new', 'popup=true' );  

                        if ( win == null ) {
                            alert('Attenzione, per aprire la finestra occorre abilitare le popup nel browser per questo sito.');
                        }
                    } );
                }

                /**
                 * 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(`{{ApiFormatProvider}}`);

                const tablesElement = document.querySelector( '#tables' );

                /// prende il link della tabella selezionata
                const preview = new LinkPreview('#preview', tablesElement, 'link' );

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

                fieldManager.enableCreateTable();

            }.bind(this));

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

        <legend>Seleziona una promo</legend>
        <select name="table" id="tables"><option value="">-- scegli --</option></select>

        <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" />

    </body>
</html>