/*********************************************************
 *
 * The Vue Router - index.js
 *
 * This file contains all of the "routes" used in the
 * vue-router. As more views are required, add them
 * following the pattern in the routes array of the new
 * VueRouter instance and import the file directly into
 * this one.
 *
 ********************************************************/

import Vue from 'vue';

import VueRouter from 'vue-router';

import Master from '../views/Master.vue';
import Dashboard from '../views/Dashboard.vue';
import Customization from '../views/Customization.vue';
import Pages from '../views/Pages.vue';
import Page from '../views/Page.vue';
import FileLibrary from '../views/FileLibrary.vue';
import GeneralSettings from '../views/GeneralSettings.vue';
import SuperAdminSettings from '../views/SuperAdminSettings.vue';
import NotFound from '../views/NotFound.vue';

import axios from 'axios';
import store from '../store';
import { get } from '../helpers/api.js';

Vue.use(VueRouter);

const router = new VueRouter({
	mode: 'history',
  base: '/admin/',
	routes: [
		{
			path: '',
			component: Master,
			meta: { requiresAuth: true },
			children: [
				{ path: '', component: Dashboard, meta: { view: "Dashboard", title: "Dashboard" } },
        { path: 'customization/:tab', component: Customization, meta: { view: "Customization", title: "Customization" } },
        { path: 'customization', component: Customization, meta: { view: "Customization", title: "Customization" } },
				{ path: 'pages', component: Pages, meta: { view: "Pages", title: "Pages" } },
        { path: 'pages/new', component: Page, meta: { view: "Page", title: "New Page" } },
        { path: 'pages/:slug', component: Page, meta: { view: "Page", title: "Edit Page" } },
				{ path: 'file-library', component: FileLibrary, meta: { view: "File Library", title: "File Library" } },
        { path: 'settings', component: GeneralSettings, meta: { view: "General Settings", title: "Settings" } },
        { path: 'admin-settings', component: SuperAdminSettings, meta: { view: "Super Admin Settings", title: "Super Admin" } },
        { path: '*', component: NotFound, meta: { view: "Not Found", title: "404 Not Found" } }
      ]
		}
	]
});


router.beforeEach( (to, from, next) => {
	// console.log("^^^^router beforeEach, going to: " + to.meta.view);
	// console.log("^^^^router beforeEach, coming from: " + from.meta.view);
	if (!to.matched.some(record => record.meta.requiresAuth)) {
		if (to.path == "/login" && !!window.localStorage['apiToken']) {
			next("/");
		}
		else {
			next();
		}
	}
	else {
		if (!!window.jwtToken) {
      get('whoami', window.jwtToken)
        .then( (res) => {
          if (!!res.data.user) {
            const nearestWithTitle = to.matched.slice().reverse().find( function(r) {
              return r.meta && r.meta.title;
            });
            // If a route with a title was found, set the document title to that value.
            if (!!nearestWithTitle) {
              const siteNameWithPipe = document.title.substring(0, document.title.indexOf("|") + 1);
              document.title = siteNameWithPipe + " " + nearestWithTitle.meta.title;
            }

            store.commit('setWhoami', res.data.user);

            next();
          }
          else {
            window.location.reload(true);
          }
        })
        .catch( (err) => {
          if (err.response.status == 401) {
            delete window.jwtToken;
            window.location.reload(true);
          }
        });
		}
		// Else if there's no API token
		else {
      window.location.reload(true);
    }
	}
});


export default router;
