import { inject, computed, h } from 'vue';
import { MenuContextKey } from "./Menu";
import MenuItem from './MenuItem';
import MenuItemGroup from './MenuItemGroup';
import Submenu, { submenuContextKey } from "./Submenu";
export function useMenu(props) {
  const menuContext = inject(MenuContextKey);
  const submenuContext = inject(submenuContextKey);
  const {
    props: menuProps
  } = menuContext;
  const isRoot = menuContext && !submenuContext;
  const horizontalRef = computed(() => {
    return menuProps.mode === 'horizontal';
  });
  const inlineRef = computed(() => {
    return menuProps.mode === 'inline';
  });
  const indentRef = computed(() => {
    return horizontalRef.value ? 0 : menuProps.indent;
  });
  const parentPaddingLeftRef = computed(() => {
    if (menuContext.collapsedRef.value) return 0;
    if (isRoot) return 0;

    if (submenuContext) {
      return submenuContext.paddingLeftRef.value;
    }
  });
  const paddingLeftRef = computed(() => {
    if (horizontalRef.value) return undefined;
    if (!inlineRef.value) return undefined;
    return parentPaddingLeftRef.value + indentRef.value;
  });
  const disabledRef = computed(() => {
    return menuContext.props.disabled || (submenuContext === null || submenuContext === void 0 ? void 0 : submenuContext.props.disabled) || props.disabled;
  });
  const isActiveRef = computed(() => {
    return menuContext.activePathRef.value.includes(props.value);
  });
  return {
    menuContext,
    submenuContext,
    horizontalRef,
    inlineRef,
    indentRef,
    parentPaddingLeftRef,
    paddingLeftRef,
    disabledRef,
    isActiveRef,
    isRoot
  };
}
export function createItem(node) {
  if (node.children) {
    if (node.type === 'group') {
      return h(MenuItemGroup, { ...node,
        node,
        value: node.key
      });
    } else {
      return h(Submenu, { ...node,
        node,
        value: node.key
      });
    }
  } else {
    return h(MenuItem, { ...node,
      node,
      value: node.key
    });
  }
} // ========================== Tree ==========================

export function traverseTree(tree, cb) {
  tree === null || tree === void 0 ? void 0 : tree.forEach(opt => {
    if (tree.children) traverseTree(tree.children, cb);
    cb(opt);
  });
}
export function getNonLeafKeys(tree) {
  const keys = [];
  traverseTree(tree, opt => keys.push(opt.key));
  return keys;
}
export function treeFindPath(tree, func, path = []) {
  for (const item of tree) {
    var _item$children;

    path.push(item.key);
    if (func(item)) return path;

    if ((_item$children = item.children) !== null && _item$children !== void 0 && _item$children.length) {
      const children = treeFindPath(item.children, func, path);
      if (children.length) return children;
    }

    path.pop();
  }

  return [];
}