package jp.yoyoyoyo.webformmanager.action;

import java.security.MessageDigest;
import java.sql.SQLException;

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

import jp.yoyoyoyo.webformmanager.dao.UpdatePasswordDAO;
import jp.yoyoyoyo.webformmanager.form.ChangePasswordConfirmForm;
import jp.yoyoyoyo.webformmanager.form.ChangePasswordForm;
import jp.yoyoyoyo.webformmanager.util.CommonUtil;

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

public class ChangePasswordConfirmAction extends Action {
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response){
		HttpSession session = request.getSession();
		ChangePasswordConfirmForm changePasswordConfirmForm = (ChangePasswordConfirmForm)form;
		
		if(changePasswordConfirmForm.getChangePasswordConfirmBack() != null && !changePasswordConfirmForm.getChangePasswordConfirmBack().equals("")){
			ChangePasswordForm  changePasswordForm = (ChangePasswordForm)session.getAttribute("changePasswordData");
			
			request.setAttribute("id", changePasswordForm.getId());
			request.setAttribute("oldPassword", changePasswordForm.getOldPassword());
			request.setAttribute("password1", changePasswordForm.getPassword1());
			request.setAttribute("password2", changePasswordForm.getPassword2());
			return mapping.findForward("changePassword");	
		} else if(changePasswordConfirmForm.getChangePasswordConfirmSave() != null && !changePasswordConfirmForm.getChangePasswordConfirmSave().equals("")){
			ChangePasswordForm  changePasswordForm = (ChangePasswordForm)session.getAttribute("changePasswordData");
			
			// パスワードをSHA-256で暗号化
			byte[] binary = changePasswordForm.getPassword1().getBytes();
			MessageDigest md;
			try{
				md = MessageDigest.getInstance("SHA-256");
				byte[] digest = md.digest(binary);
					
				changePasswordForm.setEncryptedPassword(CommonUtil.bytesToHexString(digest));
			}catch(Exception e){
				// エラーが発生したとき
				return mapping.findForward("maintenance");
			}
			
			UpdatePasswordDAO dao = new UpdatePasswordDAO();
			
			try {
				dao.executeSP(changePasswordForm, 0);
			} catch (SQLException e) {
				
				return mapping.findForward("maintenance");
			}
			
			session.removeAttribute("changePasswordData");
			
			return mapping.findForward("messageBox2");	
		} else {
			ChangePasswordForm  changePasswordForm = (ChangePasswordForm)session.getAttribute("changePasswordData");
			
			request.setAttribute("data", changePasswordForm);
			
			return mapping.findForward("changePasswordConfirm");	
		}
	}
}
