package com.yihu.hos.common.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

/**
 * @created Airhead 2016/2/17.
 */
public class MongoDBConfig {
    String name;
    String uri;
    String defaultDatabaseName;

    static MongoClient mongoClient;
    MongoClientOptions mongoClientOptions;      //暂未使用，Mongo默认配置
    MongoDatabase mongoDatabase;

    public MongoDBConfig(String uri) {
        this.name = MongoDBKit.MAIN_CONFIG_NAME;
        this.uri = uri;
        this.defaultDatabaseName = MongoDBKit.DEFAULT_DB_NAME;
    }

    public MongoDBConfig(String name, String uri) {
        this.name = name;
        this.uri = uri;
        this.defaultDatabaseName = MongoDBKit.DEFAULT_DB_NAME;
    }

    public MongoDBConfig(String name, String uri, String databaseName) {
        this.name = name;
        this.uri = uri;
        this.defaultDatabaseName = databaseName;
    }

    public String getName() {
        return name;
    }

    public MongoDatabase getDatabase(String databaseName) {
        if (mongoClient == null) {
            MongoClientURI mongoClientURI = new MongoClientURI(uri);
            mongoClient = new MongoClient(mongoClientURI);
        }

        if (mongoDatabase != null) {
            if (mongoDatabase.getName().equals(databaseName)) {
                return mongoDatabase;
            }
        }

        mongoDatabase = mongoClient.getDatabase(databaseName);
        return mongoDatabase;
    }

    public MongoDatabase getDatabase() {
        if (mongoDatabase != null) {
            return mongoDatabase;
        }

        return getDatabase(defaultDatabaseName);
    }
}
