package com.shin1ogawa.servlet;

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

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.entity.Message;
import com.shin1ogawa.service.BoardService;
import com.shin1ogawa.service.MessageService;

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

	BoardService boardService = new BoardService();
	MessageService service = new MessageService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		String boardId = req.getParameter("boardId");
		if (StringUtils.isEmpty(boardId)) {
			resp.sendRedirect("/");
			System.out.println("boardIdが指定されていません。");
			return;
		}
		if (!StringUtils.isNumeric(boardId)) {
			resp.sendRedirect("/");
			System.out.println("不正なboardId(数値でない)が指定されました。");
			return;
		}
		Board board = boardService.getById(Long.parseLong(boardId));
		if (board == null) {
			resp.sendRedirect("/");
			System.out.println("boardが存在しません。id=" + boardId);
			return;
		}
		String body = req.getParameter("body");
		if (StringUtils.isNotEmpty(body)) {
			Message message = MessageService.create(board, user, body);
			System.out.println("new message: " + message);
			Board save = boardService.save(board);
			System.out.println("update board: " + save);
			removeCache(board);
		}
		resp.sendRedirect("/board?id=" + boardId);
	}

	/**
	 * 保存した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) {
			//
		}
	}
}
