 
     @__service = {}
     @listeners = {}
-    @batchQueue = {}
     @batchResults = {}
     @ready = false
 

    delete @_db.listeners[@__id]

class Neo4jDB
  constructor: (@url, opts = {}) ->
    @url = @url or process.env.NEO4J_URL or process.env.GRAPHENEDB_URL or 'http://localhost:7474'
    check @url, String
    check opts, Object

    @defaultHeaders = _.extend @defaultHeaders, opts.headers if opts?.headers
    @defaultHeaders.Authorization = "Basic " + (new Buffer("#{opts.username}:#{opts.password}").toString('base64')) if opts.password and opts.username

    @on 'batch', @__request
    tasks = []
    @on 'query', (id, task) => 
      tasks.push task
      if @ready
        @emit 'batch', tasks, -> tasks = [] 
    
    @__connect()

  __request: _.throttle (tasks, cb) ->
    bound =>
      @__call @__service.batch.endpoint
      , 
        data: tasks
        headers:
          Accept: 'application/json; charset=UTF-8'
          'Content-Type': 'application/json'
      ,
        'POST'
      ,
        (error, results) =>
          # console.log results

          if results?.data
            @__proceedResult result for result in results.data

          else if results?.content
            content = JSON.parse results.content
            @__proceedResult result for result in content
      cb and cb()

  , 100

  __proceedResult: (result) ->
    if result?.body
      if _.isEmpty result.body?.errors
        @emit result.id, null, result.body
      else
        for error in result.body.errors
          console.error error.message
          console.error {code: error.code}
        @emit result.id, null, []
    else
      @emit result.id, null, []

  __batch: (task, callback, reactive) ->
    task.to = task.to.replace @root, ''
    @emit 'query', task.id, task
    unless callback
      res =  Meteor.wrapAsync((cb) =>
        @once task.id, (error, response) =>
          bound => cb error, @__transformData _.clone(response), reactive
      )()
      return res
    else
      @once task.id, (error, response) =>
        bound =>
          callback error, @__transformData _.clone(response), reactive

  __connect: -> 
    response = @__call @root
