package jp.yoyoyoyo.webformmanager.action;

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

import jp.yoyoyoyo.webformmanager.dao.InsertStatusHistoryDAO;
import jp.yoyoyoyo.webformmanager.form.StatusChangeConfirmForm;
import jp.yoyoyoyo.webformmanager.model.ChangeStatusData;
import jp.yoyoyoyo.webformmanager.model.LoginInfo;

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 StatusChangeConfirmAction extends Action {
		public ActionForward execute(ActionMapping mapping,
				ActionForm form,
				HttpServletRequest request,
				HttpServletResponse response){
			
			HttpSession session = request.getSession();
			StatusChangeConfirmForm statusChangeConfirmForm = (StatusChangeConfirmForm)form; 
			
			// ログイン情報を取得
			LoginInfo info = (LoginInfo)session.getAttribute("loginData");
			
			// ログインしていないときはエラー
			if(info == null){
				return mapping.findForward("maintenance");
			}
			
			// Writeでないときはエラー
			if(!info.isRoleWrite()){
				return mapping.findForward("maintenance");
			}
			
			if(statusChangeConfirmForm.getStatusChangeConfirmBack() != null && !statusChangeConfirmForm.getStatusChangeConfirmBack().equals("")){	// 戻るボタンを押したとき
				// 値を復元
				ChangeStatusData data = (ChangeStatusData)session.getAttribute("statusChangeData");
				
				request.setAttribute("id", data.getId());
				request.setAttribute("status", data.getNewStatus());
				request.setAttribute("comment", data.getComment());
				
				return mapping.findForward("statusChange");
			} else if(statusChangeConfirmForm.getStatusChangeConfirmSave() != null && !statusChangeConfirmForm.getStatusChangeConfirmSave().equals("")){	// 保存ボタンを押したとき
				// ステータスの更新を行う
				InsertStatusHistoryDAO dao = new InsertStatusHistoryDAO();
				
				ChangeStatusData data = (ChangeStatusData)session.getAttribute("statusChangeData");
				
				data.setOperatorId(info.getOperatorId());
				
				try{
					dao.executeSP(data);
				} catch(Exception e){
					return mapping.findForward("maintenance");
				}
			
				// セッションのクリア
				session.removeAttribute("statusChangeData");
						
				return mapping.findForward("messageBox");
			} else {
				request.setAttribute("data", session.getAttribute("statusChangeData"));
				
				return mapping.findForward("statusChangeConfirm");
			
			}
			
		}
}
