/*
 * 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 nuts.core.image.Images;
import nuts.core.lang.Classes;
import nuts.core.lang.Methods;
import nuts.core.lang.collection.SafeMap;
import nuts.core.orm.dao.DataAccessClientProxy;
import nuts.gae.dao.GaeDataAccessClientFactory;
import nuts.gae.image.GaeImages;
import nuts.gae.taskqueue.GaeTaskQueueFactory;
import nuts.gae.vfs.ngfs.provider.GaeVFS;

import java.util.HashMap;
import java.util.Map;

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

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 = Classes.getClass("ognl.OgnlRuntime");
		if (ognl != null) {
			Methods.invokeStaticMethod(ognl, "setSecurityManager", new Object[] { null }, new Class[] { SecurityManager.class });
		}

		Images.setMe(new GaeImages());

		GaeVFS.init();
		
		GaeTaskQueueFactory.setInstance(new GaeTaskQueueFactory());
	}

	@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);
	}
}
