import { computed, inject, provide, ref } from "vue";
import { isUndefined } from "lodash-es";
import { useRoute, useRouter } from "#imports";
export const MenuKey = Symbol.for("ramacare:menu");
export function routeToMenuItem(route) {
  let menuItem;
  if (!isUndefined(route.meta) && !isUndefined(route.meta?.menuItem)) {
    const menuMeta = route.meta?.menuItem;
    menuItem = {
      title: menuMeta.title,
      icon: menuMeta.icon,
      role: menuMeta.role,
      name: route.name?.toString() || "",
      image: menuMeta.image,
      menuItems: [],
      link: {
        name: route.name
      },
      active: menuMeta.active != void 0 ? menuMeta.active : true
    };
    if (route.children) {
      const menuItems = new Array();
      for (const children of route.children.sort((a, b) => (a.name?.toString() ?? "").localeCompare(b.name?.toString() ?? ""))) {
        const childMenuItem = routeToMenuItem(children);
        if (childMenuItem) menuItems.push(childMenuItem);
        menuItem.menuItems = menuItems;
      }
    }
  }
  return menuItem;
}
export function createMenu() {
  const menuAll = ref([]);
  const routes = useRouter().getRoutes().sort((a, b) => (a.name?.toString() ?? "").localeCompare(b.name?.toString() ?? ""));
  for (const route of routes) {
    const paths = route.path.split("/");
    if (paths.length == 2) {
      if (route.path != "/login" && route.path != "/") {
        const menuItem = routeToMenuItem(route);
        if (menuItem) menuAll.value.push(menuItem);
      }
    }
  }
  provide(MenuKey, {
    menuByRoute: computed(() => {
      const route = useRoute();
      for (const menuItem of menuAll.value) {
        if (menuItem.name == route.path.split("/")[1]) {
          return menuItem.menuItems;
        }
      }
      return [];
    }),
    menuAll
  });
}
export function useMenu() {
  return inject(MenuKey, null);
}
