import { Plugin } from 'ckeditor5/src/core';
import { WidgetResize } from 'ckeditor5/src/widget';
import MediaLoadObserver from '../media/medialoadobserver';

export default class MediaResizeHandles extends Plugin {
	static get requires() {
		return [ WidgetResize ];
	}

	static get pluginName() {
		return 'MediaResizeHandles';
	}

	init() {
		const command = this.editor.commands.get('resizeMedia');
		this.bind('isEnabled').to(command);

		this._setupResizerCreator();
	}

	_setupResizerCreator() {

		const editor = this.editor;
		const editingView = editor.editing.view;

		editingView.addObserver( MediaLoadObserver );
		this.listenTo( editingView.document, 'mediaLoaded', ( evt, domEvent ) => {
			if ( !domEvent.target.matches( 'figure.media.ck-widget > media, figure.media.ck-widget > a > media' ) ) {
				return;
			}

			const mediaView = editor.editing.view.domConverter.domToView( domEvent.target );
			const widgetView = mediaView.findAncestor( 'figure' );
			let resizer = this.editor.plugins.get( WidgetResize ).getResizerByViewElement( widgetView );

			if ( resizer ) {
				resizer.redraw();

				return;
			}


			const mapper = editor.editing.mapper;
			const mediaModel = mapper.toModelElement( widgetView );

			resizer = editor.plugins
				.get( WidgetResize )
				.attachTo( {
					unit: editor.config.get( 'media.resizeUnit' ),

					modelElement: mediaModel,
					viewElement: widgetView,
					editor,
					getHandleHost( domWidgetElement ) {
						return domWidgetElement.querySelector( 'media' );
					},
					getResizeHost( domWidgetElement ) {
						return domWidgetElement;
					},
					isCentered() {
						const mediaStyle = mediaModel.getAttribute( 'mediaStyle' );

						return !mediaStyle || mediaStyle === 'full' || mediaStyle === 'alignCenter';
					},

					onCommit( newValue ) {
						editor.execute( 'resizeMedia', { width: newValue } );
					}
				} );

			resizer.on( 'updateSize', () => {
				if ( !widgetView.hasClass( 'media_resized' ) ) {
					editingView.change( writer => {
						writer.addClass( 'media_resized', widgetView );
					} );
				}
			} );

			resizer.bind( 'isEnabled' ).to( this );
		} );
	}
}
