package database;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import core.ApplicationConfiguration;
import org.bson.BsonDocument;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by gpietrus on 20.02.2016.
 */
public class MongoDBConnector implements DBConnector {
    private ApplicationConfiguration applicationConfiguration;
    private MongoClient mongoClient;
    private MongoDatabase database;

    public MongoDBConnector(ApplicationConfiguration applicationConfiguration) {
        this.applicationConfiguration = applicationConfiguration;
    }

    @Override
    public void connect() {
        //todo: get from configuration file
        mongoClient = new MongoClient(
                applicationConfiguration.getDbHost(),
                applicationConfiguration.getDbPort());
        this.database = mongoClient.getDatabase(
                applicationConfiguration.getDbName()
        );
    }

    @Override
    public void disconnect() {
    }

    @Override
    public void databaseCleanup() {

    }

    public ArrayList<Document> getCollection(String collectionName) {
        return database.getCollection(collectionName).find().into(new ArrayList<>());
    }

    public void getDocument(String collectionName, Map criteria) {
        BsonDocument bsonDocument = new BsonDocument();
        bsonDocument.putAll(criteria);
        database.getCollection(collectionName).find(bsonDocument);
    }

    public void addDocument(String collectionName, Document document) {
        database.getCollection(collectionName).insertOne(document);
    }

    public void removeCollection(String collectionName) {
        database.getCollection(collectionName).drop();
    }

}
