package com.shin1ogawa.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserServiceFactory;
import com.shin1ogawa.entity.Board;
import com.shin1ogawa.service.BoardService;

@SuppressWarnings("serial")
public class Index extends HttpServlet {

	BoardService service = new BoardService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("user", UserServiceFactory.getUserService()
				.getCurrentUser());
		req.setAttribute("loginUrl", UserServiceFactory.getUserService()
				.createLoginURL(req.getRequestURI()));
		req.setAttribute("logoutUrl", UserServiceFactory.getUserService()
				.createLogoutURL(req.getRequestURI()));
		req.setAttribute("boards", getBoards());
		req.setAttribute("noBoards", getBoards().isEmpty());
		req.getRequestDispatcher("/index.jsp").forward(req, resp);
	}

	/**
	 * Board一覧を返す。
	 * <p>
	 * キャッシュがあればそれを使用し、キャッシュがなければDBから取得してキャッシュする。
	 * </p>
	 * 
	 * @return Board一覧
	 */
	@SuppressWarnings("unchecked")
	private List<Board> getBoards() {
		String key = Board.class.getName();
		Cache cache = null;
		try {
			cache = CacheManager.getInstance().getCacheFactory().createCache(
					Collections.emptyMap());
			if (cache.containsKey(key)) {
				return (List<Board>) cache.get(key);
			}
		} catch (CacheException e) {
			//
		}
		Query query = service.newQuery();
		query.setOrdering("created desc");
		List<Board> list = service.list(query);
		if (cache != null) {
			cache.put(key, list);
		}
		return list;
	}
}
