package org.springframework.multitenancy.mongo.operation;

import java.util.List;

import org.bson.Document;
import org.springframework.multitenancy.mongo.datasource.MongoDataSource;
import org.springframework.multitenancy.mongo.mapping.MongoIndexChange;
import org.springframework.multitenancy.mongo.mapping.MongoPersistentEntityIndex;

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

/**
 * Class responsible for execute operations in MongoDB
 * 
 * @author WRP
 * */
public class MongoBasicOperations implements MongoOperations {
	
	private MongoDataSource dataSource;
	private MongoPersistentEntityIndex index;
	
	public MongoBasicOperations(MongoDataSource dataSource, MongoPersistentEntityIndex index){
		this.dataSource = dataSource;
		this.index = index;
	}
		
	@Override
	public boolean exist(String collectionName) {
		MongoDatabase database = dataSource.getDataSource();
		MongoCursor<String> result =  database.listCollectionNames().iterator();
		
		while(result.hasNext()){
			if(result.next().equalsIgnoreCase(collectionName)){
				return true;
			}
		}
		    	
		return false;
	}
	
	@Override
	public <T> MongoCollection<Document> getCollection(String collectionName, Class<T> type) {
		MongoDatabase database = dataSource.getDataSource();
		
		MongoCollection<Document> collection = database.getCollection(collectionName);
		
		List<MongoIndexChange> indexChanges = index.getChanges(collection, type);
		
		for (MongoIndexChange change : indexChanges) {
			ensureIndex(collection, change.getName(), change.getDefinition(), change.getOptions(), change.isReplace());
		}	
		
		return database.getCollection(collectionName);
	}
	
	@Override
	public void ensureIndex(MongoCollection<Document> collection, String name, Document index, IndexOptions opts, boolean replace) {
		
		if(replace){
			collection.dropIndex(name);
		}
				
		collection.createIndex(index, opts);
	}
}