package jp.yoyoyoyo.webformmanager.action;

import java.sql.SQLException;
import java.util.List;

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

import jp.yoyoyoyo.webformmanager.dao.RequestDataDAO;
import jp.yoyoyoyo.webformmanager.dao.StatusHistoryDAO;
import jp.yoyoyoyo.webformmanager.form.DetailForm;
import jp.yoyoyoyo.webformmanager.model.LoginInfo;
import jp.yoyoyoyo.webformmanager.model.RequestData;
import jp.yoyoyoyo.webformmanager.model.StatusHistory;

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 DetailAction extends Action {
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response){
		
		DetailForm detailForm = (DetailForm)form;
		HttpSession session = request.getSession();
		
		// ログイン情報の取得
		LoginInfo info = (LoginInfo)session.getAttribute("loginData");
		
		// ログインしていないときはエラー
		if(info == null){
			return mapping.findForward("maintenance");
		}
		
		// Read or Writeでないときはエラー
		if(!(info.isRoleRead() || info.isRoleWrite())){
			return mapping.findForward("maintenance");
		}
		
		if(detailForm.getBack() != null && !detailForm.getBack().equals("")){	// 戻るボタンを押したとき
			return mapping.findForward("status");	
		} else if(detailForm.getStatusChange() != null && !detailForm.getStatusChange().equals("")){	// ステータス更新ボタンを押したとき
			return mapping.findForward("statusChange");	
		} else {
			// Getパラメータの取得
			String id = request.getParameter("id");
			
			if(id == null || id.equals("")){
				// GETパラメータidがないときはセッションから取得
				id = (String)session.getAttribute("detailId");
			} else { 
				session.setAttribute("detailId", id);
			}
			
			// データの取得
			// 履歴データの取得
			RequestDataDAO dao = new RequestDataDAO();
			RequestData data = null;
			
			StatusHistoryDAO dao2 = new StatusHistoryDAO();
			List<StatusHistory> list = null;
			
			try {
				data = dao.getRequestDataByID(Integer.valueOf(id));
				
				list = dao2.getStatusHistory(Integer.valueOf(id));
			} catch (SQLException e) {
				return mapping.findForward("maintenance");
			} catch (Exception e){
				return mapping.findForward("maintenance");
			}
			
			request.setAttribute("requestData", data);
			
			request.setAttribute("statusList", list);
			
			session.setAttribute("detailStatus", data.getStatus());
			
			return mapping.findForward("detail");		
		}
		

	}
}
