package com.zhiwei.manage.handle;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.zhiwei.manage.bean.ServerBean;
import com.zhiwei.manage.util.MongoConnect;

@Service("firstRun")
public class DbDepot {

	@Resource(name = "mongoTemplate")
	private MongoTemplate mongo;
	// 信息和检测模板切换链接
	public static ConcurrentMap<String, Object> dbCons;
	public static ConcurrentMap<String, Object> newsCol;
	public static ConcurrentMap<String, Object> dataCol;
	public static String nowPt = "网媒";
	private static final Log log = LogFactory.getLog(DbDepot.class);

	public void init() {
		log.info("数据连接map初始化");
		dataCol = new ConcurrentHashMap<String, Object>();
		dbCons = new ConcurrentHashMap<String, Object>();
		newsCol = new ConcurrentHashMap<String, Object>();
		List<ServerBean> list = mongo.find(Query.query(Criteria.where("pt").is(nowPt)), ServerBean.class);
		for (ServerBean sb : list) {
			System.out.println(sb);
			if (sb.getDbType().equals("mongo")) {
				if (sb.getDbUsername() != null && !sb.getDbUsername().trim().equals("")) {
					DBCollection con = new MongoConnect(sb.getDbHost(), sb.getDbPort(), sb.getDbUsername(),
							sb.getDbPassword(), sb.getDbName()).getCollection(sb.getCollection());
					dbCons.put(sb.getOther(), con);
				} else {
					DBCollection con = new MongoConnect(sb.getDbHost(), sb.getDbPort(), sb.getDbName())
							.getCollection(sb.getCollection());
					dbCons.put(sb.getOther(), con);
				}
			}
		}
		System.out.println("连接初始化成功");
	}

	public DBCollection getDBCollection(String other) {
		DBCollection con = null;
		ServerBean sb = mongo.findOne(
				Query.query(Criteria.where("pt").is(nowPt).orOperator(Criteria.where("other").is(other))),
				ServerBean.class);
		System.out.println(sb);
		if (sb != null) {
			if (sb.getDbType().equals("mongo")) {
				if (sb.getDbUsername() != null && !sb.getDbUsername().equals("")) {
					con = new MongoConnect(sb.getDbHost(), sb.getDbPort(), sb.getDbUsername(), sb.getDbPassword(),
							sb.getDbName()).getCollection(sb.getCollection());
					dbCons.put(sb.getOther(), con);
				} else {
					con = new MongoConnect(sb.getDbHost(), sb.getDbPort(), sb.getDbName())
							.getCollection(sb.getCollection());
					dbCons.put(sb.getOther(), con);
				}
			}
		}
		return con;
	}

}
