package cn.ibizlab.core.data.mongodb;

import cn.ibizlab.core.data.model.DSLink;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DynamicMongoContextHolder
{

  public static final Map<String, MongoDbFactory> MONGO_CLIENT_DB_FACTORY_MAP = new HashMap<>();
  public static final ThreadLocal<MongoDbFactory> MONGO_DB_FACTORY_THREAD_LOCAL =
      new ThreadLocal<>();

  public static MongoDbFactory getMongoDbFactory() {
    return MONGO_DB_FACTORY_THREAD_LOCAL.get();
  }

  public static void push(String name) {
    MONGO_DB_FACTORY_THREAD_LOCAL.set(MONGO_CLIENT_DB_FACTORY_MAP.get(name));
  }

  public static void poll() {
    MONGO_DB_FACTORY_THREAD_LOCAL.remove();
  }

  public static synchronized void addFactory(String ds, DSLink link)
  {
    addFactory(ds,link.getUrl());
  }

  public static synchronized void addFactory(String ds, String uri)
  {
    MONGO_CLIENT_DB_FACTORY_MAP.put(ds, new SimpleMongoClientDbFactory(uri));
  }

  public static synchronized void removeFactory(String ds)
  {
    MONGO_CLIENT_DB_FACTORY_MAP.remove(ds);
  }



}
