/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 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 java.util.HashMap;
import java.util.Map;

import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import nuts.core.collections.SafeMap;
import nuts.core.images.ImageFactory;
import nuts.core.lang.ClassUtils;
import nuts.core.lang.MethodUtils;
import nuts.core.net.HttpClientAgent;
import nuts.core.orm.dao.DataAccessClientProxy;
import nuts.gae.dao.GaeDataAccessClientFactory;
import nuts.gae.http.GaeConnectionManager;
import nuts.gae.images.GaeImageFactory;
import nuts.gae.taskqueue.GaeTaskQueueFactory;
import nuts.gae.vfs.ngfs.provider.GaeVFS;

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

/**
 */
public class WebApplet extends BaseApplet {
	/**
	 * @return the instance
	 */
	public static WebApplet get() {
		return (WebApplet)instance;
	}

	/**
	 * @return true if gae support
	 */
	public static boolean isGaeSupport() {
		return true;
	}

	/**
	 * @throws Exception if an error occurs
	 */
	@Override
	protected void initialize() throws Exception {
		super.initialize();
		
		Class ognl = ClassUtils.getClass("ognl.OgnlRuntime");
		if (ognl != null) {
			MethodUtils.invokeStaticMethod(ognl, "setSecurityManager", new Object[] { null }, new Class[] { SecurityManager.class });
		}

		ImageFactory.setInstance(new GaeImageFactory());

		GaeVFS.init();
		
		GaeTaskQueueFactory.setInstance(new GaeTaskQueueFactory());
		
		HttpClientAgent.setDefaultClientConnectionManager(new GaeConnectionManager());
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void buildCache() throws Exception {
		CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
		Map<String, Object> props = new HashMap<String, Object>();
		int ce = getPropertyAsInt("cache.expire", 0);
		if (ce > 0) {
			props.put(GCacheFactory.EXPIRATION_DELTA, ce);
		}
		cache = new SafeMap(cacheFactory.createCache(props));
	}

	/**
	 * @throws Exception if an error occurs
	 */
	@Override
	protected void buildDataAccessClient() throws Exception {
		log.info("Building DataAccessClient ...");

		dataAccessClient = GaeDataAccessClientFactory.buildDataAccessClient(properties);

		DataAccessClientProxy.setDataAccessClient(dataAccessClient);
	}

	@Override
	protected void initUploadSetting() throws Exception {
	}
}
