import Ember from 'ember'
export panda_authorizations = [
  {type: 'model', target: 'panda/organization',     permissions: ['manage']}
  {type: 'model', target: 'panda/project',          permissions: ['read', 'manage']}
  {type: 'model', target: 'panda/project-instance', permissions: ['read', 'manage']}
]
export default Ember.Route.extend
  setupController: (controller, model) ->
    adapters = @store.peekAll('panda/adapter')
    active_authorizations = model.get('role_names')

    active_authorizations.push "ban-app-panda" unless active_authorizations.some (permission) ->
      permission.match new RegExp('-app-panda$')
    panda_authorizations.forEach (authorization) ->
      match_found = false
      authorization.permissions.forEach (permission) ->
        match_found = true if "#{permission}-#{authorization.type}-#{authorization.target}" in active_authorizations
      active_authorizations.push "ban-#{authorization.type}-#{authorization.target}" unless match_found

    # explicitly add ban-model-epots/work-order if no permission is present
    adapters.forEach (adapter) ->
      adapter.get('authorizations').forEach (authorization) ->
        match_found = false
        authorization.permissions.forEach (permission) ->
          match_found = true if "#{permission}-#{authorization.type}-#{authorization.target}" in active_authorizations
        active_authorizations.push "ban-#{authorization.type}-#{authorization.target}" unless match_found
      has_adapter_authorization = active_authorizations.some (permission) ->
        permission.match(new RegExp("-adapter-#{adapter.id}$"))
      active_authorizations.push "ban-adapter-#{adapter.id}" unless has_adapter_authorization

    controller.set 'active_authorizations', active_authorizations
    controller.set 'adapters', adapters
    controller.set 'panda_authorizations', panda_authorizations
    @_super arguments...
