+WAIT_FOR_DATABASE_TIMEOUT = 1000 # ms
+
 # The order of documents here tests delayed definitions
 
 # Just to make sure things are sane

if Meteor.isServer and Document.instances is 1
  testAsyncMulti 'peerdb - exception while processing', [
    (test, expect) ->
      Log._intercept 4 # Four to see if we catch more than expected

      IdentityGenerator.documents.insert
        source: 'exception'

  Meteor.publish null, ->
    SpecialPost.documents.find()

  Future = Npm.require 'fibers/future'

  Meteor.methods
    'wait-for-database': ->
      future = new Future()
      timeout = null
      newTimeout = ->
        Meteor.clearTimeout timeout if timeout
        timeout = Meteor.setTimeout ->
          timeout = null
          future.return() unless future.isResolved()
        , WAIT_FOR_DATABASE_TIMEOUT
      newTimeout()
      handles = []
      for document in Document.list
        do (document) ->
          initializing = true
          handles.push document.documents.find({}).observeChanges
            added: (id, fields) ->
              newTimeout() unless initializing
            changed: (id, fields) ->
              newTimeout()
            removed: (id) ->
              newTimeout()
          initializing = false
      future.wait()
      for handle in handles
        handle.stop()

waitForDatabase = (test, expect) ->
  Meteor.call 'wait-for-database', expect (error) ->
