import { createRouter, createWebHashHistory } from "vue-router";
import { Routes, routes, system, Route } from "./config";
import { RouteName } from "./routeName";

export * from "./config";
export * from "./routeName";
export const router = createRouter({
  history: createWebHashHistory(),
  routes: routes as any,
});

router.beforeEach((to, from, next) => {
  console.log(to.name, 'to.name1', to, RouteName.viewLayout);
  if (!to.name || to.name === RouteName.viewLayout) {
    router.replace({ name: RouteName.scene });
    return;
  }
  next();
});

const getConfig = (routes: Routes) => {
  let config: Routes = [];

  for (let item of routes) {
    if (!system.includes(item)) {
      config.push({
        ...item,
        children: item.children && getConfig(item.children),
      });
    }
  }

  return config;
};

export const routeIsSystem = (proutes = routes) => {
  for (let item of proutes) {
    if (!system.includes(item)) {
      if (item.name === router.currentRoute.value?.name) {
        return false;
      } else if (item.children && !routeIsSystem(item.children)) {
        return false;
      }
    }
  }

  return true;
};

export const findRoute = (
  routeName: string,
  fullPath = false,
  routeAll = routes
): Route | null => {
  for (const route of routeAll) {
    if (route.name === routeName) {
      return route;
    } else if (route.children) {
      const childRoute = findRoute(routeName, fullPath, route.children);
      if (childRoute) {
        return fullPath ? { ...route, children: [childRoute] } : childRoute;
      }
    }
  }
  return null;
};
