package jp.co.headwaters.webappos.controller.cache;

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

import jp.co.headwaters.webappos.controller.ControllerConstants;
import jp.co.headwaters.webappos.controller.model.SystemConstant;
import jp.co.headwaters.webappos.controller.utils.DaoUtils;

import org.apache.ibatis.session.SqlSession;

public class SystemConstantCache {

	private static final SystemConstantCache _instance = new SystemConstantCache();
	private Map<String, Map<String, SystemConstant>> _map;

	private SystemConstantCache() {
	}

	public static SystemConstantCache getInstance() {
		return _instance;
	}

	public void refresh() {
		List<SystemConstant> systemConstantList = null;
		try (SqlSession session = DaoUtils.getSqlSessionFactory().openSession()) {
			systemConstantList = session.selectList(ControllerConstants.SYSTEM_CONSTANT_SEL_STATEMENT);
		}

		this._map = new HashMap<String, Map<String, SystemConstant>>();
		if (systemConstantList != null) {
			for (SystemConstant systemConstant : systemConstantList) {
				if (!this._map.containsKey(systemConstant.getCategory())) {
					this._map.put(systemConstant.getCategory(), new HashMap<String, SystemConstant>());
				}
				this._map.get(systemConstant.getCategory()).put(systemConstant.getKey(), systemConstant);
			}
		} else {
			// TODO:ワーニング
		}
	}

	public Map<String, Map<String, SystemConstant>> getAllSystemConstant() {
		return this._map;
	}

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

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

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

	public SystemConstant getSystemConstant(String key) {
		return this._map.get("").get(key); //$NON-NLS-1$
	}
}
