"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const reactBinding = require("@contember/react-binding");
const client = require("@contember/client");
const utilities = require("@contember/utilities");
const react = require("react");
const ReactDOM = require("react-dom");
const dropzone = require("react-dropzone");
const AcceptFileKindError = require("../../fileHandler/AcceptFileKindError.cjs");
function _interopNamespaceDefault(e) {
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const dropzone__namespace = /* @__PURE__ */ _interopNamespaceDefault(dropzone);
const { useDropzone } = dropzone__namespace;
const useNormalizedUploadState = ({
  fileUpload,
  isMultiple,
  fileHandler,
  prepareEntityForNewFile
}) => {
  const isMutating = reactBinding.useMutationState();
  const bindingOperations = reactBinding.useBindingOperations();
  const [uploadState, { initializeUpload, startUpload, failUpload }] = fileUpload;
  const onDrop = react.useCallback(async (files) => {
    const { getEntityByKey, getEntityListSubTree, getEntitySubTree, contentClient, systemClient, tenantClient } = bindingOperations;
    const filesWithIds = [];
    const metadataByFileId = ReactDOM.unstable_batchedUpdates(() => {
      for (const file of files) {
        prepareEntityForNewFile((getNewAccessor) => {
          const fileId = getNewAccessor().key;
          filesWithIds.push([fileId, file]);
        });
      }
      return initializeUpload(filesWithIds);
    });
    const resolvedKindPromises = [];
    for (const fileMetadata of metadataByFileId.values()) {
      resolvedKindPromises.push(fileHandler.acceptFile({
        file: fileMetadata.file,
        abortSignal: fileMetadata.abortController.signal,
        objectUrl: fileMetadata.previewUrl,
        getEntityByKey,
        getEntityListSubTree,
        getEntitySubTree,
        contentClient,
        systemClient,
        tenantClient
      }));
    }
    const resolvedFileKinds = await Promise.allSettled(resolvedKindPromises);
    ReactDOM.unstable_batchedUpdates(() => {
      const resolved = /* @__PURE__ */ new Map();
      const rejected = [];
      for (const [i, result] of resolvedFileKinds.entries()) {
        if (result.status === "fulfilled") {
          const resolvedKind = result.value;
          if (resolvedKind === void 0) {
            rejected.push(files[i]);
            continue;
          }
          resolved.set(files[i], {
            uploader: resolvedKind.fileKind.uploader
          });
          if (resolvedKind.finalizeEntity) {
            const fileId = filesWithIds[i][0];
            const fileEntity = getEntityByKey(fileId);
            resolvedKind.finalizeEntity(fileEntity);
          }
        } else if (result.status === "rejected") {
          const errors = [];
          const e = result.reason;
          if (e instanceof AcceptFileKindError.AcceptFileKindError) {
            errors.push(new client.FileUploadError(e.options));
          } else if (e instanceof AggregateError) {
            for (const error of e.errors) {
              if (error instanceof AcceptFileKindError.AcceptFileKindError) {
                errors.push(new client.FileUploadError(error.options));
              }
            }
          }
          const file = files[i];
          if (errors.length) {
            rejected.push([file, errors]);
          } else {
            rejected.push(file);
          }
        } else {
          utilities.assertNever(result);
        }
      }
      if (rejected.length) {
        failUpload(rejected);
      }
      startUpload(resolved);
    });
  }, [bindingOperations, initializeUpload, prepareEntityForNewFile, fileHandler, startUpload, failUpload]);
  const dropzoneState = useDropzone({
    onDrop,
    disabled: isMutating,
    accept: fileHandler.acceptedMimes ?? void 0,
    multiple: isMultiple,
    noKeyboard: true
    // This would normally be absolutely henious but there is a keyboard-focusable button inside.
  });
  return {
    uploadState,
    dropzoneState
  };
};
exports.useNormalizedUploadState = useNormalizedUploadState;
//# sourceMappingURL=useNormalizedUploadState.cjs.map
