import {
  constantRoutes,
  asyncRoutes
} from '@/router'
import { Role } from '@/constant'

function hasPermission (accessSet, access) {
  return !access || (Array.isArray(access) ? access.some(item => accessSet.has(item)) : accessSet.has(access))
}

export function filterAsyncRoutes (routes, accessSet) {
  const res = []

  routes.forEach(route => {
    if (!route.dev && hasPermission(accessSet, route.access)) {
      if (route.children) {
        const children = filterAsyncRoutes(route.children, accessSet)
        if (!children.length) {
          return
        }
        res.push({ ...route, children })
      } else {
        res.push({ ...route })
      }
    }
  })

  return res
}

const state = {
  routes: []
}

const mutations = {
  SET_ROUTES (state, routes) {
    state.routes = routes
  }
}

const actions = {
  generateRoutes ({ commit }, { roles, accesses }) {
    let accessedRoutes
    if (__DEV__ && roles.has(Role.SUPER_ADMIN)) {
      accessedRoutes = asyncRoutes
    } else {
      accessedRoutes = filterAsyncRoutes(asyncRoutes, accesses)
    }
    commit('SET_ROUTES', constantRoutes.concat(accessedRoutes))
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
