package jp.agentec.sinaburocast.cache;

import jp.agentec.sinaburocast.common.util.CacheUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Abstractキャッシュ用クラス
 *
 *
 * @author tsukada
 *
 */
public abstract class AbstractCache<T> {
	private final Log logger= LogFactory.getLog(getClass());

	private Cache cache;
	
	protected void setCache(String cacheName) {
		cache = CacheUtil.getCache(cacheName);
	}

	/**
	 * キャッシュを探す
	 * 
	 * @param keys
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public T find(Object... keys) {
		String key = StringUtils.join(keys, "_");
		Element element = cache.get(key);
		if (element != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("find in cache " + element);
			}
			return (T)element.getObjectValue();
		}
		else {
			T obj = findRawValue(keys);
			cache.put(new Element(key, obj));
			return obj;
		}
	}

	/**
	 * 元データを探す
	 * 
	 * @param key
	 * @return
	 */
	protected abstract T findRawValue(Object... key);

	/**
	 * すべてクリアする
	 * 
	 */
	public void removeAll() {
		cache.removeAll();
	}

	/**
	 * 引数に該当するキャッシュを削除する
	 * 
	 * @return
	 */
	public boolean remove(Object... keys) {
		String key = StringUtils.join(keys, "_");
		return cache.remove(key);
	}

}