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

export default class FlowchartDialogCommand extends Command {
	execute() {
    const editor = this.editor;
    const isFlowchart = this.isFlowchartImage(editor.editing.view.document.selection.getSelectedElement(), editor.plugins.get('Image'))
    if (isFlowchart) {
      const parentElement = editor.editing.view.document.selection.getSelectedElement();
      const altAtr = parentElement.getChild(0).getAttribute('alt');
      const arrAtr = altAtr.split("#");
      const id = arrAtr[1];
      QMSCKEditorService.flowchartNotify(id);
    }
    else {
      QMSCKEditorService.flowchartNotify('');
    }
    window.addEventListener(QMSCKEditorConstant.QMSCK_FLOWCHART_PLUGIN_RESP, function (evt) {
      editor.model.change( writer => {
          const imageElement = writer.createElement( 'image', {
              src: evt.detail.values,
              alt: evt.detail.key
          } );
          // Insert the image in the current selection location.
          editor.model.insertContent( imageElement, editor.model.document.selection );
      });
    }, { once: true });
	}

  isFlowchartImage( element, image ) {
    const isImage = element && image.isImageWidget( element );

    if ( !isImage ) {
      return false;
    }

    const altAtr = element.getChild(0).getAttribute('alt')
    if (altAtr && altAtr.includes(QMSCKEditorConstant.QMSCK_FLOWCHART)) {
      return true;
    }
    else {
      return false;
    }
  }
}

