import { boot } from 'quasar/wrappers';
import { StateInterface } from 'src/store';
import { RouteRecord } from 'vue-router';
import { Store } from 'vuex';

export default boot<Store<StateInterface>>(({ router, store }) => {
  router.beforeEach((to, from, next) => {
    const session = store.state.session.currentSession;

    if (to.path.startsWith('/main')) {
      // Secured area (LOGIN REQUIRED)
      // Check login is ok
      if (!session || session.expires <= new Date()) {
        store.dispatch('session/logout').catch(error => {
          console.warn(error);
        });
        return;
      }

      // Check if special permissions are required
      if (
        to.matched.every((record: RouteRecord) => {
          if (!('meta' in record) || !('permissions' in record.meta))
            return true;
          if (record.meta) {
            if ((<{ permissions: FG.Permission[] }>record.meta).permissions) {
              return (<{ permissions: FG.Permission[] }>(
                record.meta
              )).permissions.every((permission: string) => {
                return store.state.user.currentPermissions.includes(permission);
              });
            }
          }
        })
      ) {
        next();
      } else {
        next({ name: 'login', query: { redirect: to.fullPath } });
      }
    } else {
      if (
        to.name == 'login' &&
        store.state.user.currentUser &&
        !to.params['logout']
      ) {
        // Called login while already logged in
        void next({ name: 'dashboard' });
      } else {
        // We are on the non secured area
        next();
      }
    }
  });
});