package org.lumongo.util;

import java.util.Collection;

import org.bson.BSON;
import org.lumongo.cluster.message.Lumongo.Metadata;
import org.lumongo.cluster.message.Lumongo.ResultDocument;

import com.google.protobuf.ByteString;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class BsonHelper {
	public static DBObject dbObjectFromResultDocument(ResultDocument rd) {
		if (rd.hasDocument()) {
			if (rd.getType().equals(ResultDocument.Type.BSON)) {
				ByteString bs = rd.getDocument();
				DBObject document = new BasicDBObject();
				document.putAll(BSON.decode(bs.toByteArray()));
				return document;
			}
			else {
				throw new IllegalArgumentException("Raw document must be of type <" + ResultDocument.Type.BSON + ">");
			}
		}
		return null;
	}
	
	public static ResultDocument dbObjectToResultDocument(String uniqueId, DBObject document) {
		return dbObjectToResultDocument(uniqueId, document, null);
	}
	
	public static ResultDocument dbObjectToResultDocument(String uniqueId, DBObject document, Collection<Metadata> metadata) {
		
		ByteString byteString = ByteString.copyFrom(BSON.encode(document));
		ResultDocument.Builder builder = ResultDocument.newBuilder();
		builder.setDocument(byteString);
		if (metadata != null) {
			builder.addAllMetadata(metadata);
		}
		builder.setType(ResultDocument.Type.BSON);
		builder.setUniqueId(uniqueId);
		return builder.build();
	}
}

@@ -769,25 +769,24 @@
 rn null;%0A%09%7D%0A
-%09
 %0A%09public sta
@@ -925,19 +925,209 @@
 nt, 
-null
+false);%0A%09%7D%0A%0A%09public static ResultDocument dbObjectToResultDocument(String uniqueId, DBObject document, boolean compressed) %7B%0A%09%09return dbObjectToResultDocument(uniqueId, document, null, compressed
 );%0A%09%7D%0A
-%09
 %0A%09pu
@@ -1243,22 +1243,40 @@
 metadata
+, boolean compressed
 ) %7B%0A
-%09%09
 %0A%09%09ByteS
@@ -1582,16 +1582,53 @@
 queId);%0A
+%09%09builder.setCompressed(compressed);%0A
 %09%09return

allow compression on bson