import React, { Component } from 'react';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

const TextEditor = ({data, setData}) => {

    function uploadAdapter(loader) {
        return {
            upload: () => {
                return new Promise(async (resolve, reject) => {
                    try {
                    const file = await loader.file;
                    const buff = await file.arrayBuffer()
                    const bytesArray = new Uint8Array(buff)
                    const bytesString = btoa(String.fromCharCode.apply(null, bytesArray))
                    resolve({
                        default: `data:image/jpg;base64, ${bytesString}`
                    });
                    } catch (error) {
                        reject("Hello");
                    }
              });
            }
        }
    }

    function uploadPlugin(editor) {
        editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
            return uploadAdapter(loader);
        };
    }

    return (
        <div className="App">
            <h2>Редактор статьи</h2>
            <CKEditor
                editor={ ClassicEditor }
                data={data}
                config = {{
                    extraPlugins: [uploadPlugin],
                    mediaEmbed: {previewsInData: true }
                }}
                onReady={ editor => {
                    // You can store the "editor" and use when it is needed.
                    console.log( 'Editor is ready to use!', editor );
                } }
                onChange={ ( event, editor ) => {
                    setData(editor.getData())
                }}
                onBlur={ ( event, editor ) => {}}
                onFocus={ ( event, editor ) => {}}
            />
        </div>
    );
}

export default TextEditor