package com.shin1ogawa.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.logging.Logger;

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

import org.apache.commons.lang.StringUtils;

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

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

	BoardService service = new BoardService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		String title = req.getParameter("title");
		if (StringUtils.isNotEmpty(title)) {
			Board board = BoardService.create(user, title);
			board = service.save(board);
			Logger.getLogger(PostBoard.class.getName()).info(
					"new board: " + board);
			removeCache(board);
			resp.sendRedirect("/board?id=" + board.getId());
		} else {
			resp.sendRedirect("/");
		}
	}

	/**
	 * 保存したBoardと、Board一覧のキャッシュがあれば削除する。
	 * 
	 * @param board
	 */
	private void removeCache(Board board) {
		String key = Board.class.getName() + "\\" + board.getId();
		try {
			// IDに対応するBoard
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			Cache cache = cacheFactory.createCache(Collections.emptyMap());
			if (cache.containsKey(key)) {
				cache.remove(key);
			}
			// Board一覧
			key = Board.class.getName();
			if (cache.containsKey(key)) {
				cache.remove(key);
			}
		} catch (CacheException e) {
			//
		}
	}
}
