'use strict';

require('../../../../utils/index.cjs');
var util = require('../util.cjs');
var log = require('../../../../utils/log.cjs');
var props = require('../../../../utils/vue/props.cjs');
var camelize = require('../../../../utils/lang/camelize.cjs');
var omit = require('../../../../utils/lang/omit.cjs');

function getKey(key, pos) {
  if (key !== null && key !== void 0)
    return key;
  return pos;
}
function fillFieldNames(fieldNames) {
  const { title, _title, key, children } = fieldNames || {};
  const mergedTitle = title || "title";
  return {
    title: mergedTitle,
    _title: _title || [mergedTitle],
    key: key || "key",
    children: children || "children"
  };
}
function warningWithoutKey(treeData, fieldNames) {
  const keys = /* @__PURE__ */ new Map();
  function dig(list, path = "") {
    (list || []).forEach((treeNode) => {
      const key = treeNode[fieldNames.key];
      const children = treeNode[fieldNames.children];
      log.warning(
        key !== null && key !== void 0,
        `Tree node must have a certain key: [${path}${key}]`
      );
      const recordKey = String(key);
      log.warning(
        !keys.has(recordKey) || key === null || key === void 0,
        `Same 'key' exist in the Tree: ${recordKey}`
      );
      keys.set(recordKey, true);
      dig(children, `${path}${recordKey} > `);
    });
  }
  dig(treeData);
}
function convertTreeToData(rootNodes) {
  function dig(node = []) {
    const treeNodes = props.filterEmpty(node);
    return treeNodes.map((treeNode) => {
      var _a, _b, _c, _d;
      if (!util.isTreeNode(treeNode)) {
        log.warning(!treeNode, "Tree/TreeNode can only accept TreeNode as children.");
        return null;
      }
      const slots = treeNode.children || {};
      const key = treeNode.key;
      const props = {};
      for (const [k, v] of Object.entries(treeNode.props))
        props[camelize.camelize(k)] = v;
      const { isLeaf, checkable, selectable, disabled, disableCheckbox } = props;
      const newProps = {
        isLeaf: isLeaf || isLeaf === "" || void 0,
        checkable: checkable || checkable === "" || void 0,
        selectable: selectable || selectable === "" || void 0,
        disabled: disabled || disabled === "" || void 0,
        disableCheckbox: disableCheckbox || disableCheckbox === "" || void 0
      };
      const slotsProps = { ...props, ...newProps };
      const {
        title = (_a = slots.title) == null ? void 0 : _a.call(slots, slotsProps),
        icon = (_b = slots.icon) == null ? void 0 : _b.call(slots, slotsProps),
        switcherIcon = (_c = slots.switcherIcon) == null ? void 0 : _c.call(slots, slotsProps),
        ...rest
      } = props;
      const children = (_d = slots.default) == null ? void 0 : _d.call(slots);
      const dataNode = {
        ...rest,
        title,
        icon,
        switcherIcon,
        key,
        isLeaf,
        ...newProps
      };
      const parsedChildren = dig(children);
      if (parsedChildren.length)
        dataNode.children = parsedChildren;
      return dataNode;
    });
  }
  return dig(rootNodes);
}
function flattenTreeData(treeNodeList, expandedKeys, fieldNames) {
  const {
    _title: fieldTitles,
    key: fieldKey,
    children: fieldChildren
  } = fillFieldNames(fieldNames);
  const expandedKeySet = new Set(expandedKeys === true ? [] : expandedKeys);
  const flattenList = [];
  function dig(list, parent = null) {
    return list.map((treeNode, index) => {
      const pos = util.getPosition(parent ? parent.pos : "0", index);
      const mergedKey = getKey(treeNode[fieldKey], pos);
      let mergedTitle;
      for (let i = 0; i < fieldTitles.length; i += 1) {
        const fieldTitle = fieldTitles[i];
        if (treeNode[fieldTitle] !== void 0) {
          mergedTitle = treeNode[fieldTitle];
          break;
        }
      }
      const flattenNode = {
        ...omit.omit(treeNode, [...fieldTitles, fieldKey, fieldChildren]),
        title: mergedTitle,
        key: mergedKey,
        parent,
        pos,
        children: null,
        data: treeNode,
        isStart: [...parent ? parent.isStart : [], index === 0],
        isEnd: [...parent ? parent.isEnd : [], index === list.length - 1]
      };
      flattenList.push(flattenNode);
      if (expandedKeys === true || expandedKeySet.has(mergedKey))
        flattenNode.children = dig(treeNode[fieldChildren] || [], flattenNode);
      else
        flattenNode.children = [];
      return flattenNode;
    });
  }
  dig(treeNodeList);
  return flattenList;
}
function traverseDataNodes(dataNodes, callback, config) {
  let mergedConfig = {};
  if (typeof config === "object")
    mergedConfig = config;
  else
    mergedConfig = { externalGetKey: config };
  mergedConfig = mergedConfig || {};
  const { childrenPropName, externalGetKey, fieldNames } = mergedConfig;
  const { key: fieldKey, children: fieldChildren } = fillFieldNames(fieldNames);
  const mergeChildrenPropName = childrenPropName || fieldChildren;
  let syntheticGetKey;
  if (externalGetKey) {
    if (typeof externalGetKey === "string")
      syntheticGetKey = (node) => node[externalGetKey];
    else if (typeof externalGetKey === "function")
      syntheticGetKey = (node) => externalGetKey(node);
  } else {
    syntheticGetKey = (node, pos) => getKey(node[fieldKey], pos);
  }
  function processNode(node, index, parent, pathNodes) {
    const children = node ? node[mergeChildrenPropName] : dataNodes;
    const pos = node ? util.getPosition(parent.pos, index) : "0";
    const connectNodes = node ? [...pathNodes, node] : [];
    if (node) {
      const key = syntheticGetKey(node, pos);
      const data = {
        node,
        index,
        pos,
        key,
        parentPos: parent.node ? parent.pos : null,
        level: parent.level + 1,
        nodes: connectNodes
      };
      callback(data);
    }
    if (children) {
      children.forEach((subNode, subIndex) => {
        processNode(
          subNode,
          subIndex,
          {
            node,
            pos,
            level: parent ? parent.level + 1 : -1
          },
          connectNodes
        );
      });
    }
  }
  processNode(null);
}
function convertDataToEntities(dataNodes, {
  initWrapper,
  processEntity,
  onProcessFinished,
  externalGetKey,
  childrenPropName,
  fieldNames
} = {}, legacyExternalGetKey) {
  const mergedExternalGetKey = externalGetKey || legacyExternalGetKey;
  const posEntities = {};
  const keyEntities = {};
  let wrapper = {
    posEntities,
    keyEntities
  };
  if (initWrapper)
    wrapper = initWrapper(wrapper) || wrapper;
  traverseDataNodes(
    dataNodes,
    (item) => {
      const { node, index, pos, key, parentPos, level, nodes } = item;
      const entity = { node, nodes, index, key, pos, level };
      const mergedKey = getKey(key, pos);
      posEntities[pos] = entity;
      keyEntities[mergedKey] = entity;
      entity.parent = posEntities[parentPos];
      if (entity.parent) {
        entity.parent.children = entity.parent.children || [];
        entity.parent.children.push(entity);
      }
      if (processEntity)
        processEntity(entity, wrapper);
    },
    { externalGetKey: mergedExternalGetKey, childrenPropName, fieldNames }
  );
  if (onProcessFinished)
    onProcessFinished(wrapper);
  return wrapper;
}
function getTreeNodeProps(key, {
  expandedKeysSet,
  selectedKeysSet,
  loadedKeysSet,
  loadingKeysSet,
  checkedKeysSet,
  halfCheckedKeysSet,
  dragOverNodeKey,
  dropPosition,
  keyEntities
}) {
  const entity = keyEntities[key];
  const treeNodeProps = {
    eventKey: key,
    expanded: expandedKeysSet.has(key),
    selected: selectedKeysSet.has(key),
    loaded: loadedKeysSet.has(key),
    loading: loadingKeysSet.has(key),
    checked: checkedKeysSet.has(key),
    halfChecked: halfCheckedKeysSet.has(key),
    pos: String(entity ? entity.pos : ""),
    parent: entity.parent,
    // [Legacy] Drag props
    // Since the interaction of drag is changed, the semantic of the props are
    // not accuracy, I think it should be finally removed
    dragOver: dragOverNodeKey === key && dropPosition === 0,
    dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,
    dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1
  };
  return treeNodeProps;
}
function convertNodePropsToEventData(props) {
  const {
    data,
    expanded,
    selected,
    checked,
    loaded,
    loading,
    halfChecked,
    dragOver,
    dragOverGapTop,
    dragOverGapBottom,
    pos,
    active,
    eventKey
  } = props;
  const eventData = {
    dataRef: data,
    ...data,
    expanded,
    selected,
    checked,
    loaded,
    loading,
    halfChecked,
    dragOver,
    dragOverGapTop,
    dragOverGapBottom,
    pos,
    active,
    eventKey,
    key: eventKey
  };
  if (!("props" in eventData)) {
    Object.defineProperty(eventData, "props", {
      get() {
        log.warning(
          false,
          "Second param return from event is node data instead of TreeNode instance. Please read value directly instead of reading from `props`."
        );
        return props;
      }
    });
  }
  return eventData;
}

exports.convertDataToEntities = convertDataToEntities;
exports.convertNodePropsToEventData = convertNodePropsToEventData;
exports.convertTreeToData = convertTreeToData;
exports.fillFieldNames = fillFieldNames;
exports.flattenTreeData = flattenTreeData;
exports.getKey = getKey;
exports.getTreeNodeProps = getTreeNodeProps;
exports.traverseDataNodes = traverseDataNodes;
exports.warningWithoutKey = warningWithoutKey;
//# sourceMappingURL=treeUtil.cjs.map
