"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.transformToTaskList = exports.transformTaskListToBlockNodes = exports.transformListStructure = exports.transformListRecursively = exports.transformBetweenListTypes = exports.getFormattedNode = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _model = require("@atlaskit/editor-prosemirror/model");
var _utils = require("@atlaskit/editor-prosemirror/utils");
var _listUtils = require("./list-utils");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var getContentSupportChecker = function getContentSupportChecker(targetNodeType) {
  return function (node) {
    try {
      return targetNodeType.validContent(_model.Fragment.from(node));
    } catch (_unused) {
      return false;
    }
  };
};
var _transformListRecursively = exports.transformListRecursively = function transformListRecursively(props, onhandleUnsupportedContent) {
  var transformedItems = [];
  var listNode = props.listNode,
    isSourceBulletOrOrdered = props.isSourceBulletOrOrdered,
    isTargetBulletOrOrdered = props.isTargetBulletOrOrdered,
    isSourceTask = props.isSourceTask,
    isTargetTask = props.isTargetTask,
    supportedListTypes = props.supportedListTypes,
    schema = props.schema,
    targetNodeType = props.targetNodeType;
  var _schema$nodes = schema.nodes,
    taskList = _schema$nodes.taskList,
    listItem = _schema$nodes.listItem,
    taskItem = _schema$nodes.taskItem,
    paragraph = _schema$nodes.paragraph;
  listNode.forEach(function (child) {
    if (isSourceBulletOrOrdered && isTargetTask) {
      // Convert bullet/ordered => task
      if (child.type === listItem) {
        var inlineContent = [];
        var nestedTaskLists = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== taskList) {
            nestedTaskLists.push(_transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent));
          } else if (!getContentSupportChecker(taskItem)(grandChild) && !grandChild.isTextblock) {
            onhandleUnsupportedContent === null || onhandleUnsupportedContent === void 0 || onhandleUnsupportedContent(grandChild);
          } else {
            inlineContent.push.apply(inlineContent, (0, _toConsumableArray2.default)((0, _listUtils.convertBlockToInlineContent)(grandChild, schema)));
          }
        });
        transformedItems.push(taskItem.create(null, inlineContent.length > 0 ? inlineContent : null));
        transformedItems.push.apply(transformedItems, nestedTaskLists);
      }
    } else if (isSourceTask && isTargetBulletOrOrdered) {
      // Convert task => bullet/ordered
      if (child.type === taskItem) {
        var _inlineContent = (0, _toConsumableArray2.default)(child.content.content);
        var paragraphNode = paragraph.create(null, _inlineContent.length > 0 ? _inlineContent : null);
        transformedItems.push(listItem.create(null, [paragraphNode]));
      } else if (child.type === taskList) {
        var transformedNestedList = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
          listNode: child
        }), onhandleUnsupportedContent);
        var lastItem = transformedItems[transformedItems.length - 1];
        if ((lastItem === null || lastItem === void 0 ? void 0 : lastItem.type) === listItem) {
          // Attach nested list to previous item
          var updatedContent = [].concat((0, _toConsumableArray2.default)(lastItem.content.content), [transformedNestedList]);
          transformedItems[transformedItems.length - 1] = listItem.create(lastItem.attrs, updatedContent);
        } else {
          // No previous item, flatten nested items
          transformedItems.push.apply(transformedItems, (0, _toConsumableArray2.default)(transformedNestedList.content.content));
        }
      }
    } else if (isSourceBulletOrOrdered && isTargetBulletOrOrdered) {
      if (child.type === listItem) {
        var convertedNestedLists = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== targetNodeType) {
            var convertedNode = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent);
            convertedNestedLists.push(convertedNode);
          } else {
            convertedNestedLists.push(grandChild);
          }
        });
        transformedItems.push(listItem.create(null, convertedNestedLists));
      }
    }
  });
  return targetNodeType.create(null, transformedItems);
};

/**
 * Transform list structure between different list types
 */
var transformListStructure = exports.transformListStructure = function transformListStructure(context) {
  var tr = context.tr,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos,
    targetNodeType = context.targetNodeType;
  var nodes = tr.doc.type.schema.nodes;
  var unsupportedContent = [];
  var onhandleUnsupportedContent = function onhandleUnsupportedContent(content) {
    unsupportedContent.push(content);
  };
  try {
    var listNode = {
      node: sourceNode,
      pos: sourcePos
    };
    var sourceList = listNode.node,
      listPos = listNode.pos;
    // const { taskList, listItem, taskItem, paragraph } = nodes;

    var isSourceBulletOrOrdered = (0, _listUtils.isBulletOrOrderedList)(sourceList.type);
    var isTargetTask = (0, _listUtils.isTaskList)(targetNodeType);
    var isSourceTask = (0, _listUtils.isTaskList)(sourceList.type);
    var isTargetBulletOrOrdered = (0, _listUtils.isBulletOrOrderedList)(targetNodeType);
    var supportedListTypes = (0, _listUtils.getSupportedListTypesSet)(nodes);
    var newList = _transformListRecursively({
      isSourceBulletOrOrdered: isSourceBulletOrOrdered,
      isSourceTask: isSourceTask,
      isTargetBulletOrOrdered: isTargetBulletOrOrdered,
      isTargetTask: isTargetTask,
      listNode: sourceList,
      schema: tr.doc.type.schema,
      supportedListTypes: supportedListTypes,
      targetNodeType: targetNodeType
    }, onhandleUnsupportedContent);
    tr.replaceWith(listPos, listPos + sourceList.nodeSize, [newList].concat(unsupportedContent));
    return tr;
  } catch (_unused2) {
    return tr;
  }
};

/**
 * Transform between different list types
 */
var transformBetweenListTypes = exports.transformBetweenListTypes = function transformBetweenListTypes(context) {
  var tr = context.tr,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos,
    targetNodeType = context.targetNodeType;
  var nodes = tr.doc.type.schema.nodes;
  var sourceListType = sourceNode.type;
  var isSourceBulletOrOrdered = (0, _listUtils.isBulletOrOrderedList)(sourceListType);
  var isTargetTask = (0, _listUtils.isTaskList)(targetNodeType);
  var isSourceTask = (0, _listUtils.isTaskList)(sourceListType);
  var isTargetBulletOrOrdered = (0, _listUtils.isBulletOrOrderedList)(targetNodeType);

  // Check if we need structure transformation
  var needsStructureTransform = isSourceBulletOrOrdered && isTargetTask || isSourceTask && isTargetBulletOrOrdered;
  try {
    if (!needsStructureTransform) {
      // Simple type change for same structure lists (bullet <-> ordered)
      // Apply to the main list
      tr.setNodeMarkup(sourcePos, targetNodeType);

      // Apply to nested lists
      var listStart = sourcePos;
      var listEnd = sourcePos + sourceNode.nodeSize;
      var supportedListTypesSet = (0, _listUtils.getSupportedListTypesSet)(nodes);
      tr.doc.nodesBetween(listStart, listEnd, function (node, pos, parent) {
        // Only process nested lists (not the root list we already handled)
        if (supportedListTypesSet.has(node.type) && pos !== sourcePos) {
          var isNestedList = parent && (supportedListTypesSet.has(parent.type) || parent.type === nodes.listItem);
          if (isNestedList) {
            var shouldTransformNode = node.type === sourceListType || (0, _listUtils.isBulletOrOrderedList)(node.type) && isTargetBulletOrOrdered;
            if (shouldTransformNode) {
              tr.setNodeMarkup(pos, targetNodeType);
            }
          }
        }
        return true; // Continue traversing
      });
      return tr;
    } else {
      return transformListStructure(context);
    }
  } catch (_unused3) {
    return null;
  }
};

/**
 * Transform selection to task list
 * Handles the special structure where taskItem contains text directly (no paragraph wrapper)
 */
var transformToTaskList = exports.transformToTaskList = function transformToTaskList(tr, range, targetNodeType, targetAttrs, nodes) {
  try {
    var taskItem = nodes.taskItem;
    var listItems = [];

    // Process each block in the range
    tr.doc.nodesBetween(range.start, range.end, function (node) {
      if (node.isBlock) {
        // For block nodes like paragraphs, directly use their inline content
        var inlineContent = (0, _toConsumableArray2.default)(node.content.content);
        if (inlineContent.length > 0) {
          // Create task item with inline content directly
          var listItem = taskItem.create(targetAttrs, inlineContent);
          listItems.push(listItem);
        }
      }
      return false; // Don't traverse into children
    });
    if (listItems.length === 0) {
      return null;
    }

    // Create the new task list
    var newList = targetNodeType.create(targetAttrs, listItems);

    // Replace the range with the new list
    tr.replaceWith(range.start, range.end, newList);
    return tr;
  } catch (_unused4) {
    return null;
  }
};
var transformTaskListToBlockNodes = exports.transformTaskListToBlockNodes = function transformTaskListToBlockNodes(context) {
  var tr = context.tr,
    targetNodeType = context.targetNodeType,
    targetAttrs = context.targetAttrs,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos;
  var selection = tr.selection;
  var schema = selection.$from.doc.type.schema;
  var taskItemsResult = (0, _utils.findChildrenByType)(sourceNode, schema.nodes.taskItem);
  var taskItems = taskItemsResult.map(function (item) {
    return item.node;
  });
  var taskItemFragments = taskItems.map(function (taskItem) {
    return taskItem.content;
  });
  var targetNodes = [];

  // Convert fragments to headings if target is heading
  if (targetNodeType === schema.nodes.heading && targetAttrs) {
    // convert the fragments to headings
    var targetHeadingLevel = targetAttrs.level;
    targetNodes = taskItemFragments.map(function (fragment) {
      return schema.nodes.heading.createChecked({
        level: targetHeadingLevel
      }, fragment.content);
    });
  }

  // Convert fragments to paragraphs if target is paragraphs
  if (targetNodeType === schema.nodes.paragraph) {
    // convert the fragments to paragraphs
    targetNodes = taskItemFragments.map(function (fragment) {
      return schema.nodes.paragraph.createChecked({}, fragment.content);
    });
  }

  // Convert fragments to code block if target is code block
  if (targetNodeType === schema.nodes.codeBlock) {
    // convert the fragments to one code block
    var codeBlockContent = taskItemFragments.map(function (fragment) {
      return fragment.textBetween(0, fragment.size, '\n');
    }).join('\n');
    targetNodes = [schema.nodes.codeBlock.createChecked({}, schema.text(codeBlockContent))];
  }

  // Replace the task list node with the new content in the transaction
  var slice = new _model.Slice(_model.Fragment.fromArray(targetNodes), 0, 0);
  var rangeStart = sourcePos !== null ? sourcePos : selection.from;
  tr.replaceRange(rangeStart, rangeStart + sourceNode.nodeSize, slice);
  return tr;
};
var getFormattedNode = exports.getFormattedNode = function getFormattedNode(tr) {
  var selection = tr.selection;
  var nodes = tr.doc.type.schema.nodes;

  // Find the node to format from the current selection
  var nodeToFormat;
  var nodePos = selection.from;

  // Try to find the current node from selection
  var selectedNode = (0, _utils.findSelectedNodeOfType)([nodes.paragraph, nodes.heading, nodes.blockquote, nodes.panel, nodes.expand, nodes.codeBlock, nodes.bulletList, nodes.orderedList, nodes.taskList, nodes.layoutSection])(selection);
  if (selectedNode) {
    nodeToFormat = selectedNode.node;
    nodePos = selectedNode.pos;
  } else {
    // Try to find parent node (including list parents)
    var parentNode = (0, _utils.findParentNodeOfType)([nodes.blockquote, nodes.panel, nodes.expand, nodes.codeBlock, nodes.listItem, nodes.taskItem, nodes.layoutSection])(selection);
    if (parentNode) {
      nodeToFormat = parentNode.node;
      nodePos = parentNode.pos;
      var paragraphOrHeadingNode = (0, _utils.findParentNodeOfType)([nodes.paragraph, nodes.heading])(selection);
      // Special case: if we found a listItem, check if we need the parent list instead
      if (parentNode.node.type === nodes.listItem || parentNode.node.type === nodes.taskItem) {
        var listParent = (0, _utils.findParentNodeOfType)([nodes.bulletList, nodes.orderedList, nodes.taskList])(selection);
        if (listParent) {
          // For list transformations, we want the list parent, not the listItem
          nodeToFormat = listParent.node;
          nodePos = listParent.pos;
        }
      } else if (parentNode.node.type !== nodes.blockquote && paragraphOrHeadingNode) {
        nodeToFormat = paragraphOrHeadingNode.node;
        nodePos = paragraphOrHeadingNode.pos;
      }
    }
  }
  if (!nodeToFormat) {
    nodeToFormat = selection.$from.node();
    nodePos = selection.$from.pos;
  }
  return {
    node: nodeToFormat,
    pos: nodePos
  };
};