<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Inserisci il link</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>

            let content = tinyMCE.activeEditor.selection.getContent();

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

                tinyMCEPopup.alert("Selezionare un testo ", () => {

                    tinyMCEPopup.close();
                }); 
            }

            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}}/link`, '#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 content = tinymce.activeEditor.selection.getContent();

                    /// casi di uscita                    
                    if( url  == '') { tinyMCE.alert( "Selezionare un link" );  return; }

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

                    /// a tendere lo shortcode dovrebbe essere questo commentato
                    // let shortcode = `[affiliate_link link_id="${link}" format="link"]${content}[/affiliate_link]`;
                    
                    /// adesso invece c'è questo
                    let shortcode = `[affiliate_link link_id="${data.id}"]${content}[/affiliate_link]`;

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