import { useState, useRef, useEffect, createElement } from "react";
import { BindingError } from "@contember/binding";
import { FilePreview, ErrorList, Message, UploadProgress } from "@contember/ui";
function InitializedFilePreview({
  fileKind,
  resolvedEntity,
  formatMessage,
  uploadState
}) {
  const [extractionState, setExtractionState] = useState({ name: "uninitialized" });
  const isMountedRef = useRef(true);
  useEffect(() => {
    const extractData = async () => {
      if (extractionState.name !== "uninitialized" || uploadState.readyState === "error") {
        return;
      }
      const dataPromises = fileKind.extractors.map((extractor) => extractor.extractFileData ? extractor.extractFileData({
        file: uploadState.file,
        acceptArtifacts: uploadState.metadata,
        objectUrl: uploadState.previewUrl
      }) : Promise.resolve());
      setExtractionState({ name: "working" });
      try {
        const data = await Promise.all(dataPromises);
        if (!isMountedRef.current) {
          return;
        }
        setExtractionState({
          name: "success",
          data
        });
      } catch (e) {
        setExtractionState({
          name: "error"
        });
      }
    };
    extractData();
  }, [extractionState.name, fileKind.extractors, uploadState]);
  useEffect(() => {
    if (uploadState.readyState !== "success" || extractionState.name !== "success") {
      return;
    }
    if (!resolvedEntity.fileEntity) {
      throw new BindingError();
    }
    resolvedEntity.fileEntity.batchUpdates((getEntity) => {
      for (let i = 0; i < fileKind.extractors.length; i++) {
        const extractor = fileKind.extractors[i];
        const extractedData = extractionState.data[i];
        extractor.populateFields({
          file: uploadState.file,
          objectUrl: uploadState.previewUrl,
          extractedData,
          uploadResult: uploadState.result,
          acceptArtifacts: uploadState.metadata,
          entity: getEntity()
        });
      }
    });
  }, [extractionState, fileKind.baseEntity, fileKind.extractors, resolvedEntity.fileEntity, uploadState]);
  useEffect(() => () => {
    isMountedRef.current = false;
  }, []);
  const getOverlay = () => {
    if (uploadState.readyState === "error") {
      const endUserMessages = uploadState.errors ? uploadState.errors.filter((error) => !!error.options.endUserMessage).map((error) => ({ message: formatMessage(error.options.endUserMessage, "upload.fileState.failedUpload") })) : [];
      if (endUserMessages.length) {
        return /* @__PURE__ */ createElement(ErrorList, {
          errors: endUserMessages
        });
      }
    }
    if (uploadState.readyState === "error" || extractionState.name === "error") {
      return /* @__PURE__ */ createElement(Message, {
        intent: "danger"
      }, formatMessage("upload.fileState.failedUpload"));
    }
    if (uploadState.readyState === "success") {
      if (extractionState.name === "success") {
        return void 0;
      }
      return /* @__PURE__ */ createElement(UploadProgress, {
        progress: formatMessage("upload.fileState.finalizing")
      });
    }
    if (uploadState.readyState === "uploading") {
      return /* @__PURE__ */ createElement(UploadProgress, {
        progress: uploadState.progress
      });
    }
    return /* @__PURE__ */ createElement(UploadProgress, null);
  };
  return /* @__PURE__ */ createElement(FilePreview, {
    overlay: getOverlay()
  }, fileKind.renderFilePreview({
    file: uploadState.file,
    objectUrl: uploadState.previewUrl,
    acceptArtifacts: uploadState.metadata
  }));
}
export { InitializedFilePreview };
//# sourceMappingURL=InitializedFilePreview.js.map
