/* $Id: ApprovalRetryAction.java,v 1.8 2005/08/26 04:45:16 ysahara Exp $
*
* Copyright (c)ARGO 21, Corporation. 2005.  All rights reserved.
 * 
 * This file is part of Nautica Workflow.
 * 
 *  Nautica Workflow is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 * 
 *  Nautica Workflow is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with Nautica Workflow; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *  
*/
package jp.co.argo21.nautica.workflow.sample.action;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

import jp.co.argo21.nautica.workflow.sample.actionform.ApprovalCommentForm;
import jp.co.argo21.nautica.workflow.sample.actionform.UserBean;
import jp.co.argo21.nautica.workflow.sample.model.AppTransaction;
import jp.co.argo21.nautica.workflow.sample.model.Application;
import jp.co.argo21.nautica.workflow.sample.model.dao.AppTransactionDAO;
import jp.co.argo21.nautica.workflow.sample.model.dao.DAOFactory;
import jp.co.argo21.nautica.workflow.sample.util.SingletonServices;
import jp.co.argo21.nautica.workflow.sample.util.StatusConstants;
import jp.co.argo21.nautica.workflow.sample.util.Constants;
import jp.co.argo21.nautica.workflow.soap.WorkItemHandler;
import jp.co.argo21.nautica.workflow.soap.message.Attribute;

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

/**
 * 申請画面で差し戻しボタン押下時の処理を行うアクションクラス。
 * 
 * @author  ruchida(Argo 21, Corp.)
 * @version $Revision: 1.8 $
 * @since   Nautica Workflow 0.9
 */
public class ApprovalRetryAction extends Action {

    /**
     * 申請を差し戻す。
     * 
     * @param mapping アクションマッピング
     * @param form アクションフォーム
     * @param request リクエスト
     * @param response レスポンス
     * @return アクションフォワード
     */
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
    {
        // セッションおよびリクエストから申請内容取得
        ApprovalCommentForm approvalForm = (ApprovalCommentForm)form;
        UserBean user = (UserBean)request.getSession().getAttribute("user");
        String sessionID = user.getSessionID();
        Application app = (Application) request.getSession().getAttribute("appmodel");
        String appID = app.getId();
        String wid = (String) request.getSession().getAttribute("wid");
        
        try {
            // 申請トランザクションテーブルの[状態]が"WAIT"で、
            // [承認ブロック番号]が最小のレコードを取得
            AppTransactionDAO appTransDao = DAOFactory.getAppTransactionDAO();
            AppTransaction[] appTranses = appTransDao.getAppTransactionsByAppID(appID);
            AppTransaction appTrans = null;
            for (int i = 0; i < appTranses.length; i++) {
                String status = appTranses[i].getAppStatus();
                if ((StatusConstants.STATUS_TRANS_WAIT).equals(status)) {
                    appTrans = appTranses[i];
                    break;
                }
            }
            
            // 取得した申請トランザクションテーブルの
            // [状態][申請者/承認者ユーザID][コメント][対象日]を更新
            if (appTrans != null) {
                appTrans.setAppStatus(StatusConstants.STATUS_TRANS_RETRY);
                appTrans.setAppUserID(user.getUserID());
                appTrans.setComment(approvalForm.getComment());
                appTrans.setDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
                appTransDao.updateAppTransaction(appTrans);
                
                // 申請者の[状態]を”待ち”に変更
                AppTransaction applyTrans = appTransDao.getAppTransactionByAppIDBlockID(appID, 0);
                applyTrans.setAppStatus(StatusConstants.STATUS_TRANS_WAIT);
                appTransDao.updateAppTransaction(applyTrans);
            }
            
            // 作業項目のプロセス変数[承認結果]に"RETRY"を設定
            WorkItemHandler wfWorkitemHandler = SingletonServices.getInstance().getWfWorkitemHandler();
            Attribute approvalResult = new Attribute();
            approvalResult.setName(Constants.APPROVAL_RESULT);
            approvalResult.setValue(Constants.RETRY);
            approvalResult.setType(1);
            wfWorkitemHandler.assignWorkItemAttribute(sessionID, wid, approvalResult);
            
            // 作業項目のプロセス変数[状態]に"APPLY_WAIT"を設定
            Attribute status = new Attribute();
            status.setName(Constants.STATUS);
            status.setValue(StatusConstants.APPLY_WAIT);
            status.setType(1);
            wfWorkitemHandler.assignWorkItemAttribute(sessionID, wid, status);
            
            // 作業項目の完了
            wfWorkitemHandler.completeWorkItem(sessionID,wid);

            // 申請書番号をリクエストに設定
            request.setAttribute("appid", appID);
            
            return mapping.findForward(Constants.SUCCESS);
        } catch (SQLException e) {
            // セッション無効化
            request.getSession().invalidate();
            // 致命的エラー
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (RemoteException e) {
            // セッション無効化
            request.getSession().invalidate();
            // 致命的エラー
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (ServiceException e) {
            // セッション無効化
            request.getSession().invalidate();
            // 致命的エラー
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (Exception e) {
            // セッション無効化
            request.getSession().invalidate();
            // 予期せぬエラー
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.UNEXPECTED_ERROR);
        }
    }
}