import Clipboard from "@ckeditor/ckeditor5-clipboard/src/clipboard";
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import HtmlDataProcessor from "@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor";
import plainTextToHtml from "@ckeditor/ckeditor5-clipboard/src/utils/plaintexttohtml";

/**
 * Override what is done in clipboard paste if config.aaForcePlainTextPaste is defined
 */
export default class PasteAsPlainText extends Plugin {
    /**
     * @inheritDoc
     */
    static get requires() {
        return [Clipboard,];
    }

    /**
     * @inheritDoc
     */
    static get pluginName() {
        return 'PasteAsPlainText';
    }

    init() {
        const editor = this.editor;
        const clipboardPlugin = editor.plugins.get('ClipboardPipeline');
        if (editor.config.get('aaForcePlainTextPaste')) {
            const view = editor.editing.view;
            const viewDocument = view.document;

            // Data processor used to convert pasted HTML to a view structure.
            this._htmlDataProcessor = new HtmlDataProcessor(viewDocument);

            this.listenTo(viewDocument, 'clipboardInput', (evt, data) => {
                if (editor.isReadOnly) {
                    return;
                }

                const dataTransfer = data.dataTransfer;

                let content = plainTextToHtml(dataTransfer.getData('text/plain'));

                // keep default clipboard plugin
                content = editor.data.htmlProcessor.toView(content);
                clipboardPlugin.fire('inputTransformation', {content, dataTransfer});

                view.scrollToTheSelection();
                evt.stop();
            }, {priority: 'highest'});
        }
    }
}
