<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Inserisci il link per il bottone</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>    
    <link rel="stylesheet" href="{{base_url}}/css/forms.css">

    <script>

        class FieldsManager extends Form {

            initFields() {
                
                this.addDropdown( 'subject', `${this.apiBase}subjects/`,           '#subject', 'id' );
                this.addDropdown( 'program', `${this.apiBase}programs/subject_id`, '#program', 'id' );
                this.addDropdown( 'link',    `${this.apiBase}links/program_id/{{domain}}/button`, '#link', 'link', 'title' );

                this.fields.program.dependsOn( 'subject_id', this.fields.subject );
                this.fields.link.dependsOn(    'program_id', this.fields.program );
            }
            
            submit( event ) {
                
                let data       = this.fields.link.payload();
                let url        = this.fields.link.value();                
                let program_id = this.fields.program.value();

                let contentElement = document.getElementById('content');

                /// casi di uscita
                if (contentElement.value.trim()  == '') { tinyMCE.alert("Inserire un testo"); return; }
                if (link  == '')                        { tinyMCE.alert("Selezionare un link");  return; }

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

                let content = contentElement.value;

                let shortcode = `[affiliate_button link_id="${data.id}" format_id="{{format_id}}"]${content}[/affiliate_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 fieldManager = new FieldsManager(`{{ApiLinkProvider}}`);

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

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

        }.bind(this));

    </script>
</head>
<body onload="tinyMCEPopup.executeOnLoad('init();')">
    
    
    <legend>Inserisci la CTA</legend>
    <input type="text" id="content" name="content" value=""/>
    
    <legend>Seleziona l'argomento</legend>                        
    <select name="subject" id="subject"><option value="">-- scegli --</option></select>

    <legend>Seleziona il programma</legend>           
    <select name="program" id="program"><option value="">-- scegli --</option></select>

    <legend>Seleziona il link</legend>           
    <select name="link" id="link"><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>