 
 jraphical   = require 'jraphical'
+crypto      = require 'crypto'
+
 JName       = require '../name'
 JUser       = require '../user'
 JGroup      = require '../group'
-JCredential = require './credential'
-crypto      = require 'crypto'
 
 module.exports = class JProvisioner extends jraphical.Module
 

          callback null, provisioner


  @fetchBySlug = (client, slug, callback)->

    options =
      limit         : 1
      targetOptions : selector : { slug }

    {delegate} = client.connection
    delegate.fetchProvisioner { }, options, (err, res)->

      return callback err        if err?
      return callback null, res  if res?

      { group } = client.context
      JGroup.one slug: group, (err, group)->
        return callback err  if err?

        group.fetchProvisioner { }, options, (err, res)->
          callback err, res


  @one$ = permit 'list provisioners',

    success: (client, slug, callback)->

      @fetchBySlug client, slug, callback


  @some$ = permit 'list provisioners', success: JCredential.someHelper


  fetchUsers: JCredential::fetchUsers


  setPermissionFor: (target, {user, owner}, callback)->

    Relationship.remove
      targetId : @getId()
      sourceId : target.getId()
    , (err)=>

      if user
        as = if owner then 'owner' else 'user'
        target.addProvisioner this, { as }, (err)-> callback err
      else
        callback err

  # .share can be used like this:
  #
  # JProvisionerInstance.share { user: yes, owner: no, target: "gokmen"}, cb
  #                                       group or user slug -> ^^^^^^

  shareWith$: permit

    advanced: [
      { permission: 'update provisioner', validateWith: Validators.own }
    ]

    success: JCredential::shareWith


  delete: permit 'delete provisioner',

    success: (client, callback)->

      { delegate } = client.connection

      Relationship.one
        targetId : @getId()
        sourceId : delegate.getId()
      , (err, rel)=>

        return callback err   if err?
        return callback null  unless rel?

        if rel.data.as is 'owner'
          @remove callback
        else
          rel.remove callback


  update$: permit

    advanced: [
      { permission: 'update provisioner', validateWith: Validators.own }
    ]

    success: (client, options, callback)->

      {content, label} = options

    softDelete        : yes

    permissions       :

      'create provisioner'     : ['member']
      'list provisioners'      : ['member']

      'update own provisioner' : ['member']
      'delete own provisioner' : ['member']

      'update provisioner'     : []
      'delete provisioner'     : []

    sharedMethods     :
      static          :
        one           :
          (signature Object, Function)
        create        :
          (signature Object, Function)
        some          : [
