/* $Id: NotifyAction.java,v 1.7 2005/08/26 04:45:14 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.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

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

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.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.security.Role;
import jp.co.argo21.nautica.workflow.security.User;
import jp.co.argo21.nautica.workflow.security.simple.RoleManagerRemote;
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.7 $
 * @since   Nautica Workflow 0.9
 */
public class NotifyAction extends Action {

    /**
     * 同報確認処理を行う。
     * 
	 * @param mapping アクションマッピング
	 * @param form アクションフォーム
	 * @param request リクエスト
	 * @param response レスポンス
	 * @return アクションフォワード
     */
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
    {        
        // 申請書番号を取得
        String appID = (String) request.getSession().getAttribute("appid");
        
        // セッションからユーザ情報と、ハッシュテーブルを取得
        UserBean userbean = (UserBean) request.getSession().getAttribute("user");
        Hashtable widhash = (Hashtable) request.getSession().getAttribute("getwid");
        
        // セッションID、ワークアイテムIDを取得
        String sessionID = userbean.getSessionID();
        String wid = (String) widhash.get(appID);
        
        try {
            // ログインユーザのロールを見て、プロセス変数を変更する
            User user = userbean.getUser();
            RoleManagerRemote roleManager = SingletonServices.getInstance().getRoleManager();
            Role[] attachedRoles = roleManager.getAttachedRoles(user);
            Attribute attr = new Attribute();
            attr.setType(3);        
            List list = new ArrayList();
            for (int i = 0; i < attachedRoles.length; i++) {
                list.add(attachedRoles[i].getID());
            }        
            if (list.contains("JINJI_KACHO_ROLE")) {
                attr.setName("NOTIFICATION_JINJI_KACHO");
            } else if (list.contains("JINJI_BUCHO_ROLE")) {
                attr.setName("NOTIFICATION_JINJI_BUCHO");
            }        
            attr.setValue("true");
            WorkItemHandler itemhandler = SingletonServices.getInstance().getWfWorkitemHandler();
            itemhandler.assignWorkItemAttribute(sessionID, wid, attr);        

            // ワークアイテムの完了をエンジンに通知
            itemhandler.completeWorkItem(sessionID, wid);
            
            // 申請トランザクションテーブルの[状態]を変更
            AppTransactionDAO apptDAO = DAOFactory.getAppTransactionDAO();
            AppTransaction appt = apptDAO.getAppTransactionByAppIDUserID(appID, user.getID());
            appt.setAppStatus(StatusConstants.STATUS_TRANS_CONFIRMED);
            apptDAO.updateStatus(appt);

            // リクエストに値をセット
            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 (ServiceException e) {
            // セッション無効化
            request.getSession().invalidate();
            // エンジン接続に失敗（ワークアイテムハンドラ取得失敗）
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (NamingException 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();
            // エンジン接続に失敗（ワークアイテム属性・ユーザID取得失敗）
            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);
        }
    }
}