package cn.hmsoft.hmplatform.wxtoken.util;

import java.util.HashMap;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.hmplatform.wxtoken.data.model.PWxDefine;

/**********************
 * token
 *
 */
public class WeixinTokenModuleUtil {

	private static WeixinTokenModuleUtil util = null;
	private static HashMap<String, PWxDefine> WxDefineMap = null;
	private static HashMap<String, WeixinTokenRequestThread> TokenThreadMap = null;

	private WeixinTokenModuleUtil() {

	}

	public static WeixinTokenModuleUtil instance(boolean refresh) {
		if (util == null || refresh) {
			synchronized (WeixinTokenModuleUtil.class) {
				WxDefineMap = new HashMap<String, PWxDefine>();
				TokenThreadMap = new HashMap<String, WeixinTokenRequestThread>();
				for (PWxDefine p : SpringHelper.AppGobalDao.all(PWxDefine.class)) {
					WxDefineMap.put(p.getApp_id(), p);
					WeixinTokenRequestThread thread = new WeixinTokenRequestThread(p);
					thread.start();
					TokenThreadMap.put(p.getApp_id(), thread);
				}
				util = new WeixinTokenModuleUtil();
			}
		}
		return util;
	}

	public void addWxDefine(PWxDefine p) {
		if (!WxDefineMap.containsKey(p.getApp_id())) {
			WxDefineMap.put(p.getApp_id(), p);
			WeixinTokenRequestThread thread = new WeixinTokenRequestThread(p);
			thread.start();
			TokenThreadMap.put(p.getApp_id(), thread);

		}
	}

	public PWxDefine getWxDefine(String app_id) {
		try {
			return TokenThreadMap.get(app_id).getWxDefine();
		} catch (Exception e) {

		}
		return null;
	}

}
