import { Command } from '@ckeditor/ckeditor5-core';
import * as QMSCKEditorConstant from '../common/qmsCKEditorConstant';
import * as QMSCKEditorService from '../common/qmsCKEditorService';

export default class LoadTemplateDialogCommand extends Command {
    constructor( editor ) {
		super( editor );
	}
    
	execute() {
    const editor = this.editor;
    QMSCKEditorService.loadTemplateNotify(null, editor.id);
    window.addEventListener(QMSCKEditorConstant.QMSCK_LOAD_TEMPLATE_PLUGIN_RESP, function (evt) {
        if(evt.detail && evt.detail.isReplace)
        {
            editor.setData(evt.detail.content);
        }
        else
        {
            if(evt.detail && evt.detail.content && evt.detail.content !== '')
            {
                let content = evt.detail.content;
                if(!editor.model.document.selection.focus.isAtStart) // cursor in start of the text row
                {
                    content = '<p>&nbsp;</p>'+ evt.detail.content;
                }
                content += '<p>&nbsp;</p>';              
                const viewFragment = editor.data.processor.toView( content );
    
                const modelFragment = editor.data.toModel( viewFragment );
                editor.model.insertContent( modelFragment );
            }
        }
    }, { once: true });
	}
}

