import Vue from 'vue'
import Router from 'vue-router'
import SecurityService from '@/plugins/security'
import { APP_CLASSES } from '@/store/utils/localStorageKeys'
import appStatus from './app-status'

const requireComponent = require.context(
  // Look for files in the current directory
  '../app',
  // Look in  subdirectories
  true,
  // Only include "_base-" prefixed .vue files
  /router.js$/
)

let routes = []
// For each matching file name...
requireComponent.keys().forEach(fileName => {
  // Can use _ to turn route off
  if (fileName.indexOf('_') === -1) {
    routes = [...routes, ...requireComponent(fileName).default]
  }
})

Vue.use(Router)

const router = new Router({
  base: process.env.NODE_ENV === 'production' && process.env.VUE_APP_PUBLIC_PATH ? process.env.VUE_APP_PUBLIC_PATH : '',
  linkActiveClass: 'open active',
  routes: routes,
  mode: 'history',
  scrollBehavior() {
    return { x: 0, y: 0 }
  },
})

// Capture route transition
router.beforeEach((to, from, next) => {
  if (router.app !== null && typeof router.app.$analytics === 'function') {
    router.app.$analytics(to.fullPath)
  }

  // Redirect to / when route is disabled
  if (to.matched.some(route => route.meta.disabled)) {
    return next({ path: '/' })
  }

  // Set the app statuses of the application
  return appStatus(router.app, to, from).then(() => {
    return next(SecurityService.check(to))
  })
})

router.afterEach((to, from) => {
  let app = document.querySelector('#app')
  let body = document.querySelector('body')
  if (app !== null && body !== null) {
    app.removeAttribute('screen')
    body.removeAttribute('page-screen')

    let matchedRoutes = Object.assign([], to.matched)
    let screened = matchedRoutes.reverse().find(function(route) {
      if (typeof route.meta.screen !== 'undefined') {
        return route
      }
    })
    // look in template
    if (typeof screened === 'undefined') {
      screened = matchedRoutes.reverse().find(function(route) {
        if (typeof route.meta.template !== 'undefined' && typeof route.meta.template.screen !== 'undefined') {
          return route
        }
      })
    }
    if (typeof screened !== 'undefined') {
      app.setAttribute('screen', screened.meta.screen || screened.meta.template.screen)
      body.setAttribute('page-screen', screened.meta.screen || screened.meta.template.screen)
    }
    let appClasses = localStorage.getItem(APP_CLASSES) || ''
    body.className = (body.className + ' ' + appClasses)
      .split(' ')
      .filter(itemClass => itemClass.trim() !== '')
      .join(' ')
  }
})
export default router
