import { useEnvironment, VariableInputTransformer, BindingError } from "@contember/binding";
import { useMemo } from "react";
import { useObjectMemo } from "@contember/react-utils";
import { SingleKindFileHandler } from "./SingleKindFileHandler.js";
import { DiscriminatedFileHandler } from "./DiscriminatedFileHandler.js";
import { fileKindTemplateAnalyzer } from "../fileKinds/fileKindTemplateAnalyzer.js";
const getFileHandler = (props, environment, componentName) => {
  if (!("discriminationField" in props)) {
    return createSingleKindFileHandler(props);
  }
  return createDiscriminatedFileKinds(props, environment, componentName);
};
const useFileHandler = (unstableProps, componentName) => {
  const environment = useEnvironment();
  const props = useObjectMemo(unstableProps);
  return useMemo(() => getFileHandler(props, environment, componentName), [componentName, environment, props]);
};
const createSingleKindFileHandler = (props) => {
  const { hasUploadedFile, children, acceptFile, acceptMimeTypes, baseEntity, renderFilePreview, renderUploadedFile, extractors, uploader } = props;
  return new SingleKindFileHandler({
    acceptFile,
    acceptMimeTypes,
    baseEntity,
    children,
    extractors,
    renderFilePreview,
    renderUploadedFile,
    uploader
  }, hasUploadedFile);
};
const createDiscriminatedFileKinds = (props, environment, componentName) => {
  const { discriminationField, children, baseEntity } = props;
  const processed = fileKindTemplateAnalyzer.processChildren(children, environment);
  const fileKinds = processed.map((node) => node.value);
  const normalizedFileKinds = /* @__PURE__ */ new Map();
  for (const { acceptFile, acceptMimeTypes, baseEntity: baseEntity2, children: children2, extractors, renderFilePreview, renderUploadedFile, uploader, discriminateBy, childrenOutsideBaseEntity } of fileKinds) {
    const value = VariableInputTransformer.transformValue(discriminateBy, environment);
    normalizedFileKinds.set(value, {
      discriminateBy: value,
      datum: {
        acceptFile,
        acceptMimeTypes,
        baseEntity: baseEntity2,
        children: children2,
        extractors,
        renderFilePreview,
        renderUploadedFile,
        uploader,
        childrenOutsideBaseEntity
      }
    });
  }
  if (!normalizedFileKinds.size) {
    throw new BindingError(`${componentName}: having supplied the 'discriminationField' prop, you must specify at least one file kind!`);
  }
  return new DiscriminatedFileHandler(discriminationField, baseEntity, normalizedFileKinds);
};
export { createDiscriminatedFileKinds, createSingleKindFileHandler, getFileHandler, useFileHandler };
//# sourceMappingURL=useFileHandler.js.map
