package ${package}.page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

import org.apache.commons.lang.StringUtils;
import org.t2framework.t2.annotation.composite.POST;
import org.t2framework.t2.annotation.core.Ajax;
import org.t2framework.t2.annotation.core.Default;
import org.t2framework.t2.annotation.core.Page;
import org.t2framework.t2.annotation.core.RequestParam;
import org.t2framework.t2.navigation.Json;
import org.t2framework.t2.navigation.Redirect;
import org.t2framework.t2.navigation.SimpleText;
import org.t2framework.t2.spi.Navigation;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.inject.Inject;

import ${package}.entity.SampleEntity;
import ${package}.logic.SampleEntityLogic;

@Page("index")
public class IndexPage {
	@Inject SampleEntityLogic logic;
	
	@Ajax
	@Default
	public Navigation list() {
		List<SampleEntity> list = getEntities();
		List<SampleEntity> result = new ArrayList<SampleEntity>(list.size());
		result.addAll(list);
		return new Json(ResultObject.createResultObject(result));
	}

	@POST
	public Navigation post(@RequestParam("message") String message) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (StringUtils.isEmpty(message)) {
			return new SimpleText("メッセージが入力されていません。");
		} else {
			SampleEntity entity = SampleEntityLogic.create(user, message);
			logic.save(entity);
			removeCache();
			return new Redirect("index.html");
		}
	}

	@SuppressWarnings("unchecked")
	private List<SampleEntity> getEntities() {
		String key = SampleEntity.class.getName();
		Cache cache = null;
		try {
			cache = CacheManager.getInstance().getCacheFactory().createCache(
					Collections.emptyMap());
			if (cache.containsKey(key)) {
				return (List<SampleEntity>) cache.get(key);
			}
		} catch (CacheException e) {
			//
		}
		Query query = logic.newQuery();
		query.setOrdering("created desc");
		List<SampleEntity> list = logic.list(query);
		if (cache != null) {
			cache.put(key, list);
		}
		return list;
	}

	private void removeCache() {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			String key = SampleEntity.class.getName();
			if (cache.containsKey(key)) {
				cache.remove(key);
			}
		} catch (CacheException e) {
			//
		}
	}
}
