"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var decoration_parsers_exports = {};
__export(decoration_parsers_exports, {
  getParagraphNode: () => getParagraphNode,
  mergeParagraphNodes: () => mergeParagraphNodes,
  mergeTextNodes: () => mergeTextNodes,
  parseDecorations: () => parseDecorations,
  parseEntityDecorations: () => parseEntityDecorations,
  parseInlineStyleDecorations: () => parseInlineStyleDecorations
});
module.exports = __toCommonJS(decoration_parsers_exports);
var import_lodash = __toESM(require("lodash"));
var import_v1 = require("./../../../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_consts = require("../../../consts.js");
var import_consts2 = require("../consts.js");
var import_emoji_regex = require("../emoji-regex.js");
var import_get_draft_entity_data = require("./get-draft-entity-data.js");
const isInlineStyleDecoration = (decorationType) => import_consts2.TO_RICOS_DECORATION_DATA_FIELD[decorationType] === void 0;
const pipe = (arg, ...fns) => {
  return fns.reduce((v, fn) => fn(v), arg);
};
const mergeTextNodes = (nodes) => {
  let length = 0;
  return (nodes ?? []).reduce(
    ({ text, decorationMap }, currNode) => {
      let accText = text;
      if (currNode.textData) {
        const { text: currText, decorations: currDecorations } = currNode.textData;
        const textLength = Array.from(currText).length;
        accText += currText;
        if (currDecorations) {
          convertDecorationTypes(currDecorations).forEach((decoration) => {
            if (!decorationMap[decoration.type]) {
              decorationMap[decoration.type] = [];
            }
            decorationMap[decoration.type] = [
              ...decorationMap[decoration.type],
              {
                ...decoration,
                start: length,
                end: length + textLength
              }
            ];
          });
        }
        length += textLength;
      }
      return { text: accText, decorationMap };
    },
    { text: "", decorationMap: {} }
  );
};
const mergeParagraphNodes = (nodes) => {
  return nodes.reduce(
    ({ text, decorationMap }, currNode) => {
      if (currNode.type !== import_v1.Node_Type.PARAGRAPH && currNode.type !== import_v1.Node_Type.HEADING) {
        return { text, decorationMap };
      }
      const currentText = mergeTextNodes(currNode.nodes ?? []);
      const shouldAddNewLineBetween = text && text !== "";
      const previousText = shouldAddNewLineBetween ? `${text}
` : text;
      const resultText = `${previousText}${currentText.text}`;
      const movedNewDecorationMap = moveDecorationsMapByPreviousTextLength(
        previousText,
        currentText.decorationMap
      );
      const mergedDecorationMap = mergeDecorationMap(decorationMap, movedNewDecorationMap);
      return { text: resultText, decorationMap: mergedDecorationMap };
    },
    { text: "", decorationMap: {} }
  );
};
const mergeDecorationMap = (oldDecorationMap, newDecorationMap) => {
  return Object.entries(newDecorationMap).reduce(
    (acc, [decorationType, decorations]) => {
      return {
        ...acc,
        [decorationType]: [...acc[decorationType] ?? [], ...decorations]
      };
    },
    oldDecorationMap
  );
};
const moveDecorationsMapByPreviousTextLength = (textBefore, decorationMap) => {
  return Object.entries(decorationMap).reduce(
    (acc, [decorationType, decorations]) => {
      return {
        ...acc,
        [decorationType]: decorations.map((decoration) => ({
          ...decoration,
          start: decoration.start + textBefore.length,
          end: decoration.end + textBefore.length
        }))
      };
    },
    {}
  );
};
const parseDecorations = (decorationMap, text) => {
  const nonMergableDecorations = [import_consts.LINK_TYPE, import_consts.MENTION_TYPE, import_consts.ANCHOR_TYPE];
  const decorations = Object.values(decorationMap).sort(decorationComparator).reduce((decorations2, currentDecorations) => {
    if (currentDecorations.length > 0) {
      const firstDecoration = currentDecorations.shift();
      const mergedDecorations = [firstDecoration];
      currentDecorations.forEach((decoration) => {
        const lastDecoration = mergedDecorations.pop();
        if (decoration.start === lastDecoration.end && !nonMergableDecorations.includes(decoration.type)) {
          mergedDecorations.push({ ...lastDecoration, end: decoration.end });
        } else {
          mergedDecorations.push(lastDecoration, decoration);
        }
      });
      return [...decorations2, ...mergedDecorations.sort(decorationComparator)];
    }
    return decorations2;
  }, []);
  const allDecorations = [...decorations, ...createEmojiDecorations(text)];
  const entityDecorations = allDecorations.filter(({ type }) => !isInlineStyleDecoration(type)).sort(decorationComparator);
  const inlineStyleDecorations = allDecorations.filter(({ type }) => isInlineStyleDecoration(type));
  return { inlineStyleDecorations, entityDecorations };
};
const parseInlineStyleDecorations = (decorations) => {
  const inlineStyleRanges = decorations.reduce(
    (inlineStyleRanges2, decoration) => [
      ...inlineStyleRanges2,
      {
        style: decoration.type,
        offset: decoration.start,
        length: decoration.end - decoration.start
      }
    ],
    []
  );
  return inlineStyleRanges;
};
const parseEntityDecorations = (decorations, latestEntityKey) => {
  const {
    entityRanges,
    entityMap,
    latestEntityKey: newLatestEntityKey
  } = decorations.reduce(
    ({ entityRanges: entityRanges2, entityMap: entityMap2, latestEntityKey: latestEntityKey2 }, decoration) => {
      const newEntityKey = latestEntityKey2 + 1;
      const newEntityMap = (0, import_get_draft_entity_data.createDecorationEntityData)(decoration, newEntityKey);
      return {
        entityRanges: [
          ...entityRanges2,
          {
            key: newEntityKey,
            offset: decoration.start,
            length: decoration.end - decoration.start
          }
        ],
        entityMap: { ...entityMap2, ...newEntityMap },
        latestEntityKey: newEntityKey
      };
    },
    { entityRanges: [], entityMap: {}, latestEntityKey }
  );
  return {
    entityRanges,
    entityMap,
    latestEntityKey: newLatestEntityKey
  };
};
const getParagraphNode = (node) => {
  if (node.nodes?.[0].type === import_v1.Node_Type.PARAGRAPH) {
    return node.nodes[0];
  } else {
    throw Error(`Expected a paragraph node but found ${node.nodes?.[0].type}`);
  }
};
const convertDecorationTypes = (decorations) => decorations.flatMap(
  (decoration) => pipe(
    decoration,
    toDraftDecorationType,
    convertFontSize,
    convertFontWeight,
    convertItalic,
    convertUnderline,
    splitColorDecoration
  )
);
const createEmojiDecorations = (text) => {
  const result = [];
  let match;
  while ((match = import_emoji_regex.emojiRegex.exec(text)) !== null) {
    const { 0: emojiUnicode, index: start } = match;
    const decoration = {
      type: "EMOJI_TYPE",
      emojiData: { emojiUnicode },
      start,
      end: start + Array.from(emojiUnicode).length
    };
    result.push(decoration);
  }
  return result;
};
const toDraftDecorationType = (decoration) => {
  const type = import_lodash.default.omit(import_consts2.FROM_RICOS_DECORATION_TYPE, [
    import_v1.Decoration_Type.BOLD,
    import_v1.Decoration_Type.ITALIC,
    import_v1.Decoration_Type.UNDERLINE
  ])[decoration?.type];
  return type ? { ...decoration, type } : decoration;
};
const splitColorDecoration = ({
  colorData,
  ...decoration
}) => {
  if (!colorData) {
    return decoration;
  }
  const { foreground, background } = colorData;
  return [foreground && { FG: foreground }, background && { BG: background }].filter((x) => x).map((type) => ({ ...decoration, type: JSON.stringify(type) }));
};
const convertFontSize = ({
  fontSizeData,
  ...decoration
}) => fontSizeData ? {
  ...decoration,
  type: JSON.stringify({
    "font-size": fontSizeData.value?.toString() + (fontSizeData.unit?.toLowerCase() || "px")
  })
} : decoration;
const convertFontWeight = ({
  fontWeightValue,
  ...decoration
}) => decoration.type === import_v1.Decoration_Type.BOLD ? {
  ...decoration,
  type: !fontWeightValue || fontWeightValue >= 700 ? "BOLD" : "NOT_BOLD"
} : decoration;
const convertItalic = ({
  italicData,
  ...decoration
}) => {
  const isItalicDataUndefined = typeof italicData === "undefined";
  return decoration.type === import_v1.Decoration_Type.ITALIC ? {
    ...decoration,
    type: isItalicDataUndefined || italicData ? "ITALIC" : "NOT_ITALIC"
  } : decoration;
};
const convertUnderline = ({
  underlineData,
  ...decoration
}) => {
  const isUnerlineDataUndefined = typeof underlineData === "undefined";
  return decoration.type === import_v1.Decoration_Type.UNDERLINE ? {
    ...decoration,
    type: isUnerlineDataUndefined || underlineData ? "UNDERLINE" : "NOT_UNDERLINE"
  } : decoration;
};
const decorationComparator = (a, b) => "start" in a && "start" in b ? a.start - b.start : Array.isArray(a) && Array.isArray(b) ? a[0].start - b[0].start : 0;
//# sourceMappingURL=decoration-parsers.js.map
