package com.shin1ogawa.page;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.t2framework.t2.annotation.core.Default;
import org.t2framework.t2.annotation.core.Page;
import org.t2framework.t2.contexts.WebContext;
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 com.google.inject.servlet.RequestParameters;
import com.google.inject.servlet.RequestScoped;
import com.shin1ogawa.service.IMessagesService;
import com.shin1ogawa.service.MessagesService;
import com.shin1ogawa.util.CacheUtil;

/**
 * @author shin1ogawa
 */
@RequestScoped
@Page("addMessage")
public class AddMessage {

	private static final Logger LOGGER = LoggerFactory.getLogger(ListMessage.class);

	@Inject
	@RequestParameters
	Map<String, String[]> params;

	@Inject
	IMessagesService service;

	@Inject
	HttpServletRequest request;


	/**
	 * TODO for shin1ogawa
	 * @param context
	 * @return {@link Navigation}
	 */
	@Default
	public Navigation add(WebContext context) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		final String message = params.get("message") != null ? params.get("message")[0] : null;
		if (StringUtils.isEmpty(message)) {
			return new SimpleText("メッセージが入力されていません。");
		} else if (user == null) {
			return new SimpleText("ログインしていません。");
		} else {
			service.newMessage(user, message);
			CacheUtil.removeCache(MessagesService.class.getName());
			LOGGER.info("add from " + request.getRemoteAddr());
			return new Redirect("index.html");
		}
	}
}
