import security from '.'

export default {
  check(access, forceInitialize = false) {
    let memberAuthority = security.getMemberAuthority()
    let isMemberAuthorityInnitalized = security.isMemberAuthorityInitalized()
    let hasAccess = null

    if (access.policy !== undefined && (isMemberAuthorityInnitalized === true || forceInitialize === true)) {
      Object.keys(access.policy).forEach(key => {
        // if any matching returns false then don't process anymore
        if (hasAccess !== false) {
          let permission = access.policy[key] || 'view'

          hasAccess =
            memberAuthority[key] !== undefined &&
            (memberAuthority[key][permission] !== undefined ||
              memberAuthority[key].find(value => value === permission) !== undefined)
        }
      })
    } else {
      hasAccess = true
    }

    return hasAccess || false
  },
  can(permission, oporation) {
    if (permission !== undefined) {
      return this.check({
        policy: {
          [permission]: oporation,
        },
      })
    }
  },
}
