"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_layout_image_upload_exports = {};
__export(handle_layout_image_upload_exports, {
  getImagePickMedia: () => getImagePickMedia,
  handleLayoutImageUpload: () => handleLayoutImageUpload
});
module.exports = __toCommonJS(handle_layout_image_upload_exports);
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_upload = require("./../../_shared/upload/upload.js");
const getImagePickMedia = ({
  services,
  config
}) => {
  const { handleFileUpload } = config;
  const editorPickMedia = services.editorProps.pickMedia?.pickImage;
  const devPickMedia = services.devService().pickMedia;
  const handleFileSelection = services.devService().handleFileSelection ?? config.handleFileSelection ?? (0, import_create_image_file_selection_fn.createImageFileSelectionFn)(services);
  return devPickMedia ? devPickMedia : editorPickMedia ? editorPickMedia : handleFileSelection ? async () => {
    try {
      const data = await new Promise(
        (resolve, reject) => handleFileSelection(
          ({ data: data2 }) => resolve(Array.isArray(data2) ? data2[0] : data2),
          {
            multiple: false
          },
          reject
        )
      );
      return { type: "ready-media", media: [data] };
    } catch {
      return { type: "cancel" };
    }
  } : async ({ mimeType }) => {
    const files = await services.uploadService?.selectFiles({ accept: mimeType, multiple: false }) ?? [];
    return { type: "file", file: files, customUploadFn: handleFileUpload };
  };
};
const getLayoutAttributes = ({
  uploadData,
  componentData,
  attributeKey
}) => {
  const backgroundImage = componentData?.[attributeKey];
  return {
    ...componentData,
    [attributeKey]: {
      ...backgroundImage,
      media: {
        src: "src" in uploadData ? uploadData.src : { id: uploadData.file_name },
        width: uploadData.width,
        height: uploadData.height
      },
      opacity: backgroundImage?.opacity ?? 100,
      scaling: backgroundImage?.scaling ?? "COVER",
      position: backgroundImage?.position ?? "CENTER"
    },
    loading: componentData.loading ? { ...componentData.loading, [attributeKey]: false } : void 0
  };
};
const handleLayoutImageUpload = async ({
  services,
  config,
  publicCommands,
  nodeId,
  nodeType,
  attributeKey
}) => {
  const mimeType = "image/*";
  const pickMedia = getImagePickMedia({ services, config });
  const result = await pickMedia({ mimeType, multiple: false });
  switch (result.type) {
    case "ready-media": {
      const data = result.media[0];
      const componentData = publicCommands?.getBlockComponentData(nodeId);
      const updatedData = getLayoutAttributes({
        componentData,
        uploadData: data,
        attributeKey
      });
      publicCommands?.setBlock(nodeId, nodeType, {
        ...updatedData,
        loading: componentData.loading ? { ...componentData.loading, [attributeKey]: false } : void 0
      });
      return;
    }
    case "file": {
      const file = result.file[0];
      if (file) {
        const trackBi = services.uploadService?.trackUploadBi(nodeType, file.size, file.name);
        try {
          const url = URL.createObjectURL(file);
          await Promise.resolve();
          const componentData = publicCommands?.getBlockComponentData(nodeId);
          publicCommands?.setBlock(nodeId, nodeType, {
            ...componentData,
            loading: componentData.loading ? { ...componentData.loading, [attributeKey]: true } : { [attributeKey]: true }
          });
          trackBi?.start();
          const uploadFn = result.customUploadFn || config.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 updatedData = getLayoutAttributes({
            componentData: publicCommands?.getBlockComponentData(nodeId),
            uploadData: uploadedFile.data,
            attributeKey
          });
          publicCommands?.setBlock(nodeId, nodeType, updatedData);
          URL.revokeObjectURL(url);
          trackBi?.success();
        } catch (error) {
          const componentData = publicCommands?.getBlockComponentData(nodeId);
          publicCommands?.setBlock(nodeId, nodeType, {
            ...componentData,
            error,
            loading: componentData.loading ? { ...componentData.loading, [attributeKey]: false } : void 0
          });
          trackBi?.error(error);
          services.uploadService?.notifyError(error);
        }
      } else {
        console.error("No file selected");
      }
      return;
    }
    case "cancel": {
      services.modals.notifyExternalModalClosed();
      return;
    }
    default: {
      console.error("Unhandeled media picker result:", result);
      return;
    }
  }
};
//# sourceMappingURL=handle-layout-image-upload.js.map
