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;

  function search(list: DageRouteItem[], path: string): DageRouteItem | null {
    for (const route of list) {
      if (route.path === path) {
        return route;
      }
      if (route.children) {
        const found = search(route.children, path);
        if (found) {
          return found;
        }
      }
    }
    return null;
  }

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

  return result;
};

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