"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 from_draft_exports = {};
__export(from_draft_exports, {
  ensureRicosContent: () => ensureRicosContent,
  fromDraft: () => fromDraft
});
module.exports = __toCommonJS(from_draft_exports);
var import_lodash = __toESM(require("lodash"));
var import_v1 = require("./../../../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_remove_inline_header_ranges = require("../../../normalization/remove-inline-header-ranges.js");
var import_utils = require("../../../utils.js");
var import_generate_random_id = require("../../generate-random-id.js");
var import_node_utils = require("../../node-utils.js");
var import_consts = require("../consts.js");
var import_get_ricos_entity_data = require("./get-ricos-entity-data.js");
var import_get_text_nodes = require("./get-text-nodes.js");
var import_parse_doc_style = require("./parse-doc-style.js");
const ensureRicosContent = (content, opts) => "blocks" in content ? fromDraft(content, opts) : content;
const normalizeTableColorValue = (color) => {
  const validColor = (0, import_utils.getValidColorValue)(color);
  return validColor?.startsWith("#") ? validColor.toUpperCase() : validColor;
};
const parseCollapsible = (entity, opts) => entity.pairs.map((pair) => ({
  id: pair.key,
  type: import_v1.Node_Type.COLLAPSIBLE_ITEM,
  nodes: [
    {
      id: (0, import_generate_random_id.generateId)(),
      type: import_v1.Node_Type.COLLAPSIBLE_ITEM_TITLE,
      nodes: fromDraft(pair.title, opts).nodes
    },
    {
      id: (0, import_generate_random_id.generateId)(),
      type: import_v1.Node_Type.COLLAPSIBLE_ITEM_BODY,
      nodes: fromDraft(pair.content, opts).nodes
    }
  ]
}));
const parseTable = (entity, opts) => Object.entries(entity.rows).map(([, row]) => ({
  id: (0, import_generate_random_id.generateId)(),
  type: import_v1.Node_Type.TABLE_ROW,
  nodes: Object.entries(row.columns ?? {}).map(([, cell]) => ({
    id: (0, import_generate_random_id.generateId)(),
    type: import_v1.Node_Type.TABLE_CELL,
    tableCellData: {
      cellStyle: {
        verticalAlignment: cell.style?.verticalAlign?.toUpperCase(),
        backgroundColor: normalizeTableColorValue(cell.style?.backgroundColor)
      },
      borderColors: {
        top: normalizeTableColorValue(cell.border?.top),
        left: normalizeTableColorValue(cell.border?.left),
        right: normalizeTableColorValue(cell.border?.right),
        bottom: normalizeTableColorValue(cell.border?.bottom)
      }
    },
    nodes: fromDraft(cell.content, opts).nodes
  }))
}));
const nestedNodesConverters = {
  [import_v1.Node_Type.COLLAPSIBLE_LIST]: parseCollapsible,
  [import_v1.Node_Type.TABLE]: parseTable
};
const normalizeBlock = (block) => {
  if (block.type === "atomic" && block.text.startsWith(" ") && block.text.trim() !== "" && block.text?.length > 1) {
    block.type = "unstyled";
  }
  block.depth = block.depth || 0;
  block.entityRanges = block.entityRanges || [];
  block.inlineStyleRanges = (block.inlineStyleRanges || []).filter((range) => range.offset >= 0).map((range) => {
    if (range.style.startsWith("#") || range.style.startsWith("$theme-color-")) {
      return {
        ...range,
        style: `{"FG":"${range.style}"}`
      };
    }
    try {
      const parsedStyle = JSON.parse(range.style);
      if ("font-size" in parsedStyle) {
        const [value, unit] = parsedStyle["font-size"].split(/(px|em)/gi);
        return {
          ...range,
          style: `{"font-size":"${parseInt(value, 10)}${unit}"}`
        };
      }
    } catch {
    }
    return range;
  });
};
const fromDraft = (draftJSON, opts = {}) => {
  const { blocks = [], entityMap = {}, documentStyle, ID: id } = import_lodash.default.cloneDeep(draftJSON);
  const nodes = [];
  const contentIdPrefix = Math.random().toString(36).substr(2, 9);
  const usedKeys = {};
  const withDepth = (block, depth = 0) => ({ ...block, depth });
  const ensureUniqueKey = (key) => {
    if (usedKeys[key]) {
      console.warn(`WARN! Duplicate block key "${key}"!`);
      key = (0, import_generate_random_id.generateId)();
    }
    usedKeys[key] = true;
    return key;
  };
  const parseBlock = (index) => {
    let block = blocks[index];
    if (!block) {
      return -1;
    }
    block = (0, import_remove_inline_header_ranges.removeInlineHeaderRanges)(block);
    normalizeBlock(block);
    switch (block.type) {
      case import_consts.BlockType.Atomic:
        const atomicBlocks = parseAtomicBlock(block);
        atomicBlocks?.forEach((atomicBlock) => {
          nodes.push(atomicBlock);
        });
        return index + 1;
      case import_consts.BlockType.Blockquote:
        nodes.push(parseQuoteBlock(block));
        return index + 1;
      case import_consts.BlockType.CodeBlock:
        nodes.push(parseCodeBlock(block));
        return index + 1;
      case import_consts.BlockType.HeaderOne:
      case import_consts.BlockType.HeaderTwo:
      case import_consts.BlockType.HeaderThree:
      case import_consts.BlockType.HeaderFour:
      case import_consts.BlockType.HeaderFive:
      case import_consts.BlockType.HeaderSix:
        nodes.push(parseHeadingBlock(block));
        return index + 1;
      case import_consts.BlockType.OrderedListItem:
      case import_consts.BlockType.UnorderedListItem:
        const { node, nextIndex } = parseListBlocks(index);
        nodes.push(node);
        return nextIndex;
      case void 0:
      case import_consts.BlockType.Unstyled:
        nodes.push(parseTextBlock(block));
        return index + 1;
      default:
        if (opts.ignoreUnsupportedValues) {
          return index + 1;
        } else {
          throw Error(`ERROR! Unknown block type "${block.type}"!`);
        }
    }
  };
  const parseAtomicBlock = (block) => {
    const { key, data, entityRanges } = block;
    if (entityRanges && entityRanges.length) {
      return entityRanges.map((entityRange) => {
        const entity = (0, import_get_ricos_entity_data.getEntity)(entityRange.key, entityMap);
        if (entity && entity.type) {
          switch (entity.type) {
            case import_v1.Decoration_Type.LINK:
            case import_v1.Decoration_Type.ANCHOR:
            case import_v1.Decoration_Type.MENTION: {
              return parseTextBlock(block);
            }
            default: {
              const nodes2 = nestedNodesConverters[entity.type]?.(
                entity,
                opts
              ) || [];
              if (!nodes2.length && (entity.type === import_v1.Node_Type.TABLE || entity.type === import_v1.Node_Type.COLLAPSIBLE_LIST)) {
                return null;
              }
              const shouldAddStyle = ![
                import_v1.Node_Type.IMAGE,
                import_v1.Node_Type.VIDEO,
                import_v1.Node_Type.DIVIDER,
                import_v1.Node_Type.HTML,
                import_v1.Node_Type.GALLERY,
                import_v1.Node_Type.BUTTON,
                import_v1.Node_Type.FILE,
                import_v1.Node_Type.COLLAPSIBLE_LIST,
                import_v1.Node_Type.GIF,
                import_v1.Node_Type.TABLE,
                import_v1.Node_Type.APP_EMBED,
                import_v1.Node_Type.POLL
              ].includes(entity.type);
              return {
                id: ensureUniqueKey(key),
                nodes: nodes2,
                ...shouldAddStyle ? { style: (0, import_get_ricos_entity_data.getNodeStyle)(data) } : {},
                ...entity
              };
            }
          }
        }
        return null;
      }).filter(isValidNode);
    }
    return null;
  };
  const isValidNode = (node) => node !== null;
  const parseQuoteBlock = (block) => ({
    id: ensureUniqueKey(block.key),
    type: import_v1.Node_Type.BLOCKQUOTE,
    nodes: [parseTextBlock(withDepth(block))],
    style: (0, import_get_ricos_entity_data.getNodeStyle)(block.data),
    blockquoteData: { indentation: block.depth }
  });
  const parseCodeBlock = (block) => ({
    id: ensureUniqueKey(block.key),
    type: import_v1.Node_Type.CODE_BLOCK,
    nodes: (0, import_get_text_nodes.getTextNodes)(block, entityMap, opts, false),
    style: (0, import_get_ricos_entity_data.getNodeStyle)(block.data),
    codeBlockData: {
      textStyle: (0, import_get_ricos_entity_data.getTextStyle)(block.data)
    }
  });
  const parseHeadingBlock = (block) => {
    const getLevel = (blockType) => {
      if (Object.keys(import_consts.HeaderLevel).includes(blockType)) {
        return import_consts.HeaderLevel[blockType];
      }
      throw Error(`ERROR! Unknown header level "${blockType}"!`);
    };
    return {
      id: ensureUniqueKey(block.key),
      type: import_v1.Node_Type.HEADING,
      headingData: {
        level: getLevel(block.type),
        indentation: block.depth,
        textStyle: (0, import_get_ricos_entity_data.getTextStyle)(block.data)
      },
      nodes: (0, import_get_text_nodes.getTextNodes)(block, entityMap, opts),
      style: (0, import_get_ricos_entity_data.getNodeStyle)(block.data)
    };
  };
  const parseTextBlock = (block) => {
    const paragraphNode = (0, import_node_utils.createParagraphNode)(
      [],
      { textStyle: (0, import_get_ricos_entity_data.getTextStyle)(block.data) },
      (0, import_get_ricos_entity_data.getNodeStyle)(block.data)
    );
    switch (block.type) {
      case import_consts.BlockType.Unstyled:
        paragraphNode.id = ensureUniqueKey(block.key);
      // falls through
      case void 0:
      case import_consts.BlockType.Atomic:
      case import_consts.BlockType.Blockquote:
        if (paragraphNode.paragraphData) {
          paragraphNode.paragraphData.indentation = parseDepth(block.depth);
        }
        break;
      case import_consts.BlockType.OrderedListItem:
      case import_consts.BlockType.UnorderedListItem:
        if (paragraphNode.paragraphData) {
          paragraphNode.paragraphData.indentation = parseDepth(block.depth);
        }
        paragraphNode.id = ensureUniqueKey(block.key);
        break;
      default:
    }
    const nodes2 = (0, import_get_text_nodes.getTextNodes)(block, entityMap, opts);
    if (!import_lodash.default.isEmpty(nodes2)) {
      paragraphNode.nodes = nodes2;
    }
    return paragraphNode;
  };
  const createListItem = (block) => ({
    id: (0, import_generate_random_id.generateId)(contentIdPrefix),
    type: import_v1.Node_Type.LIST_ITEM,
    nodes: [parseTextBlock(withDepth(block))]
  });
  const isListBlock = (block) => import_consts.FROM_DRAFT_LIST_TYPE[block.type] !== void 0;
  const parseListBlocks = (listStartIndex) => {
    const { type: listType, depth } = blocks[listStartIndex];
    const listNodes = [];
    let searchIndex = listStartIndex;
    let nextBlock = blocks[searchIndex];
    while (nextBlock && isListBlock(nextBlock) && nextBlock.depth >= depth) {
      normalizeBlock(nextBlock);
      if (nextBlock.depth > depth) {
        const { node, nextIndex } = parseListBlocks(searchIndex);
        const prevNode = listNodes[listNodes.length - 1];
        if (prevNode.nodes) {
          prevNode.nodes.push(node);
        } else {
          prevNode.nodes = [node];
        }
        searchIndex = nextIndex;
      } else if (nextBlock.type !== listType) {
        break;
      } else {
        listNodes.push(createListItem(nextBlock));
        searchIndex++;
      }
      nextBlock = blocks[searchIndex];
    }
    const listData = import_consts.FROM_DRAFT_LIST_TYPE[listType] === import_v1.Node_Type.ORDERED_LIST ? "orderedListData" : "bulletedListData";
    return {
      node: {
        id: (0, import_generate_random_id.generateId)(contentIdPrefix),
        type: import_consts.FROM_DRAFT_LIST_TYPE[listType],
        nodes: listNodes,
        [listData]: { indentation: depth }
      },
      nextIndex: searchIndex
    };
  };
  let i = 0;
  while (i !== -1) {
    i = parseBlock(i);
  }
  const content = {
    nodes,
    metadata: (0, import_node_utils.initializeMetadata)({ id }),
    documentStyle: documentStyle && (0, import_parse_doc_style.parseDocStyle)(documentStyle)
  };
  return import_v1.RichContent.fromJSON(content);
};
const parseDepth = (depth) => {
  if (isNaN(parseInt(depth.toString(), 10))) {
    return 0;
  }
  return parseInt(depth.toString(), 10);
};
//# sourceMappingURL=from-draft.js.map
