
import React, { useMemo } from 'react';
import CKEditor, { CKEditorProps } from './CKEditor';
import { useUploadController } from 'react-admin-base';

class UploadAdapter {
    loader: any;
    Upload: any;
    aborts: AbortController | null;
    
  constructor( loader, Upload ) {
      this.loader = loader;
      this.Upload = Upload;
  }

  async upload() {
      this.aborts =  new AbortController();

      const file = await this.loader.file;

      const dosya = await this.Upload.uploader(file.name, file, file.type, this.aborts.signal, (percent) => {
          this.loader.uploadTotal = file.size;
          this.loader.uploaded = file.size * percent;
      });

      return {
          default: dosya.access_url
      };
  }

  abort() {
      if (this.aborts) {
          this.aborts.abort();
          this.aborts = null;
      }
  }
}

export default function CKEditorWithUpload(props: CKEditorProps) {
  const uploadController = useUploadController();

  const config = useMemo(() => {
    const MyCustomUploadAdapterPlugin = function ( editor ) {
        editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => new UploadAdapter(loader, uploadController);
    };

    return {
      extraPlugins: [MyCustomUploadAdapterPlugin],
      image: {
          styles: [
              'alignLeft', 'alignCenter', 'alignRight'
          ],
          toolbar: [
              'imageStyle:alignLeft', 'imageStyle:alignCenter', 'imageStyle:alignRight',
              '|',
              'imageResize',
              '|',
              'imageTextAlternative'
          ]
      }
    };
  }, [uploadController]);

  return <CKEditor {...props} config={config} />;
}
