import lodash from "lodash";
import { isDraftContent, isRichContent } from "../types/content-types.js";
import { truncateRichContent } from "./ricos-truncate.js";
import { getFilteredNodes } from "./ricos-truncate.js";
const toLimits = (limits) => ({
  nodeCount: limits.blocksCount ?? Infinity,
  wordCount: limits.wordsCount ?? Infinity,
  maxPlugins: limits.maxPlugins ?? Infinity
});
const truncateContent = (content, limits, options) => {
  if (isDraftContent(content)) {
    return truncateDraftContent(content, limits);
  }
  if (isRichContent(content)) {
    const truncatedContent = truncateRichContent(content, toLimits(limits), options);
    const isTruncated = !lodash.isEqual(content, truncatedContent);
    return { content: truncatedContent, isTruncated };
  }
  return { content, isTruncated: false };
};
const truncateDraftContent = (content, limits = {}) => {
  const { blocks, entityMap } = content;
  const { wordsCount = Infinity, maxPlugins = Infinity, blocksCount = Infinity } = limits;
  if (blocksCount < 0 || blocksCount > blocks.length && wordsCount === Infinity && maxPlugins === Infinity) {
    return { content, isTruncated: false };
  }
  const newEntityMap = {};
  const BreakException = {};
  const newBlocks = [];
  let cWordCount = 0;
  let pluginsCount = 0;
  let isTruncated = false;
  try {
    blocks.forEach((block, i) => {
      if (i === blocksCount) {
        throw BreakException;
      }
      const blockWords = block.text.split(" ").filter((x) => x !== "");
      if (block.type === "atomic") {
        pluginsCount++;
      }
      if (pluginsCount > maxPlugins) {
        throw BreakException;
      }
      if (cWordCount + blockWords.length > wordsCount) {
        newBlocks.push({
          ...block,
          text: blockWords.slice(0, wordsCount - cWordCount).join(" ") + "…"
        });
      } else {
        newBlocks.push(block);
      }
      cWordCount += blockWords.length;
      block.entityRanges.forEach((entity) => {
        newEntityMap[entity.key] = entityMap[entity.key];
      });
      if (cWordCount >= wordsCount) {
        throw BreakException;
      }
    });
  } catch (e) {
    if (e !== BreakException) {
      throw e;
    }
    isTruncated = true;
  }
  const truncatedContent = { ...content, blocks: newBlocks, entityMap: newEntityMap };
  return { content: truncatedContent, isTruncated };
};
export {
  getFilteredNodes as getCountableNodes,
  truncateContent
};
//# sourceMappingURL=index.js.map
