package ch.rasc.eds.starter.config;

import javax.annotation.PostConstruct;

import org.apache.catalina.User;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;

import ch.rasc.eds.starter.entity.CPersistentLogin;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.PersistentLogin;

@Component
public class MongoDb {

	private final MongoDatabase mongoDatabase;

	@Autowired
	public MongoDb(final MongoDatabase mongoDatabase) {
		this.mongoDatabase = mongoDatabase;
	}

	@PostConstruct
	public void createIndexes() {
		this.getCollection(User.class).createIndex(Indexes.ascending(CUser.email),
				new IndexOptions().unique(true));
		this.getCollection(PersistentLogin.class)
				.createIndex(Indexes.ascending(CPersistentLogin.userId));
	}

	public MongoDatabase getMongoDatabase() {
		return this.mongoDatabase;
	}

	public <T> MongoCollection<T> getCollection(Class<T> documentClass) {
		return this.mongoDatabase.getCollection(
				StringUtils.uncapitalize(documentClass.getSimpleName()), documentClass);
	}

	public <T> MongoCollection<T> getCollection(String collectionName,
			Class<T> documentClass) {
		return this.mongoDatabase.getCollection(collectionName, documentClass);
	}

	public MongoCollection<Document> getCollection(String collectionName) {
		return this.mongoDatabase.getCollection(collectionName);
	}

	public long count(Class<?> documentClass) {
		return this.getCollection(documentClass).count();
	}
}

@@ -834,24 +834,73 @@
 Indexes() %7B%0A
+%0A%09%09if (!indexExists(User.class, CUser.email)) %7B%0A%09
 %09%09this.getCo
@@ -964,16 +964,17 @@
 email),%0A
+%09
 %09%09%09%09new 
@@ -1003,16 +1003,76 @@
 true));%0A
+%09%09%7D%0A%0A%09%09if (!indexExists(User.class, CUser.failedLogins)) %7B%0A%09
 %09%09this.g
@@ -1107,16 +1107,17 @@
 .class)%0A
+%09
 %09%09%09%09.cre
@@ -1170,16 +1170,299 @@
 erId));%0A
+%09%09%7D%0A%0A%09%7D%0A%0A%09private boolean indexExists(Class%3C?%3E clazz, String name) %7B%0A%09%09for (Document doc : this.getCollection(clazz).listIndexes()) %7B%0A%09%09%09Document key = (Document) doc.get(%22key%22);%0A%09%09%09if (key != null) %7B%0A%09%09%09%09if (key.containsKey(name)) %7B%0A%09%09%09%09%09return true;%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%09%09return false;%0A
 %09%7D%0A%0A%09pub

Improve index creation. Only create index if it does not exists