package jp.yoyoyoyo.webformmanager.action;

import java.sql.SQLException;

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

import jp.yoyoyoyo.webformmanager.dao.CheckNewUserDAO;
import jp.yoyoyoyo.webformmanager.form.NewUserForm;
import jp.yoyoyoyo.webformmanager.model.LoginInfo;
import jp.yoyoyoyo.webformmanager.util.CommonUtil;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class NewUserAction extends Action {
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response){
		
		HttpSession session = request.getSession();
		NewUserForm newUserForm = (NewUserForm)form;
		// ログイン情報を取得
		LoginInfo info = (LoginInfo)session.getAttribute("loginData");
		// ログイン状態でないときエラー
		if(info == null){
			return mapping.findForward("maintenance");
		}
		// UserManagerでないときエラー
		if(!info.isRoleUserManager()){
			return mapping.findForward("maintenance");
		}
		
		if(newUserForm.getNewUserBack() != null && !newUserForm.getNewUserBack().equals("")){	// 戻るボタンを押したとき
			return mapping.findForward("userManager");	
		} else if(newUserForm.getNewUserNext() != null && !newUserForm.getNewUserNext().equals("")){	// 次へボタンを押したとき
			// リクエストデータをフォームにコピー		
			newUserForm.setPassword1(request.getParameter("password1"));
			newUserForm.setPassword2(request.getParameter("password2"));
			
			request.setAttribute("id", request.getParameter("id"));
			request.setAttribute("operatorName", request.getParameter("operatorName"));
			request.setAttribute("password1", request.getParameter("password1"));
			request.setAttribute("password2", request.getParameter("password2"));
			
			
			// バリデーションの実行
			ActionErrors errors = newUserForm.checkValidate(mapping, request);
			
			// オペレータIDがすでに登録されているか判定する
			CheckNewUserDAO dao = new CheckNewUserDAO();
			boolean isOperatorId;
			
			try{
				isOperatorId = dao.IsOperatorId(newUserForm.getId());
			} catch(SQLException e){
				return mapping.findForward("maintenance");
			}
			
			if(isOperatorId){
				errors.add("id", new ActionMessage("error.newUser.id.existsOperatorId"));
			}
						
			// バリデーションエラーが発生したとき
			if(errors.size() > 0){
				// エラー内容をセット
				saveErrors(request, errors);
				// 入力画面に戻る
				return mapping.findForward("newUser");
			}
			
			newUserForm.setRoleText(newUserForm.getRoleTextString());
			
			newUserForm.setMaskedPassword(CommonUtil.getMaskPassword(newUserForm.getPassword1()));
						
			session.setAttribute("newUserData", newUserForm);
			
			return mapping.findForward("newUserConfirm");	
		} else {
			return mapping.findForward("newUser");	
		}
	}
}
