"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var handle_file_upload_exports = {};
__export(handle_file_upload_exports, {
  handleFileUpload: () => handleFileUpload
});
module.exports = __toCommonJS(handle_file_upload_exports);
var import_ricos_content = require("./../ricos-content/index.js");
var import_get_highest_quality_video = require("./../_shared/get-highest-quality-video.js");
var import_get_media_file_type = require("./../_shared/get-media-file-type.js");
var import_get_upload_error = require("./../_shared/get-upload-error.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_create_open_media_manager_fn = require("./../_shared/media-manager/create-open-media-manager-fn.js");
var import_types = require("./../_shared/media-manager/types.js");
var import_media_manager_uploader = require("./../_shared/request-service-provider/media-manager-uploader.js");
var import_uncreachable = require("./../_shared/uncreachable.js");
var import_upload = require("./../_shared/upload/upload.js");
var import_with_file_size_limitation = require("./../_shared/with-file-size-limitation.js");
var import_types2 = require("./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, import_types2.FILE_UPLOAD_TYPE, {
          ...componentData,
          ...getFileAttributes({
            uploadData: data[0],
            componentData
          })
        });
        return;
      }
      data.forEach((file, index) => {
        setTimeout(() => {
          publicCommands.insertBlockWithBlankLines(
            import_types2.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(
          import_types2.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(
          import_types2.FILE_UPLOAD_TYPE,
          file.size,
          file.name
        );
        try {
          const { name, size } = file;
          const type = name.split(".").pop();
          publicCommands?.setBlock(targetNodeId, import_types2.FILE_UPLOAD_TYPE, {
            ...publicCommands?.getBlockComponentData(targetNodeId),
            name,
            size,
            sizeInKb: (0, import_ricos_content.toSizeInKb)(size),
            type,
            loading: true,
            tempData: true,
            error: null
          });
          trackBi?.start();
          const uploadFn = result.customUploadFn || onFileSelected;
          if (!uploadFn) {
            (0, import_log_invariant.logInvariant)(Error("No upload function provided"));
            throw new Error("No upload function provided");
          }
          const uploadedFile = await (0, import_upload.upload)(uploadFn, file);
          const uploadData = uploadedFile.data;
          publicCommands?.setBlock(targetNodeId, import_types2.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, import_types2.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((0, import_uncreachable.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 = (0, import_media_manager_uploader.createUploadFn)(services);
    const fileType = (0, import_get_media_file_type.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 ? (0, import_get_highest_quality_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 = (0, import_get_upload_error.getUploadError)(error, metaSiteId, isOwner);
      updateEntity({ error: mediaUploadError });
    });
  };
  return (0, import_with_file_size_limitation.withFileSizeLimitation)(fileUpload, services.editorProps.fileUploadSizeLimit);
};
const createHandleFileSelectionFn = (services) => {
  const openMediaManager = (0, import_create_open_media_manager_fn.createOpenMediaManagerFn)();
  if (!openMediaManager) {
    return void 0;
  }
  return (updateEntity, onCancel) => openMediaManager({
    mediaType: import_types.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 = (0, import_get_highest_quality_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;
};
//# sourceMappingURL=handle-file-upload.js.map
