import { match } from "path-to-regexp";
import { DageRouteItem, DEFAULT_MENU, DEFAULT_ADMIN_MENU } from "@/router";

const routes = [...DEFAULT_MENU, ...DEFAULT_ADMIN_MENU];

export const findRouteParent = (
  route: DageRouteItem | null,
  list: DageRouteItem[]
): DageRouteItem | null => {
  if (!route) return null;

  for (const r of list) {
    if (r.children && r.children.includes(route)) {
      if (r.hide) {
        return findRouteParent(r, list);
      }
      return r;
    }
    if (r.children) {
      const parent = findRouteParent(route, r.children);
      if (parent) return parent;
    }
  }
  return null;
};

export const findVisibleRouteParent = (
  list: DageRouteItem[],
  targetPath: string
): DageRouteItem | null => {
  let result: DageRouteItem | null = null;

  const targetNode = findRouteByPath(list, targetPath);
  if (targetNode) {
    result = findRouteParent(targetNode, list);
  }

  return result;
};

export const findRouteByPath = (
  list = routes,
  path: string
): DageRouteItem | null => {
  for (const route of list) {
    const isMatch = match(route.path, { decode: decodeURIComponent });
    if (isMatch(path)) {
      return route;
    }
    if (route.children) {
      const subRoute = findRouteByPath(route.children, path);
      if (subRoute) {
        return subRoute;
      }
    }
  }
  return null;
};
