 

import { Command } from '@ckeditor/ckeditor5-core';
import { findAttributeRange } from '@ckeditor/ckeditor5-typing';
import { first } from '@ckeditor/ckeditor5-utils';
import { isImageAllowed } from './utils';
import { TOOLTIP_COMMANDS, HTML_ATTRIBUTE, HTML_CLASS, TOOLTIP_ATTRIBUTE, TOOLTIP_CUSTOM_PROPERTY } from './utils';

export default class RemoveTooltipCommand 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 image 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.isEnabled = model.schema.checkAttribute(selectedElement, TOOLTIP_ATTRIBUTE);
		} else {
			this.isEnabled = model.schema.checkAttributeInSelection(doc.selection, TOOLTIP_ATTRIBUTE);
		}
	}
 
	execute() {
		const editor = this.editor;
		const model = editor.model;
		const selection = model.document.selection;
 
		model.change(writer => {
			// Get ranges to unlink.
			const rangesToUnlink = selection.isCollapsed ?
				[findAttributeRange(
					selection.getFirstPosition(),
					TOOLTIP_ATTRIBUTE,
					selection.getAttribute(TOOLTIP_ATTRIBUTE),
					model
				)] :
				model.schema.getValidRanges(selection.getRanges(), TOOLTIP_ATTRIBUTE);

			// Remove `qmsTooltip` attribute from specified ranges.
			for (const range of rangesToUnlink) {
				writer.removeAttribute(TOOLTIP_ATTRIBUTE, range);
			}
		});
	}
}
