/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import net.sf.ehcache.jcache.JCache;

import nuts.core.lang.ClassLoaders;
import nuts.core.lang.Strings;

import java.io.InputStream;
import java.util.List;

public class EHCacheHelper {
	private static final String EHCACHE_CONFIG = "ehcache.xml";

	public static JCache buildJCache() throws Exception {
		return buildJCache(null, 0);
	}
	
	public static JCache buildJCache(String cacheName, int cacheExpire) throws Exception {
		Configuration conf = null;
		
		InputStream is = ClassLoaders.getResourceAsStream(EHCACHE_CONFIG);
		if (is == null) {
			is = EHCacheHelper.class.getResourceAsStream(EHCACHE_CONFIG);
			if (is == null) {
				return null;
			}
		}
		
		conf = ConfigurationFactory.parseConfiguration(is);
		is.close();

		CacheConfiguration cc = null;
		if (Strings.isEmpty(cacheName)) {
			cacheName = "_default";
			cc = conf.getCacheConfigurations().get(cacheName);
			if (cc == null) {
				cc = conf.getDefaultCacheConfiguration();
				cc = cc.clone();
				cc.setName(cacheName);
				conf.addCache(cc);
			}
		}
		else {
			cc = conf.getCacheConfigurations().get(cacheName);
		}

		if (cacheExpire > 0) {
			cc.setTimeToLiveSeconds(cacheExpire);
		}
		
		CacheManager manager = new CacheManager(conf);
		return new JCache(manager.getCache(cacheName));
	}
	
	public static void shutdownCache() {
		List knownCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
		while (!knownCacheManagers.isEmpty()) {
			((CacheManager)CacheManager.ALL_CACHE_MANAGERS.get(0)).shutdown();
		}
	}
}
