package farm.example.ifrog;


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

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;


/**
 * 
 * @author yupong7@gmail.com
 * @author mimoto
 */
public class StationCache {

	/** キャッシュ */
	private static Cache _cache = null;


	/**
	 * キャッシュを取得する
	 * 
	 * @return キャッシュ
	 * @throws GenbuException
	 */
	static Cache getCache() throws CacheException {
		if (null == _cache) {
			Map<Integer, Integer> props = new HashMap<Integer, Integer>();
			props.put(GCacheFactory.EXPIRATION_DELTA, 3600);
			CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			_cache = cacheFactory.createCache(props);
		}
		return _cache;
	}


	public static void setCache() throws CacheException {
		List<Station> stationList;
		Map<Long, Station> stationMap;
		stationList = new ArrayList<Station>();
		for (int i = 0; 10 > i; i++) {
			Station rec = new Station();
			rec.setLineCd(Long.valueOf(i));
			rec.setName("駅名" + i);
			stationList.add(rec);
		}

		stationMap = new HashMap<Long, Station>();
		for (Station rec : stationList) {
			stationMap.put(rec.getLineCd(), rec);
		}

		Cache cache = getCache();
		cache.put(Station.class.getSimpleName() + "List", stationList);
		cache.put(Station.class.getSimpleName() + "Map", stationMap);
	}


	public static List<Station> getStationList() throws CacheException {
		Cache cache = getCache();
		if (!cache.containsKey(Station.class.getSimpleName() + "List")) {
			setCache();
		}
		return (List<Station>) cache.get(Station.class.getSimpleName() + "List");
	}


	public static Map<Long, Station> getStationMap() throws CacheException {
		Cache cache = getCache();
		if (!cache.containsKey(Station.class.getSimpleName() + "Map")) {
			setCache();
		}
		return (Map<Long, Station>) cache.get(Station.class.getSimpleName() + "Map");
	}

}
