 handleAuth = require './auth/auth.coffee'
+
+mungeCallbacks = (callbacks, n) ->
+  # FIXME: this is an ugly hack; there must be a better way to implement it:
+  for own k, c of callbacks
+    if (c.join '.') is '0.responseCallback'
+      callbacks[k] = [n]
+    if c[1] is 'withArgs'
+      # since we're rewriting the protocol for the withArgs case, we need to remove everything up to withArgs
+      callbacks[k] = c.slice 2
+  callbacks
 
 module.exports = (proto, message) ->
 

  if args.length > 0
    [{ withArgs, responseCallback, kite, authentication: auth }] = args

  handleAuth(auth, @key).then (token) ->

    if !withArgs? and !responseCallback?
      # it's a normal dnode protocol message.
      proto.handle req
      return

    # it's a kite protocol message.
    withArgs ?= []

    withArgs = [withArgs]  unless Array.isArray withArgs

    # FIXME: this is an ugly hack; there must be a better way to implement it:
    for own k, c of callbacks
      if (c.join '.') is '0.responseCallback'
        callbacks[k] = [withArgs.length]
      if c[1] is 'withArgs'
        # since we're rewriting the protocol for the withArgs case, we need to remove everything up to withArgs
        callbacks[k] = c.slice 2

    proto.handle {
      method

      links
      callbacks
    }

  .catch (err) =>
    @emit 'debug', "Authentication failed"

    mungeCallbacks callbacks, 1

    proto.handle {
      method: 'kite.echo'
      arguments: [err, responseCallback]
      links
      callbacks
    }
