package jp.yoyoyoyo.webformmanager.action;

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

import jp.yoyoyoyo.webformmanager.form.EditPasswordForm;
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;

public class EditPasswordAction extends Action {
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response){
		HttpSession session = request.getSession();
		EditPasswordForm editPasswordForm = (EditPasswordForm)form;
		// ログイン情報の取得
		LoginInfo info = (LoginInfo)session.getAttribute("loginData");
		// ログインしていないときはエラー
		if(info == null){
			return mapping.findForward("maintenance");
		}
		// UserManagerでないときはエラー
		if(!info.isRoleUserManager()){
			return mapping.findForward("maintenance");
		}
		if(editPasswordForm.getEditPasswordBack() != null && !editPasswordForm.getEditPasswordBack().equals("")){	// 戻るボタンを押したとき
			return mapping.findForward("userManager");	
		} else if (editPasswordForm.getEditPasswordNext() != null && !editPasswordForm.getEditPasswordNext().equals("")){	// 次へボタンを押したとき
			// リクエストデータをフォームにコピー
			request.setAttribute("id", (String)session.getAttribute("userId"));
			request.setAttribute("password1", request.getParameter("password1"));
			request.setAttribute("password2", request.getParameter("password2"));
			
			// バリデーションの実行
			ActionErrors errors = editPasswordForm.checkValidate(mapping, request);
			
			// バリデーションエラーが発生したとき
			if(errors.size() > 0){
				// エラー内容をセット
				saveErrors(request, errors);
				// 入力画面に戻る
				return mapping.findForward("editPassword");
			}
			
			editPasswordForm.setId((String)session.getAttribute("userId"));
			editPasswordForm.setMaskedPassword(CommonUtil.getMaskPassword(editPasswordForm.getPassword1()));
			
			session.setAttribute("editPasswordData", editPasswordForm);
			
			return mapping.findForward("editPasswordConfirm");	
		} else {
			String id = request.getParameter("id");
			
			if(id == null || id.equals("")){
				// GETパラメータidがないときはセッションから取得
				id = (String)session.getAttribute("userId");
			} else { 
				session.setAttribute("userId", id);
			}
			
			request.setAttribute("id", (String)session.getAttribute("userId"));
			
			return mapping.findForward("editPassword");	
		
		}
		
	}
}
