/**
 * 
 */
package org.springframework.samples.kyuriboard.web.spring;

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

import org.apache.oro.text.perl.Perl5Util;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;

import org.springframework.web.util.WebUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import org.springframework.dao.DataIntegrityViolationException;

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

import org.apache.log4j.Logger;

/**
 * @author DAMI(archy712@naver.com)
 *
 */
public class UserFormController extends SimpleFormController {
	
	private static Logger logger = Logger.getLogger(UserFormController.class);
	
	private KyuriBoardFacade kyuriBoard;	

	/**
	 * @param kyuriBoard the kyuriBoard to set
	 */
	public void setKyuriBoard(KyuriBoardFacade kyuriBoard) {
		this.kyuriBoard = kyuriBoard;
	}

	/**
	 * Constructor
	 */
	public UserFormController() {
		setSessionForm(true);
		setValidateOnBinding(false);
		setCommandName("userForm");
		setFormView("userForm");
	}

	/* (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
		UserForm userForm = (UserForm) command;
		User user = userForm.getUser();
		
		//user.setUserName(new String(user.getUserName().getBytes("8859_1"), "euc-kr"));
		user.setInsertDate(new java.util.Date());
		
		try {
			if (userForm.isNewUser()) {
				this.kyuriBoard.insertUser(user);
			} else {
				this.kyuriBoard.updateUser(user);
			}
		} catch (DataIntegrityViolationException ex) {
			errors.rejectValue("user.userId", "USERID_ALREADY_EXISTS", "회원ID가 이미 존재합니다. 다른 ID를 입력해 주세요");
			return showForm(request, response, errors);
		}
		
		// 새로운 세션 설정
		UserSession userSession = new UserSession(this.kyuriBoard.getUserByUserId(userForm.getUser().getUserId()));
		request.getSession().setAttribute("userSession", userSession);
		
		return super.onSubmit(request, response, command, errors);
	}

	/* (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
		UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
		if (userSession != null) {
			return new UserForm(this.kyuriBoard.getUserByUserId(userSession.getUser().getUserId()));
		} else {
			return new UserForm();
		}
	}

	/* (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
		UserForm userForm = (UserForm) command;
		User user = userForm.getUser();
		
		if (user.getUserName() != null) {
			user.setUserName(new String(user.getUserName().getBytes("8859_1"), "euc-kr"));
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug("userName : " + user.getUserName());
		}
		
		errors.setNestedPath("user");
		getValidator().validate(user, errors);
		errors.setNestedPath("");

		// 부가적인 유효성 검증
		if (userForm.isNewUser()) {
			ValidationUtils.rejectIfEmpty(errors, "user.userId", "USERID_REQUIRED", "회원ID가 필요합니다");
			if (user.getPasswd() == null || user.getPasswd().length() < 1 ||
					!user.getPasswd().equals(userForm.getRepeatedPasswd())) {
				errors.reject("PASSWD_MISMATCH", "비밀번호가 존재하지 않거나 맞지 않습니다.");
			}
		} else if (user.getPasswd() != null && user.getPasswd().length() > 0) {
			if (!user.getPasswd().equals(userForm.getRepeatedPasswd())) {
				errors.reject("PASSWD_MISMATCH", "비밀번호가 존재하지 않거나 맞지 않습니다");
			}			
		}
		
		if (user.getPasswd() != null && user.getPasswd().length() < 4) {
			errors.reject("PASSWD_TOO_SHORT", "비밀번호는 최소 4자리 이상이어야 합니다");
		}
		
		if (userForm.getRepeatedPasswd() != null && userForm.getRepeatedPasswd().length() < 4) {
			errors.reject("REPEATEDPASSWD_TOO_SHORT", "확인 비밀번호는 최소 4자리 이상이어야 합니다");
		}
		
		if (user.getUserId() != null && user.getUserId().length() < 4) {
			errors.reject("USERID_TOO_SHORT", "회원ID는 최소 4자리 이상이어야 합니다");
		}
		
		if (user.getUserName() != null && user.getUserName().length() < 2) {
			errors.reject("USERNAME_TOO_SHORT", "회원 이름은 최소 2자리 이상이어야 합니다");
		}
		
		// 회원ID 영문 검사
		
		// 이메일 검사
		String EMAIL_REGEXP = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
		Perl5Util perl5Util = new Perl5Util();
		if (!perl5Util.match(EMAIL_REGEXP, user.getEmail())) {
			errors.reject("INVALID_EMAIL", "이메일 형식이 잘못되었습니다");
		}
		
	}
	
	
	
	

}
