"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_get_highest_quality_video = require(".//get-highest-quality-video.js");
var import_get_media_file_type = require(".//get-media-file-type.js");
var import_get_upload_error = require(".//get-upload-error.js");
var import_log_invariant = require(".//log-invariant.js");
var import_create_open_media_manager_fn = require(".//media-manager/create-open-media-manager-fn.js");
var import_types = require(".//media-manager/types.js");
var import_media_manager_uploader = require(".//request-service-provider/media-manager-uploader.js");
var import_uncreachable = require(".//uncreachable.js");
var import_upload = require(".//upload/upload.js");
var import_with_file_size_limitation = require(".//with-file-size-limitation.js");
var import_wix_rich_content_common = require("./../wix-rich-content-common/index.js");
const ACCEPT_MIME_TYPES = "image/png,image/jpeg,text/csv,text/plain";
const handleFileUpload = async ({
  services,
  callbacks,
  pluginId
}) => {
  const onFileSelected = createOnFileSelectedFn(services, "public");
  const pickMedia = getFilePickMedia({ services, onFileSelected });
  const result = await pickMedia({
    mimeType: ACCEPT_MIME_TYPES,
    multiple: false
  });
  switch (result.type) {
    case "ready-media": {
      const data = result.media;
      const fileData = data[0];
      const attachment = fileDataToAttachment(fileData, (0, import_wix_rich_content_common.uuid)());
      callbacks.onSuccess(attachment.id, attachment);
      return;
    }
    case "file": {
      const _file = result.file[0];
      const file = new File([_file], _file.name, { type: _file.type });
      const trackBi = services.uploadService.trackUploadBi(pluginId, file.size, file.name);
      const attachmentId = (0, import_wix_rich_content_common.uuid)();
      try {
        const { name } = file;
        const type = name.split(".").pop() || "";
        callbacks.onLoadingStart({
          id: attachmentId,
          status: "loading",
          file: {
            name,
            type: toFileType(type)
          }
        });
        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;
        const successAttachment = fileDataToAttachment(uploadData, attachmentId);
        callbacks.onSuccess(attachmentId, successAttachment);
        trackBi?.success();
      } catch (error) {
        callbacks.onError(attachmentId, {
          id: attachmentId,
          status: "error",
          file: {
            name: file.name,
            type: toFileType(file.name.split(".").pop() || "")
          },
          error: error.message || "Upload failed"
        });
        trackBi?.error(error);
      }
      return;
    }
    case "cancel": {
      services.modals.notifyExternalModalClosed();
      return;
    }
    default: {
      console.error((0, import_uncreachable.unreachable)(result));
    }
  }
};
const getFilePickMedia = function({
  services,
  onFileSelected
}) {
  const devPickMedia = services.devService().pickMedia;
  const editorPickMedia = services.editorProps.pickMedia?.pickFile;
  const handleFileSelection = services.devService().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 fileDataToAttachment = (fileData, attachmentId) => {
  if (isPickMediaFileType(fileData)) {
    const fileType2 = toFileType(fileData.extension || "");
    const fileUrl2 = ("url" in fileData.src ? fileData.src.url : fileData.src.id) || "";
    return {
      id: attachmentId || fileUrl2,
      status: "ok",
      file: {
        name: fileData.name || "",
        type: fileType2,
        url: fileUrl2
      }
    };
  }
  const fileName = "original_file_name" in fileData && fileData.original_file_name || "file_name" in fileData && fileData.file_name || "name" in fileData && fileData.name || "";
  const fileExtension = fileName.split(".").pop() || "type" in fileData && fileData.type || "";
  const fileType = toFileType(fileExtension);
  const fileUrl = fileData.url || fileData.id || "";
  return {
    id: attachmentId || fileUrl,
    status: "ok",
    file: {
      name: fileName,
      type: fileType,
      url: fileUrl
    }
  };
};
const createOnFileSelectedFn = (services, privacy = "public") => {
  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);
    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;
};
const toFileType = (type) => {
  if (type.includes("image") || type === "jpeg" || type === "jpg" || type === "png") {
    return type === "jpeg" ? "jpeg" : type === "jpg" ? "jpg" : "png";
  }
  if (type.includes("csv")) {
    return "csv";
  }
  if (type.includes("pdf")) {
    return "pdf";
  }
  return "text";
};
//# sourceMappingURL=handle-file-upload.js.map
