import Vue from 'vue'
import VueRouter from 'vue-router'
import menu from '/src/menu.json'

Vue.use(VueRouter)

function addMenu(list, item) {
  list.push(
    {
      path: item.to,
      name: item.label,
      meta: {
        role: item.role,
        description: item.description,
        icon: item.icon
      },
      component: () => import('/src/' + item.component)
    }
  )
}

var routes = []
menu.forEach(m => {
  if (m.menus) {
    m.menus.forEach(item => {addMenu(routes, item)})
  } else {
    addMenu(routes, m)
  }
});
routes.push({ path: "/403", component: () => import('/src/views/403.vue') })
routes.push({ path: "/404", component: () => import('/src/views/404.vue') })
routes.push({ path: "*", redirect: '/404'})

const router = new VueRouter({ routes })

router.beforeEach((to, from, next) => {
  if (to.meta.role) {
    let roles = (Vue.prototype.$keycloak) ? Vue.prototype.$keycloak.resourceAccess["leanisp-api"].roles : []
    if (roles.indexOf(to.meta.role) === -1) {
      next({ path: "/403" })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
