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

import type { RoutesName } from './constant'

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

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
