import { Plugin } from 'ckeditor5/src/core';
import ResizeMediaCommand from './resizemediacommand';

export default class MediaResizeEditing extends Plugin {
	static get pluginName() {
		return 'MediaResizeEditing';
	}

	constructor( editor ) {
		super( editor );

		editor.config.define( 'media', {
			resizeUnit: '%',
			resizeOptions: [ {
				name: 'resizeMedia:original',
				value: null,
				icon: 'original'
			},
			{
				name: 'resizeMedia:25',
				value: '25',
				icon: 'small'
			},
			{
				name: 'resizeMedia:50',
				value: '50',
				icon: 'medium'
			},
			{
				name: 'resizeMedia:75',
				value: '75',
				icon: 'large'
			} ]
		} );
	}

	init() {
		const editor = this.editor;
		const resizeMediaCommand = new ResizeMediaCommand( editor );

		this._registerSchema();
		this._registerConverters();

		editor.commands.add( 'resizeMedia', resizeMediaCommand );
		editor.commands.add( 'mediaResize', resizeMediaCommand );
	}

	_registerSchema() {
		this.editor.model.schema.extend( 'media', { allowAttributes: 'width' } );
		this.editor.model.schema.setAttributeProperties( 'width', {
			isFormatting: true
		} );
	}

	_registerConverters() {
		const editor = this.editor;

		// Dedicated converter to propagate media's attribute to the media tag.
		editor.conversion.for( 'downcast' ).add( dispatcher =>
			dispatcher.on( 'attribute:width:media', ( evt, data, conversionApi ) => {
				if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
					return;
				}

				const viewWriter = conversionApi.writer;
				const figure = conversionApi.mapper.toViewElement( data.item );

				if ( data.attributeNewValue !== null ) {
					viewWriter.setStyle( 'width', data.attributeNewValue, figure );
					viewWriter.addClass( 'media_resized', figure );
				} else {
					viewWriter.removeStyle( 'width', figure );
					viewWriter.removeClass( 'media_resized', figure );
				}
			} )
		);

		editor.conversion.for( 'upcast' )
			.attributeToAttribute( {
				view: {
					name: 'figure',
					styles: {
						width: /.+/
					}
				},
				model: {
					key: 'width',
					value: viewElement => viewElement.getStyle( 'width' )
				}
			} );
	}
}
