import { useCallback } from "react";
import { useDesugaredRelativeEntityList, useDesugaredRelativeSingleField } from "@contember/binding";
import { useGetParentEntityRef } from "../useGetParentEntityRef.js";
import { assertNever } from "../../../../../utils/assertNever.js";
const useBlockEditorOnChange = ({ refreshBlocks, editor, sortedBlocksRef, contentField, blockList, blockElementCache }) => {
  const getParentEntityRef = useGetParentEntityRef();
  const desugaredBlockList = useDesugaredRelativeEntityList(blockList);
  const desugaredBlockContentField = useDesugaredRelativeSingleField(contentField);
  return useCallback(() => {
    const { children, operations } = editor;
    const saveBlockElement = (getBlockList, id, element) => {
      getBlockList().getChildEntityById(id).getRelativeSingleField(desugaredBlockContentField).updateValue(editor.serializeNodes([element]));
      blockElementCache.set(getBlockList().getChildEntityById(id), element);
    };
    const operationsType = getTypeOfOperations(operations);
    if (operationsType === "selection") {
      return;
    }
    const topLevelBlocks = sortedBlocksRef.current;
    if (operationsType === "text" && topLevelBlocks.length > 0) {
      return getParentEntityRef.current().batchUpdates((getEntity) => {
        for (const operation of operations) {
          switch (operation.type) {
            case "insert_text":
            case "remove_text":
              const [topLevelIndex] = operation.path;
              saveBlockElement(getEntity().getRelativeEntityList(desugaredBlockList).getAccessor, topLevelBlocks[topLevelIndex].id, children[topLevelIndex]);
              break;
          }
        }
      });
    } else {
      refreshBlocks();
    }
  }, [blockElementCache, desugaredBlockContentField, desugaredBlockList, editor, getParentEntityRef, refreshBlocks, sortedBlocksRef]);
};
const getTypeOfOperations = (operations) => {
  let hasTextOperation = false;
  for (const operation of operations) {
    switch (operation.type) {
      case "set_selection":
        break;
      case "insert_text":
      case "remove_text":
        hasTextOperation = true;
        break;
      case "insert_node":
      case "merge_node":
      case "move_node":
      case "remove_node":
      case "set_node":
      case "split_node":
        return "node";
      default:
        return assertNever();
    }
  }
  return hasTextOperation ? "text" : "selection";
};
export { useBlockEditorOnChange };
//# sourceMappingURL=useBlockEditorOnChange.js.map
