import { logInvariant } from "./../../_shared/log-invariant.js";
import { createImageFileSelectionFn } from "./../../_shared/media-manager/create-image-file-selection-fn.js";
import { upload } from "./../../_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 ?? 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) {
            logInvariant(Error("No upload function provided"));
            throw new Error("No upload function provided");
          }
          const uploadedFile = await 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;
    }
  }
};
export {
  getImagePickMedia,
  handleLayoutImageUpload
};
//# sourceMappingURL=handle-layout-image-upload.js.map
