package com.yihu.hos.common.mongo;

import java.util.HashMap;
import java.util.Map;

/**
 * @created Airhead 2016/2/17.
 */
public class MongoDBKit {
    public static final String MAIN_CONFIG_NAME = "main";
    public static final String DEFAULT_DB_NAME = "test";
    static MongoDBConfig config = null;
    private static Map<String, MongoDBConfig> configNameToConfig = new HashMap<>();

    public static void start() {
        MongoDB.init();
    }

    public static MongoDBConfig getConfig() {
        return config;
    }

    public static MongoDBConfig getConfig(String configName) {
        return configNameToConfig.get(configName);
    }

    /**
     * Add Config object
     *
     * @param config the Config contains Mongodb uri and MongoClientOptions etc.
     */
    public static void addConfig(MongoDBConfig config) {
        if (config == null) {
            throw new IllegalArgumentException("Config can not be null");
        }
        if (configNameToConfig.containsKey(config.getName())) {
            throw new IllegalArgumentException("Config already exists: " + config.getName());
        }

        configNameToConfig.put(config.getName(), config);

        /**
         * Replace the main config if current config name is MAIN_CONFIG_NAME
         */
        if (MAIN_CONFIG_NAME.equals(config.getName())) {
            MongoDBKit.config = config;
        }

        /**
         * The configName may not be MAIN_CONFIG_NAME,
         * the main config have to set the first comming Config if it is null
         */
        if (MongoDBKit.config == null) {
            MongoDBKit.config = config;
        }
    }
}
