
import { Command } from '@ckeditor/ckeditor5-core';
import { isImage } from '@ckeditor/ckeditor5-image/src/image/utils';
import * as QMSCKEditorConstant from '../common/qmsCKEditorConstant';
import * as QMSCKEditorService from '../common/qmsCKEditorService';
import { IMAGEMAP_ATTRIBUTES, IMAGEMAP_COMMANDS, parsePixelToFloat, findFirstMapNode } from './utils';
import  { getSelectedImageWidget } from '@ckeditor/ckeditor5-image/src/image/utils';
import { trimStart } from '../common/qmsCKEditorUtil';

export default class ImageMapDialogCommand extends Command {

	refresh() {
		const element = this.editor.model.document.selection.getSelectedElement();
		this.isEnabled = isImage(element);
	}

	execute() {
		const editor = this.editor;
		const model = editor.model;
		const view = editor.editing.view;
		const selectedElement = model.document.selection.getSelectedElement();

		const mapName = selectedElement.getAttribute(IMAGEMAP_ATTRIBUTES.IMAGE_USE_MAP);
		let originalImageSrc = selectedElement.getAttribute(IMAGEMAP_ATTRIBUTES.IMAGE_SRC);
		if(selectedElement.hasAttribute(IMAGEMAP_ATTRIBUTES.IMAGE_SAVED_SRC) && selectedElement.getAttribute(IMAGEMAP_ATTRIBUTES.IMAGE_SAVED_SRC)){
			originalImageSrc = selectedElement.getAttribute(IMAGEMAP_ATTRIBUTES.IMAGE_SAVED_SRC);
		}

		const data = {'imageUrl': originalImageSrc, 'areas': [], imageWidth: null, imageHeight: null};
		const imageWidget = getSelectedImageWidget( view.document.selection);
		const widgetResizePlugin = editor.plugins.get('WidgetResize');
        const resizer = widgetResizePlugin.getResizerByViewElement( imageWidget );

		if(resizer){
			const resizerWrapper = resizer._viewResizerWrapper;
			data.imageWidth = parsePixelToFloat(resizerWrapper.getStyle('width', 0));
			data.imageHeight = parsePixelToFloat(resizerWrapper.getStyle('height', 0));
		}

		if(!!mapName){
			const range = model.createRangeIn(model.document.getRoot());
			const existingMapElement = findFirstMapNode(trimStart(mapName, '#'), range);
			if(existingMapElement){
				data.areas = JSON.parse(existingMapElement.getAttribute(IMAGEMAP_ATTRIBUTES.MAP_AREAS) || []);
			}
		}

		QMSCKEditorService.imageMapNotify(data);
        window[QMSCKEditorConstant.QMSCK_IMAGEMAP_IS_PROCESSING] = false;
        window.addEventListener(QMSCKEditorConstant.QMSCK_IMAGEMAP_PLUGIN_RESP, (evt) => {
            if (window[QMSCKEditorConstant.QMSCK_IMAGEMAP_IS_PROCESSING]) {
                return;
            }
            window[QMSCKEditorConstant.QMSCK_IMAGEMAP_IS_PROCESSING] = true;
			const options = evt.detail;
            editor.commands.get(IMAGEMAP_COMMANDS.IMAGEMAP).execute(options);
        }, { once: true});
	}
}
