 {Module} = require 'jraphical'
-_ = require 'underscore'
+{difference} = require 'underscore'
 
 module.exports = class JGroup extends Module
 

      if delegate.getId().equals accountId
        return callback new KodingError 'You cannot transfer ownership to yourself, concentrate and try again!'

      # double check that client is really the owner
      @fetchMyRoles client, (err, roles)=>
        return callback err if err

        if not 'owner' in roles
          return callback new KodingError 'You must be owner to perform this action!'

        JAccount.one _id:accountId, (err, account)=>
          return callback err if err

              callback err

            # give rights to new owner
            queue = difference(['member', 'admin'], newOwnersRoles).map (role)=>=>
              @addMember account, role, (err)->
                return kallback err if err
                queue.fin()

            dash queue, =>
              # transfer ownership
              owner.update $set: targetId: accountId, kallback

  ensureUniquenessOfRoleRelationship:(target, options, fallbackRole, roleUnique, callback)->
    unless callback
      callback   = roleUnique
      roleUnique = no

    if 'string' is typeof options
      as = options
    else if options and options.as
      {as} = options
    else
      as = fallbackRole

    selector =
      targetName : target.bongo_.constructorName
      sourceId   : @getId()
      sourceName : @bongo_.constructorName
      as         : as

    if not roleUnique
      selector['targetId'] = target.getId()

    Relationship.count selector, (err, count)->
      if err then callback err
      else if count is 0 then callback null
      else callback new KodingError 'This relationship already exists'

  oldAddMember = @::addMember
  addMember:(target, options, callback)->
    @ensureUniquenessOfRoleRelationship target, options, 'member', (err)=>
      if err then callback err
      else oldAddMember.call @, target, options, callback

  oldAddAdmin = @::addAdmin
  addAdmin:(target, options, callback)->
    @ensureUniquenessOfRoleRelationship target, options, 'admin', (err)=>
      if err then callback err
      else oldAddAdmin.call @, target, options, callback

  oldAddOwner = @::addOwner
  addOwner:(target, options, callback)->
    @ensureUniquenessOfRoleRelationship target, options, 'owner', yes, (err)=>
      if err then callback err
      else oldAddOwner.call @, target, options, callback

