import security, { ACTION_ALLOW, ACTION_DENY, ROLE_IS_LOGGED_IN } from '.'

/**
 * Routes security guard
 * used to check if user has rights to given rules
 * rules are array of objects as eg:
 * use toSkip = true to disable security check (for special case modules where mixed mode required)
 ```
 [
 { path: '^/user/login', role: ROLE_IS_LOGGED_IN, action: ACTION_DENY, to: {path: HOME_PAGE_URL}}
 -- OR --
 { path: '^/user/login', role: ROLE_IS_LOGGED_IN, toSkip: true }
 ]
 ```
 * path: is the regular expression to match
 * role: is the user role to check, roles are const defined starting with ROLE_* in index.js
 * action: is the action to take, actions are const defined starting with ACTION_* in index.js
 * to: is a vuex route object to return if the the match fails
 */
export default {
  _route: null,
  _rules: false,
  check(route, loggedInCheck = true) {
    // route will route normally when returned true
    let routeTo = true
    let propagatedRouteTo = null
    // only process if rules is an array
    if (this._rules.constructor === Array) {
      this._rules.forEach(function(rule) {
        let regex = new RegExp(rule.path)
        if (route.matched.some(record => regex.test(record.path))) {
          // check if the rule requires user login
          if (rule.role === ROLE_IS_LOGGED_IN && rule.toSkip === undefined) {
            // check if user is logged in
            if (security.isUserLoggedIn() && loggedInCheck === true) {
              // deny access if user is logged in
              if (rule.action === ACTION_DENY) {
                routeTo = rule.to
                return
              }
              // allow access if user is logged in
              if (rule.action === ACTION_ALLOW) {
                routeTo = true
                if (rule.propagation === false) {
                  propagatedRouteTo = true
                }
              }
            } else {
              // dont redirect if user is not logged in
              if (rule.action === ACTION_DENY) {
                routeTo = true
                return
              }
              // redirect to path if user is not logged in
              if (rule.action === ACTION_ALLOW) {
                routeTo = rule.to
                if (rule.propagation === false) {
                  propagatedRouteTo = true
                }
              }
            }
          } else {
            routeTo = true
          }
        }
      })
    }
    return propagatedRouteTo || routeTo
  },
  rules(accessRules) {
    this._rules = accessRules
  },
}
