import { useMutationState, useBindingOperations } from "@contember/binding";
import { FileUploadError } from "@contember/client";
import { useCallback } from "react";
import { unstable_batchedUpdates } from "react-dom";
import { useDropzone } from "react-dropzone";
import { AcceptFileKindError } from "../../fileHandler/AcceptFileKindError.js";
import { assertNever } from "../../../../../utils/assertNever.js";
const useNormalizedUploadState = ({
  fileUpload,
  isMultiple,
  fileHandler,
  prepareEntityForNewFile
}) => {
  const isMutating = useMutationState();
  const bindingOperations = useBindingOperations();
  const [uploadState, { initializeUpload, startUpload, failUpload }] = fileUpload;
  const onDrop = useCallback((files) => {
    const { getEntityByKey, getEntityListSubTree, getEntitySubTree, contentClient, systemClient, tenantClient } = bindingOperations;
    const filesWithIds = [];
    let metadataByFileId;
    unstable_batchedUpdates(() => {
      for (const file of files) {
        prepareEntityForNewFile((getNewAccessor) => {
          const fileId = getNewAccessor().key;
          filesWithIds.push([fileId, file]);
        });
      }
      metadataByFileId = initializeUpload(filesWithIds);
    });
    Promise.resolve().then(async () => {
      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);
      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) {
              errors.push(new FileUploadError(e.options));
            } else if (e instanceof AggregateError) {
              for (const error of e.errors) {
                if (error instanceof AcceptFileKindError) {
                  errors.push(new FileUploadError(error.options));
                }
              }
            }
            const file = files[i];
            if (errors.length) {
              rejected.push([file, errors]);
            } else {
              rejected.push(file);
            }
          } else {
            assertNever();
          }
        }
        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
  });
  return {
    uploadState,
    dropzoneState
  };
};
export { useNormalizedUploadState };
//# sourceMappingURL=useNormalizedUploadState.js.map
