/**
 * BoardForm에 대한 컨트롤러
 * 게시물 수정/입력시 사용
 */
package org.springframework.samples.kyuriboard.web.spring;

import java.util.Map;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import org.apache.log4j.Logger;

import org.springframework.samples.kyuriboard.domain.Board;
import org.springframework.samples.kyuriboard.domain.logic.KyuriBoardFacade;

/**
 * @author DAMI(archy712@naver.com)
 *
 */
public class BoardFormController extends SimpleFormController {
	
	private Logger logger = Logger.getLogger(getClass());
	
	public static final String[] HTMLYNS = {"Y", "N"};
	
	// ----------------------------------------
	// Setter Injection
	// ----------------------------------------
	private KyuriBoardFacade kyuriBoard;
	
	public void setkyuriBoard(KyuriBoardFacade kyuriBoard) {
		this.kyuriBoard = kyuriBoard;
	}
	
	public BoardFormController() {
		setSessionForm(true);
		setValidateOnBinding(false);
		setCommandName("boardForm");
		setFormView("boardForm");
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		
		if (logger.isInfoEnabled()) {
			logger.info("formBackingObject() 호출");
		}
		
		if (request.getParameter("boardId") != null) {
			return new BoardForm(this.kyuriBoard.getBoardByBoardId(new Integer(request.getParameter("boardId")).intValue()));
		} else {
			return new BoardForm();
		}
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
	 */
	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
		// TODO Auto-generated method stub
		
		if (logger.isInfoEnabled()) {
			logger.info("onBindAndValidate() 호출");
		}
		
		BoardForm boardForm = (BoardForm) command;
		Board board = boardForm.getBoard();
		
		// 구동서버가 톰캣일 경우에 한글 처리
		// 나중에 리팩토링시 [구동 WAS] 변수를 사용하여 처리를 할 것.
		board.setTitle(new String(board.getTitle().getBytes("8859_1"), "euc-kr"));
		board.setContent(new String(board.getContent().getBytes("8859_1"), "euc-kr"));		
		
		errors.setNestedPath("board");
		getValidator().validate(board, errors);
		errors.setNestedPath("");
		
		// 부가적인 유효성 검사
		if ((boardForm.getBoard().getTitle() == null) || ((boardForm.getBoard().getTitle() != null) && (boardForm.getBoard().getTitle().length() < 10))) {
			errors.reject("TITLE_NOTCORRECT", "제목은 10글자 이상이어야 합니다");
		}
		
		if ((boardForm.getBoard().getContent() == null) || ((boardForm.getBoard().getTitle() != null) && (boardForm.getBoard().getContent().length() < 10))) {
			errors.reject("TITLE_NOTCORRECT", "내용은 10글자 이상이어야 합니다");
		}
	}
	

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
	 */
	protected Map referenceData(HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		Map model = new HashMap();
		model.put("htmlyns", HTMLYNS);
		return model;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		// TODO Auto-generated method stub	
		
		if (logger.isInfoEnabled()) {
			logger.info("onSubmit() 호출");
		}
		
		BoardForm boardForm = (BoardForm) command;
		Board board = boardForm.getBoard();
		
		UserSession userSession = (UserSession) request.getSession().getAttribute("userSession");
		board.setUserIp(request.getRemoteAddr());
		board.setUserId(userSession.getUser().getUserId());		
		board.setVisited(0);
		board.setRecom(0);
		board.setInsertDate(new java.util.Date());
		
		if (logger.isInfoEnabled()) {
			logger.info("userIp : " + board.getUserIp());
			logger.info("userId : " + board.getUserId());
			logger.info("title : " + board.getTitle());
			logger.info("content : " + board.getContent());
			logger.info("htmlyn : " + board.getHtmlyn());
		}
		
		try {
			if (boardForm.isNewBoard()) {
				this.kyuriBoard.insertBoard(board);
			} else {
				this.kyuriBoard.updateBoard(board);
			}
		} catch (Exception ex) {
			System.out.println("에러 : " + ex.getMessage());
			return showForm(request, response, errors);
		}
		
		return super.onSubmit(request, response, command, errors);
	}	
	
	

}
