 
 import Foundation
 import BSON
+import When
 
 public class Collection {
     let database: Database?

    // Create
    
    public func insert(document: Document, flags: InsertMessage.Flags = []) throws {
        try insert([document], flags: flags)
    }
    
    public func insert(documents: [Document], flags: InsertMessage.Flags = []) throws {
        guard let database: Database = database else {
            throw MongoError.BrokenCollectionObject
        }

    
    // Read
    
    public func find(query: Document, flags: QueryMessage.Flags = [], numbersToSkip: Int32 = 0, numbersToReturn: Int32 = 0) throws -> Completer<[Document]> {
        let completer = Completer<[Document]>()
        
        let queryMsg = try QueryMessage(collection: self, query: query, flags: [], numbersToSkip: numbersToSkip, numbersToReturn: numbersToReturn)
        
        try self.database?.server.sendMessage(queryMsg) { reply in
            completer.complete(reply.documents)
        }
        
        return completer
    }
    
    public func findOne(query: Document, flags: QueryMessage.Flags = [], numbersToSkip: Int32 = 0) throws -> ThrowingCompleter<Document?> {
        let completer = ThrowingCompleter<Document?>()
        
        let documentsFuture = try find(query, flags: flags, numbersToSkip: numbersToSkip)
        
        documentsFuture.future.then { documents in
            completer.complete(documents.first)
        }
        
        return completer
    }
    
    // Update
