import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'iview';

Vue.use(VueRouter);

import AppLayout from './layouts/AppLayout.vue';
import EmployerLayout from './layouts/EmployerLayout.vue';

import Home from './views/Home.vue';
import Account from './views/Account.vue';
import Employer from './views/Employer.vue';
import LoginEmployer from './views/LoginEmployer.vue';
import PageNotFound from './views/PageNotFound.vue';
import Addjob from './views/Addjob.vue';
import RegisterEmployer from './views/RegisterEmployer';

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/employer',
      name: 'employerLayout',
      component: EmployerLayout,
      children: [
        {
          path: '',
          name: 'Employer',
          component: Employer
        },
        {
          path: 'login',
          name: 'loginEmployer',
          component: LoginEmployer
        },
        {
          path: 'register',
          name: 'registerEmployer',
          component: RegisterEmployer
        },
        {
          path: 'addjob',
          name: 'addjob',
          component: Addjob
        },
        {
          path: '*',
          name: '404Employer',
          component: PageNotFound
        }
      ]
    },
    {
      path: '/',
      name: 'appLayout',
      component: AppLayout,
      children: [
        {
          path: '',
          name: 'Home',
          component: Home
        },
        {
          path: 'account',
          name: 'account',
          component: Account
        },
        {
          path: '*',
          name: 'pageNotFound',
          component: PageNotFound,
          meta: {
            requiredUser: true
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  if(to.matched.some(record => record.meta.requiredUser)) {
    if(!localStorage.getItem('access_token')) {
      next('/employer/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

router.afterEach(route => {
  iView.LoadingBar.finish();
})

export default router