import { Command } from '@ckeditor/ckeditor5-core';
import { findAttributeRange } from '@ckeditor/ckeditor5-typing';
import { first } from '@ckeditor/ckeditor5-utils';
import * as QMSCKEditorConstant from '../common/qmsCKEditorConstant';
import * as QMSCKEditorService from '../common/qmsCKEditorService';
import { isImageAllowed, TOOLTIP_COMMANDS, TOOLTIP_ATTRIBUTE } from './utils';

export default class TooltipDialogCommand extends Command {
  
	refresh() {
		const model = this.editor.model;
		const doc = model.document;
		const selectedElement = first(doc.selection.getSelectedBlocks());
		// A check for the `LinkImage` plugin. If the selection contains an element, get values from the element.
		// Currently the selection reads attributes from text nodes only. See #7429 and #7465.
		if (isImageAllowed(selectedElement, model.schema)) {
            this.value = selectedElement.getAttribute(TOOLTIP_ATTRIBUTE);
			this.isEnabled = model.schema.checkAttribute(selectedElement, TOOLTIP_ATTRIBUTE);
		} else {
            this.value = doc.selection.getAttribute(TOOLTIP_ATTRIBUTE);
			this.isEnabled = model.schema.checkAttributeInSelection(doc.selection, TOOLTIP_ATTRIBUTE);
		}
	}
 
	execute() {
        const editor = this.editor;
		const model = editor.model;
		const selection = model.document.selection;
        const tooltip = { text: '', content: '' };
        if(selection.isCollapsed){
            if(selection.hasAttribute(TOOLTIP_ATTRIBUTE)){
				const linkRange = findAttributeRange(selection.getFirstPosition(), TOOLTIP_ATTRIBUTE, selection.getAttribute(TOOLTIP_ATTRIBUTE), model);
				for (const node of linkRange.getItems()) {
					if ((node.is('text') || node.is('textProxy')) && node.hasAttribute(TOOLTIP_ATTRIBUTE)) {
						tooltip.text = node.data;
                    	tooltip.content = node.getAttribute(TOOLTIP_ATTRIBUTE);
						break;
					}
				}
			}
        }
        else
        {
            const ranges = selection.getFirstRange();
            if(ranges)
            {
                for (const item of ranges.getItems()) {
                    if (item.data) {
                        tooltip.text = tooltip.text + item.data;
                    }
                }
            }
        }

        QMSCKEditorService.tooltipNotify(tooltip);
        window[QMSCKEditorConstant.QMSCK_TOOLTIP_IS_PROCESSING] = false;
 
		window.addEventListener(QMSCKEditorConstant.QMSCK_TOOLTIP_PLUGIN_RESP, function (evt) {
            if (window[QMSCKEditorConstant.QMSCK_TOOLTIP_IS_PROCESSING]) { 
                return; 
            }
            const options = evt.detail;
            editor.commands.get(TOOLTIP_COMMANDS.TOOLTIP).execute(options);
            window[QMSCKEditorConstant.QMSCK_TOOLTIP_IS_PROCESSING] = true;            
		}, { once: true }); 
	}
}

