package jp.co.headwaters.webappos.cache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.co.headwaters.webappos.dao.DaoUtil;
import jp.co.headwaters.webappos.dao.bean.SystemConstant;

import org.apache.ibatis.session.SqlSession;

public class SystemConstantCache {

	private static final SystemConstantCache instance = new SystemConstantCache();

	private Map<String, Map<String, SystemConstant>> systemConstantMap;

	private SystemConstantCache() {
	}

	public static SystemConstantCache getInstance() {
		return instance;
	}

	public void refresh() {
		SqlSession session = DaoUtil.getSqlSessionFactory().openSession();
		List<SystemConstant> systemConstantList = null;
		try {
			systemConstantList = session.selectList("system_constant.selectAll");
		} finally {
			session.close();
		}

		systemConstantMap = new HashMap<String, Map<String, SystemConstant>>();

		for (SystemConstant systemConstant : systemConstantList){
			if (!systemConstantMap.containsKey(systemConstant.getCategory())){
				systemConstantMap.put(systemConstant.getCategory(), new HashMap<String, SystemConstant>());
			}
			systemConstantMap.get(systemConstant.getCategory()).put(systemConstant.getKey(), systemConstant);
		}
	}

	public Map<String, Map<String, SystemConstant>> getAllSystemConstant() {
		return systemConstantMap;
	}

	public Map<String, SystemConstant> getSystemConstantMap(String category) {
		return systemConstantMap.get(category);
	}

	public List<SystemConstant> getSystemConstantList(String category) {
		List<SystemConstant> result = new ArrayList<SystemConstant>();
		for (SystemConstant entry : systemConstantMap.get(category).values()){
			result.add(entry);
		}
		return result;
	}

	public SystemConstant getSystemConstant(String category, String key) {
		return systemConstantMap.get(category).get(key);
	}

	public SystemConstant getSystemConstant(String key) {
		return systemConstantMap.get("").get(key);
	}
}
