import React from 'react'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import { Grid, InputLabel } from '@material-ui/core'
import { apiUploadFile } from 'app/apis/Functions/Upload.js'

function CKedittorComponents(props) {
    const { title, desc, setDesc, id } = props
    function uploadPlugin(editor) {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            return uploadAdapter(loader)
        }
    }
    function uploadAdapter(loader) {
        return {
            upload: () => {
                return new Promise((resolve, reject) => {
                    const body = new FormData()
                    loader.file.then((file) => {
                        body.append('files', file)
                        apiUploadFile(body)
                            .then((res) => {
                                console.log(res.data.data[0].url)
                                resolve({
                                    default: res.data.data[0].url,
                                })
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                })
            },
        }
    }
    return (
        <>
            {
                <Grid item xs={12} sm={12}>
                    <InputLabel style={{ paddingBottom: '5px' }}>
                        {title}
                    </InputLabel>

                    <CKEditor
                        config={{
                            extraPlugins: [uploadPlugin],
                        }}
                        editor={ClassicEditor}
                        data={desc}
                        onReady={(editor) => {
                            id && editor.setData(desc)
                            // You can store the "editor" and use when it is needed.
                        }}
                        onChange={(event, editor) => {
                            const content = editor.getData()
                            setDesc(content)
                        }}
                        onBlur={(event, editor) => {}}
                        onFocus={(event, editor) => {}}
                    />
                </Grid>
            }
        </>
    )
}

export default CKedittorComponents