import { useCallback } from 'react';
import { useSetAtom } from 'jotai';
import { Room } from 'matrix-js-sdk';
import {
  roomIdToUploadItemsAtomFamily,
  TUploadItem,
} from '../state/room/roomInputDrafts';
import { encryptFile } from '../utils/matrix';
import { safeFile } from '../utils/mimeTypes';
import { fulfilledPromiseSettledResult } from '../utils/common';
import { useFilePicker } from './useFilePicker';

/**
 * Enqueues files into the room composer upload board (shared by RoomInput and header media).
 */
export const useRoomUploadFiles = (room: Room) => {
  const setSelectedFiles = useSetAtom(roomIdToUploadItemsAtomFamily(room.roomId));

  const handleFiles = useCallback(
    async (files: File[]) => {
      const safeFiles = files.map(safeFile);
      const fileItems: TUploadItem[] = [];

      if (room.hasEncryptionStateEvent()) {
        const encryptFiles = fulfilledPromiseSettledResult(
          await Promise.allSettled(safeFiles.map((f) => encryptFile(f)))
        );
        encryptFiles.forEach((ef) =>
          fileItems.push({
            ...ef,
            metadata: {
              markedAsSpoiler: false,
            },
          })
        );
      } else {
        safeFiles.forEach((f) =>
          fileItems.push({
            file: f,
            originalFile: f,
            encInfo: undefined,
            metadata: {
              markedAsSpoiler: false,
            },
          })
        );
      }

      setSelectedFiles({
        type: 'PUT',
        item: fileItems,
      });
    },
    [setSelectedFiles, room]
  );

  const pickFiles = useFilePicker(handleFiles, true);

  return { handleFiles, pickFiles };
};
