package net.davidvoid.thor.lightning.data.access;

import net.davidvoid.thor.lightning.data.source.MongoDataSource;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;

/**
 * Created by david on 3/22/16.
 * {_id: XX, name: string, seq: long }
 * index 1: name, unique
 *
 */
@Component
public class Counter {
	@Autowired
	MongoDataSource data_source = null;

	public long getNextId(String col_name) {
		BasicDBObject query = new BasicDBObject("name", col_name);
		BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("seq", 1L));

		MongoCollection<Document> col = data_source.getDatabase().getCollection("counter");
		FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
		options.upsert(true).returnDocument(ReturnDocument.AFTER);
		Document returned = col.findOneAndUpdate(query, update, options);

		return (long) returned.get("seq");
	}
}

@@ -42,24 +42,129 @@
 .access;%0D%0A%0D%0A
+import static com.mongodb.client.model.Filters.eq;%0D%0Aimport static com.mongodb.client.model.Updates.inc;%0D%0A
 import net.d
@@ -242,24 +242,59 @@
 .Document;%0D%0A
+import org.bson.conversions.Bson;%0D%0A
 import org.s
@@ -401,43 +401,8 @@
 %0D%0A%0D%0A
-import com.mongodb.BasicDBObject;%0D%0A
 impo
@@ -799,155 +799,8 @@
  %7B%0D%0A
-%09%09BasicDBObject query = new BasicDBObject(%22name%22, col_name);%0D%0A%09%09BasicDBObject update = new BasicDBObject(%22$inc%22, new BasicDBObject(%22seq%22, 1L));%0D%0A%0D%0A
 %09%09Mo
@@ -882,16 +882,89 @@
 ter%22);%0D%0A
+%09%09Bson query = eq(%22name%22, col_name);%0D%0A%09%09Bson update = inc(%22seq%22, 1L);%0D%0A%0D%0A
 %09%09FindOn

migrate to API 3