import {
  blobToFile,
  getReadableSignedUrl,
  signedUpload,
} from 'src/utils/filesUtils';

let tempVideoUpload: any = null;

export const addVideoEditorPlugin = (editorManager: any, t: any) =>
  editorManager.PluginManager.add('videoupload', (editor: any) => {
    const openDialog = () => {
      const controller = new AbortController();

      const dialogConfig = {
        title: t('INSERT_VIDEO'),
        body: {
          type: 'panel',
          items: [
            {
              type: 'dropzone',
              name: 'ladropza',
            },
          ],
        },
        buttons: [],
        onClose() {
          controller.abort();
        },
        async onChange(api: any) {
          const video = tempVideoUpload;
          if (video) {
            // this re-renders the dialog
            api.redial({
              ...dialogConfig,
              body: {
                type: 'panel',
                items: [
                  {
                    type: 'alertbanner',
                    level: 'info',
                    text: t('LOADING'),
                    icon: 'checkmark',
                  },
                ],
              },
            });

            const signedURL = await signedUpload(
              video[0],
              false,
              true,
              controller.signal,
            );
            const readableSignedURL = await getReadableSignedUrl(signedURL);
            editor.insertContent(
              `<video controls="controls"><source src="${readableSignedURL}"></video>`,
            );
            tempVideoUpload = null;
            api.close();
          }
        },
      };

      editor.windowManager.open(dialogConfig);
      // can't modify dialog with tinymce API so I did it manually
      const dropZone = document.getElementsByClassName('tox-dropzone')[0];
      dropZone.children[0].textContent = t('DROP_VIDEO');
      dropZone.children[1].childNodes[0].textContent = t('BROWSE_VIDEO');
      (dropZone.children[1].childNodes[1] as HTMLInputElement).accept =
        'video/*';
      (dropZone.children[1].childNodes[1] as HTMLInputElement).onchange =
        ev => {
          tempVideoUpload = (ev.target as any).files;
        };
      (dropZone as HTMLInputElement).ondrop = ev => {
        tempVideoUpload = ev.dataTransfer?.files;
      };
    };
    // Add a button that opens a window
    editor.ui.registry.addButton('videoupload', {
      tooltip: t('INSERT_VIDEO'),
      icon: 'upload',
      onAction: openDialog,
    });
  });

export const imagesUploadHandler = async (
  blobInfo: { blob: () => Blob; filename: () => string },
  progress: (p: number) => void,
  errorMsg: string,
) => {
  try {
    progress(10);
    let blob = blobInfo.blob();
    // when using the toolbar button, blob is a File
    // when dragging or pasting, blob is a Blob
    if (!(blob instanceof File)) {
      blob = blobToFile(blob, blobInfo.filename());
    }
    progress(70);
    const signedURL = await signedUpload(blob as File, false, false);
    const readableSignedURL = await getReadableSignedUrl(signedURL);
    return readableSignedURL;
  } catch (error) {
    throw Object.assign(new Error(errorMsg), { remove: true });
  }
};
