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 EditCompany from './views/EditCompany.vue';
import RegisterEmployer from './views/RegisterEmployer';
import ManagejobEmployer from './views/managejob.vue'

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: 'managejob',
          name: 'managejobEmployer',
          component: ManagejobEmployer
        },
        {
          path: 'editcompany',
          name: 'editcompany',
          component: EditCompany
        },
        {
          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