import { toSizeInKb } from "./../ricos-content/index.js";
import { getHighestQualityVideo } from "./../_shared/get-highest-quality-video.js";
import { getMediaFileType } from "./../_shared/get-media-file-type.js";
import { getUploadError } from "./../_shared/get-upload-error.js";
import { logInvariant } from "./../_shared/log-invariant.js";
import { createOpenMediaManagerFn } from "./../_shared/media-manager/create-open-media-manager-fn.js";
import { MediaManagerMediaType } from "./../_shared/media-manager/types.js";
import { createUploadFn } from "./../_shared/request-service-provider/media-manager-uploader.js";
import { unreachable } from "./../_shared/uncreachable.js";
import { upload } from "./../_shared/upload/upload.js";
import { withFileSizeLimitation } from "./../_shared/with-file-size-limitation.js";
import { FILE_UPLOAD_TYPE } from "./types.js";
const handleFileUpload = async ({
  config,
  services,
  publicCommands,
  nodeId,
  referenceElement
}) => {
  const { accept = "*", multi = true } = config;
  const onFileSelected = config.onFileSelected ?? createOnFileSelectedFn(services, config);
  const pickMedia = getFilePickMedia({ config, services, onFileSelected });
  const result = await pickMedia({
    mimeType: accept,
    multiple: nodeId ? false : multi
  });
  switch (result.type) {
    case "ready-media": {
      const data = result.media;
      if (nodeId) {
        const componentData = publicCommands?.getBlockComponentData(nodeId);
        publicCommands?.setBlock(nodeId, FILE_UPLOAD_TYPE, {
          ...componentData,
          ...getFileAttributes({
            uploadData: data[0],
            componentData
          })
        });
        return;
      }
      data.forEach((file, index) => {
        setTimeout(() => {
          publicCommands.insertBlockWithBlankLines(
            FILE_UPLOAD_TYPE,
            getFileAttributes({
              uploadData: file,
              componentData: {}
            }),
            { updateSelection: data.length === index + 1 }
          );
        });
      });
      return;
    }
    case "file": {
      const files = result.file;
      files.map(async (_file, index) => {
        const targetNodeId = nodeId ?? publicCommands.insertBlockWithBlankLines(
          FILE_UPLOAD_TYPE,
          { loading: true },
          { updateSelection: files.length === index + 1 }
        );
        const file = new File([_file], _file.name, { type: _file.type });
        const trackBi = services.uploadService.trackUploadBi(
          FILE_UPLOAD_TYPE,
          file.size,
          file.name
        );
        try {
          const { name, size } = file;
          const type = name.split(".").pop();
          publicCommands?.setBlock(targetNodeId, FILE_UPLOAD_TYPE, {
            ...publicCommands?.getBlockComponentData(targetNodeId),
            name,
            size,
            sizeInKb: toSizeInKb(size),
            type,
            loading: true,
            tempData: true,
            error: null
          });
          trackBi?.start();
          const uploadFn = result.customUploadFn || onFileSelected;
          if (!uploadFn) {
            logInvariant(Error("No upload function provided"));
            throw new Error("No upload function provided");
          }
          const uploadedFile = await upload(uploadFn, file);
          const uploadData = uploadedFile.data;
          publicCommands?.setBlock(targetNodeId, FILE_UPLOAD_TYPE, {
            ...getFileAttributes({
              uploadData,
              componentData: publicCommands?.getBlockComponentData(targetNodeId)
            }),
            error: null,
            tempData: null,
            loading: false
          });
          trackBi?.success();
        } catch (error) {
          const componentData = publicCommands?.getBlockComponentData(targetNodeId);
          publicCommands?.setBlock(targetNodeId, FILE_UPLOAD_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));
    }
  }
};
const getFilePickMedia = function({
  config,
  services,
  onFileSelected
}) {
  const devPickMedia = services.devService().pickMedia;
  const editorPickMedia = services.editorProps.pickMedia?.pickFile;
  const handleFileSelection = services.devService().handleFileSelection ?? config.handleFileSelection ?? createHandleFileSelectionFn(services);
  return devPickMedia ? devPickMedia : editorPickMedia ? editorPickMedia : handleFileSelection ? async () => {
    try {
      const data = await new Promise(
        (resolve, reject) => handleFileSelection(({ data: data2 }) => resolve(data2), reject)
      );
      return { type: "ready-media", media: data instanceof Array ? data : [data] };
    } catch {
      return { type: "cancel" };
    }
  } : async ({ mimeType }) => {
    const files = await services.uploadService?.selectFiles({ accept: mimeType, multiple: false }) ?? [];
    return { type: "file", file: files, customUploadFn: onFileSelected };
  };
};
const isPickMediaFileType = (data) => "type" in data && data.type === "file";
const getFileAttributes = ({
  uploadData,
  componentData
}) => {
  if (isPickMediaFileType(uploadData)) {
    const parsedSize2 = isNaN(parseInt(uploadData.size?.toString() ?? "")) ? null : parseInt(uploadData.size?.toString() ?? "");
    return {
      ...componentData,
      src: uploadData.src,
      name: uploadData.name,
      type: uploadData.extension,
      size: parsedSize2,
      pdfSettings: null,
      loading: false
    };
  }
  const { url, id, privacy, size, ...rest } = uploadData;
  const src = url ? { url } : { id };
  const parsedSize = isNaN(parseInt(size?.toString() ?? "")) ? null : parseInt(size?.toString() ?? "");
  return {
    ...componentData,
    ...rest,
    src: { ...src, private: privacy === "private" },
    size: parsedSize,
    pdfSettings: uploadData.pdfSettings || componentData?.pdfSettings || null,
    loading: false
  };
};
const createOnFileSelectedFn = (services, config) => {
  const { metaSiteId, uid, siteOwnerId } = services.wixInstance();
  if (!metaSiteId) {
    return void 0;
  }
  const fileUpload = (file, updateEntity) => {
    const upload2 = createUploadFn(services);
    const fileType = getMediaFileType(file.name);
    const privacy = config.privacy || "public";
    return upload2(file, fileType, { privacy }).then(({ original_file_name: name, media_type, file_url, file_output }) => {
      const fileUrl = file_output?.video ? getHighestQualityVideo(file_output.video).url : file_url;
      const type = file.name.split(".").length > 1 ? file.name.split(".").pop() : media_type;
      const componentData = getFilePluginComponentData(name, fileUrl, type || "", privacy);
      updateEntity({ data: componentData });
    }).catch((error) => {
      const isOwner = siteOwnerId === uid;
      const mediaUploadError = getUploadError(error, metaSiteId, isOwner);
      updateEntity({ error: mediaUploadError });
    });
  };
  return withFileSizeLimitation(fileUpload, services.editorProps.fileUploadSizeLimit);
};
const createHandleFileSelectionFn = (services) => {
  const openMediaManager = createOpenMediaManagerFn();
  if (!openMediaManager) {
    return void 0;
  }
  return (updateEntity, onCancel) => openMediaManager({
    mediaType: MediaManagerMediaType.ALL_MEDIA,
    appDefId: services.wixInstance().appDefId
  }).then((items) => {
    const componentData = getFilePluginComponentDataFromMediaManager(items[0]);
    updateEntity({ data: [componentData] });
  }).catch(onCancel);
};
const getFilePluginComponentDataFromMediaManager = (file) => {
  const { title: name, fileUrl, fileName, fileSize: size } = file;
  let url = fileUrl;
  let type = (fileName.split(".").length === 1 ? name : fileName).split(".").pop();
  if (file.mediaType === "video") {
    const video = getHighestQualityVideo(file.fileOutput.video);
    url = video.url;
    type = video.format;
  }
  if (!type) {
    type = "unknown";
    console.error("could not determine file type for file:", file);
  }
  return getFilePluginComponentData(name, url, type, "public", size);
};
const getFilePluginComponentData = (name, fileUrl, type, privacy = "public", size) => {
  const componentData = {
    name,
    type,
    id: fileUrl,
    privacy
  };
  return size ? { ...componentData, size } : componentData;
};
export {
  handleFileUpload
};
//# sourceMappingURL=handle-file-upload.js.map
