"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_image_upload_exports = {};
__export(handle_image_upload_exports, {
  handleImageUpload: () => handleImageUpload
});
module.exports = __toCommonJS(handle_image_upload_exports);
var import_ricos_content = require("./../ricos-content/index.js");
var import_create_media_upload_fn = require("./../_shared/create-media-upload-fn.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_create_image_file_selection_fn = require("./../_shared/media-manager/create-image-file-selection-fn.js");
var import_uncreachable = require("./../_shared/uncreachable.js");
var import_upload = require("./../_shared/upload/upload.js");
var import_consts = require("./consts.js");
const getImagePickMedia = ({
  services,
  handleFileUpload
}) => {
  const devPickMedia = services.devService().pickMedia;
  const editorPickMedia = services.editorProps.pickMedia?.pickImage;
  const handleFileSelection = services.devService().handleFileSelection ?? (0, import_create_image_file_selection_fn.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 ?? (0, import_create_media_upload_fn.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, import_ricos_content.IMAGE_TYPE, {
          ...componentData,
          image: getImageData(image),
          tempData: null,
          loading: null,
          error: null
        });
        return;
      }
      result.media.forEach((item, index) => {
        setTimeout(() => {
          const image = item;
          publicCommands.insertBlockWithBlankLines(
            import_ricos_content.IMAGE_TYPE,
            { image: getImageData(image), ...import_consts.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(
            import_ricos_content.IMAGE_TYPE,
            { ...import_consts.RICOS_DEFAULTS, loading: true },
            {
              updateSelection: resultFiles.length === index + 1,
              pos
            }
          );
          const trackBi = services.uploadService.trackUploadBi(import_ricos_content.IMAGE_TYPE, file.size, file.name);
          try {
            const url = URL.createObjectURL(file);
            await Promise.resolve();
            publicCommands?.setBlock(targetNodeId, import_ricos_content.IMAGE_TYPE, {
              ...publicCommands?.getBlockComponentData(targetNodeId),
              image: void 0,
              tempData: url,
              loading: true,
              error: null
            });
            trackBi?.start();
            const uploadFn = result.customUploadFn || handleFileUpload;
            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 { file_name, width, height } = uploadedFile.data || {};
            publicCommands?.setBlock(targetNodeId, import_ricos_content.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, import_ricos_content.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((0, import_uncreachable.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 };
};
//# sourceMappingURL=handle-image-upload.js.map
