// packages/editor/src/utils/media-upload/index.js
import { v4 as uuid } from "uuid";
import { select, dispatch } from "@wordpress/data";
import { store as coreDataStore } from "@wordpress/core-data";
import { uploadMedia } from "@wordpress/media-utils";
import { isClientSideMediaSupported } from "@wordpress/upload-media";
import { store as editorStore } from "../../store/index.mjs";
var noop = () => {
};
function mediaUpload({
  additionalData = {},
  allowedTypes,
  filesList,
  maxUploadFileSize,
  onError = noop,
  onFileChange,
  onSuccess,
  multiple = true
}) {
  const { receiveEntityRecords } = dispatch(coreDataStore);
  const { getCurrentPost, getEditorSettings } = select(editorStore);
  const {
    lockPostAutosaving,
    unlockPostAutosaving,
    lockPostSaving,
    unlockPostSaving
  } = dispatch(editorStore);
  const wpAllowedMimeTypes = getEditorSettings().allowedMimeTypes;
  const isClientSideMediaActive = window.__clientSideMediaProcessing && isClientSideMediaSupported();
  const lockKey = `image-upload-${uuid()}`;
  maxUploadFileSize = maxUploadFileSize || getEditorSettings().maxUploadFileSize;
  const currentPost = getCurrentPost();
  const currentPostId = typeof currentPost?.id === "number" ? currentPost.id : currentPost?.wp_id;
  const clearSaveLock = () => {
    unlockPostSaving(lockKey);
    unlockPostAutosaving(lockKey);
  };
  if (!isClientSideMediaActive) {
    lockPostSaving(lockKey);
    lockPostAutosaving(lockKey);
  }
  const postData = currentPostId ? { post: currentPostId } : {};
  uploadMedia({
    allowedTypes,
    filesList,
    onFileChange: (files) => {
      onFileChange?.(files);
      const entityFiles = files.filter((_file) => _file?.id);
      if (entityFiles?.length) {
        const invalidateCache = true;
        receiveEntityRecords(
          "postType",
          "attachment",
          entityFiles,
          void 0,
          invalidateCache
        );
      }
      if (!isClientSideMediaActive && entityFiles.length === files.length) {
        clearSaveLock();
      }
    },
    onSuccess,
    additionalData: {
      ...postData,
      ...additionalData
    },
    maxUploadFileSize,
    onError: ({ message }) => {
      if (!isClientSideMediaActive) {
        clearSaveLock();
      }
      onError(message);
    },
    wpAllowedMimeTypes,
    multiple
  });
}
export {
  mediaUpload as default
};
//# sourceMappingURL=index.mjs.map
