import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './config'
import { computed, ref } from 'vue'
import { routesMetas, routeTrees } from './constant'

import { RoutesName } from './constant'

export const history = createWebHashHistory()
export const router = createRouter({ history, routes: routes as any })

const defaultRouteName = RoutesName.projects
const enables = ref<RoutesName[]>([])
export const enableRouteNames = (routerNames: RoutesName[]) => {
  enables.value = routerNames
  const current = router.currentRoute.value.name
  if (current && !enables.value.includes(current as RoutesName)) {
    router.replace(defaultRouteName)
  }
}

router.beforeEach((to, from) => {
  if (to.name === defaultRouteName) {
    return true
  }
  const goto = enables.value.includes(to.name as RoutesName)
  if (goto) {
    return true
  }
  if (!from || !enables.value.includes(from.name as RoutesName)) {
    router.replace({ name: defaultRouteName })
  }
  return false
})

export const getRouteTreePaths = (
  name: RoutesName = router.currentRoute.value.name as RoutesName,
  trees = routeTrees
): RoutesName[] => {
  for (const tree of trees) {
    if (tree.name === name) {
      return [tree.name]
    } else if (tree.children) {
      const childTreePaths = getRouteTreePaths(name, tree.children)
      if (childTreePaths.length) {
        return [tree.name, ...childTreePaths]
      }
    }
  }
  return []
}

export const currentMeta = computed(() => {
  const currentName = router.currentRoute.value.name as RoutesName
  if (currentName && currentName in routesMetas) {
    return routesMetas[currentName]
  }
})

export * from './config'
export * from './constant'

export default router
