import { Command } from 'ckeditor5/src/core';
import { isMedia } from '../media/utils';

export default class ResizeMediaCommand extends Command {
	refresh() {
		const element = this.editor.model.document.selection.getSelectedElement();

		this.isEnabled = isMedia( element );

		if ( !element || !element.hasAttribute( 'width' ) ) {
			this.value = null;
		} else {
			this.value = {
				width: element.getAttribute( 'width' ),
				height: null
			};
		}
	}

	execute( options ) {
		const model = this.editor.model;
		const mediaElement = model.document.selection.getSelectedElement();

		this.value = {
			width: options.width,
			height: null
		};

		if ( mediaElement ) {
			model.change( writer => {
				writer.setAttribute( 'width', options.width, mediaElement );
			} );
		}
	}
}
