import security from '.'
import _ from 'lodash'

export default {
  directive() {
    return {
      update: this.directiveBind.bind(this),
      inserted: this.directiveBind.bind(this),
    }
  },
  directiveBind(el, binding, vnode, oldVnode) {
    let permission = binding.arg || 'view'

    if (!_.isEmpty(binding.value)) {
      let hasAccess = security.policy.check({
        policy: {
          [binding.value]: permission,
        },
      })

      let currentPermission = vnode.context.permissions || {}

      vnode.context.permissions = {
        ...currentPermission,
        [binding.value]: {
          // Loop though all the permissions and check if has access
          // then append to the permissions context
          ...['create', 'view', 'edit', 'list', 'search', 'delete'].reduce((policy, permission) => {
            policy[permission] = security.policy.check({
              policy: {
                [binding.value]: permission,
              },
            })

            return policy
          }, {}),
        },
      }

      let permissionName = 'permission' + permission.charAt(0).toUpperCase() + permission.substr(1).toLowerCase()

      // check if there is a dedicated function for procession permission
      // if there is then process the permission
      if (this[permissionName] !== undefined) {
        this[permissionName](el, vnode.context.permissions[binding.value])
      }
    } else {
      if (vnode.context.permissions === undefined) {
        vnode.context.permissions = {}
      }
    }
  },
  permissionView: function(el, permissions) {
    if (permissions['view'] === false) {
      if (el.parentElement !== undefined && el.parentElement !== null) {
        el.parentElement.removeChild(el)
      } else {
        el.innerHTML = ''
        el.outterHTML = ''
      }
    }
  },
  permissionCreate: function(el, permissions) {
    if (permissions['create'] === false) {
      if (el.parentElement !== undefined && el.parentElement !== null) {
        el.parentElement.removeChild(el)
      } else {
        el.innerHTML = ''
        el.outterHTML = ''
      }
    }
  },
  permissionList: function(el, permissions) {
    if (permissions['list'] === false) {
      if (el.parentElement !== undefined && el.parentElement !== null) {
        el.parentElement.removeChild(el)
      } else {
        el.innerHTML = ''
        el.outterHTML = ''
      }
    }
  },
  permissionEdit: function(el, permissions) {
    if (permissions['view'] === true && permissions['edit'] === false) {
      el.setAttribute('readonly', true)
    }
  },
}
