import { IMAGE_TYPE } from "./../ricos-content/index.js";
import { createMediaUploadFn } from "./../_shared/create-media-upload-fn.js";
import { logInvariant } from "./../_shared/log-invariant.js";
import { createImageFileSelectionFn } from "./../_shared/media-manager/create-image-file-selection-fn.js";
import { unreachable } from "./../_shared/uncreachable.js";
import { upload } from "./../_shared/upload/upload.js";
import { RICOS_DEFAULTS } from "./consts.js";
const getImagePickMedia = ({
  services,
  handleFileUpload
}) => {
  const devPickMedia = services.devService().pickMedia;
  const editorPickMedia = services.editorProps.pickMedia?.pickImage;
  const handleFileSelection = services.devService().handleFileSelection ?? createImageFileSelectionFn(services);
  return devPickMedia ? devPickMedia : editorPickMedia ? editorPickMedia : handleFileSelection ? async ({ multiple }) => {
    try {
      const data = await new Promise(
        (resolve, reject) => handleFileSelection(
          ({ data: data2 }) => resolve(data2),
          { multiple, index: void 0 },
          reject
        )
      );
      return { type: "ready-media", media: data };
    } catch {
      return { type: "cancel" };
    }
  } : async ({ mimeType, multiple }) => {
    const files = await services.uploadService?.selectFiles({ accept: mimeType, multiple }) ?? [];
    return { type: "file", file: files, customUploadFn: handleFileUpload };
  };
};
const handleImageUpload = async ({
  services,
  config,
  publicCommands,
  nodeId,
  files,
  pos,
  referenceElement
}) => {
  const { accept = "image/*", multi = true } = config;
  const multiple = nodeId ? false : multi;
  const handleFileUpload = services.devService().handleFileUpload ?? createMediaUploadFn(services);
  const pickMedia = getImagePickMedia({ services, handleFileUpload });
  const result = files ? {
    type: "file",
    file: files,
    customUploadFn: handleFileUpload
  } : await pickMedia({ mimeType: accept, multiple });
  switch (result.type) {
    case "ready-media": {
      if (nodeId) {
        const componentData = publicCommands?.getBlockComponentData(nodeId);
        const image = result.media[0] || {};
        publicCommands?.setBlock(nodeId, IMAGE_TYPE, {
          ...componentData,
          image: getImageData(image),
          tempData: null,
          loading: null,
          error: null
        });
        return;
      }
      result.media.forEach((item, index) => {
        setTimeout(() => {
          const image = item;
          publicCommands.insertBlockWithBlankLines(
            IMAGE_TYPE,
            { image: getImageData(image), ...RICOS_DEFAULTS },
            {
              updateSelection: result.media.length === index + 1
            }
          );
        });
      });
      return;
    }
    case "file": {
      const resultFiles = result.file;
      return resultFiles.map(async (file, index) => {
        setTimeout(async () => {
          const targetNodeId = nodeId ?? publicCommands.insertBlockWithBlankLines(
            IMAGE_TYPE,
            { ...RICOS_DEFAULTS, loading: true },
            {
              updateSelection: resultFiles.length === index + 1,
              pos
            }
          );
          const trackBi = services.uploadService.trackUploadBi(IMAGE_TYPE, file.size, file.name);
          try {
            const url = URL.createObjectURL(file);
            await Promise.resolve();
            publicCommands?.setBlock(targetNodeId, IMAGE_TYPE, {
              ...publicCommands?.getBlockComponentData(targetNodeId),
              image: void 0,
              tempData: url,
              loading: true,
              error: null
            });
            trackBi?.start();
            const uploadFn = result.customUploadFn || handleFileUpload;
            if (!uploadFn) {
              logInvariant(Error("No upload function provided"));
              throw new Error("No upload function provided");
            }
            const uploadedFile = await upload(uploadFn, file);
            const { file_name, width, height } = uploadedFile.data || {};
            publicCommands?.setBlock(targetNodeId, IMAGE_TYPE, {
              ...publicCommands?.getBlockComponentData(targetNodeId),
              image: { src: { id: file_name }, width, height },
              tempData: null,
              loading: null,
              error: null
            });
            URL.revokeObjectURL(url);
            trackBi?.success();
            return;
          } catch (error) {
            const componentData = publicCommands?.getBlockComponentData(targetNodeId);
            publicCommands?.setBlock(targetNodeId, IMAGE_TYPE, {
              ...componentData,
              error,
              loading: null
            });
            trackBi?.error(error);
            services.uploadService.notifyError(error);
            return;
          }
        });
      });
    }
    case "cancel": {
      services.modals.notifyExternalModalClosed({ focusReturnElement: referenceElement });
      return;
    }
    default: {
      console.error(unreachable(result));
      return;
    }
  }
};
const isPickMediaType = (data) => "type" in data && data.type === "image";
const getImageData = (data) => {
  if (isPickMediaType(data)) {
    return {
      src: data.src,
      width: data.width,
      height: data.height
    };
  }
  const { file_name, width, height } = data;
  return { src: { id: file_name }, width, height };
};
export {
  handleImageUpload
};
//# sourceMappingURL=handle-image-upload.js.map
