 Tracker     = require './tracker'
 KodingError = require '../error'
 { extend }  = require 'underscore'
-async       = require 'async'
 
 { protocol, hostname } = KONFIG
-{ secure, signature }  = Bongo
+{ secure, signature, dash } = Bongo
 
 emailsanitize = require './user/emailsanitize'
 

  # triggers sendInvitationEmail
  @create: permit 'send invitations',
    success: (client, options, callback) ->
      JUser               = require './user'
      JGroup              = require './group'

      { delegate }        = client.connection
      { invitations }     = options
      groupName           = client.context.group or 'koding'
      name                = getName delegate

      # check for membership
      JGroup.one { slug: groupName }, (err, group) ->
        return callback new KodingError err                   if err
        return callback new KodingError 'group doesnt exist'  if not group

        queue = invitations.map (invitation) -> (fin) ->

          { email, firstName, lastName, role } = invitation

          JInvitation.one { email, groupName }, (err, invitation) ->
            return fin new KodingError err  if err

            # do not send another invitation if the user is already invited
            # before
            return fin()  if invitation

            isAlreadyMember group, email, (err, isMember) ->
              return fin new KodingError err  if err

              # do not send another invitation if the user is already a member
              # of the group
              return fin()  if isMember

              hash = JUser.getHash email

              # eg: VJPj9gUQ
              code = shortid.generate()

              data =   {
                code
                hash
                email

              }
              # firstName and lastName are optional
              data.firstName = firstName  if firstName
              data.lastName  = lastName   if lastName

              invite = new JInvitation data
              invite.save (err) ->
                return callback new KodingError err  if err
                codes.push { email, code }

                return queue.fin()  if noEmail

                JInvitation.sendInvitationEmail client, invite, -> queue.fin()

        cb = ->
          if returnCodes
          then callback null, codes
          else callback()

        dash queue, cb


  # isAlreadyMember checks if the given email is already member of the given
