/* $Id: ShowApprovalListAction.java,v 1.8 2005/08/26 04:45:12 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.HashMap;
import java.util.List;
import java.util.Map;

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.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.ResourceManager;
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.simple.RoleManagerRemote;
import jp.co.argo21.nautica.workflow.soap.WorkItemHandler;
import jp.co.argo21.nautica.workflow.soap.message.Filter;
import jp.co.argo21.nautica.workflow.soap.message.WorkItem;

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 ShowApprovalListAction extends Action {

    /**
     * 承認待ち申請一覧を取得する。
     * 
	 * @param mapping アクションマッピング
	 * @param form アクションフォーム
	 * @param request リクエスト
	 * @param response レスポンス
	 * @return アクションフォワード
	 */
	public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
    {

        // リクエストからユーザ情報を取得    
        UserBean userBean = (UserBean) request.getSession().getAttribute("user");
        String sessionID = userBean.getSessionID();
    
        try {
            // プロセス変数[状態]が"APPROVAL_WAIT"に一致する作業項目のリストを取得
            WorkItemHandler wfWorkitemHandler = SingletonServices.getInstance().getWfWorkitemHandler();
            Filter[] filter = new Filter[1];
            Filter status = new Filter();
            status.setType(5003);
            status.setFilterName(Constants.STATUS);
            status.setFilterString(StatusConstants.APPROVAL_WAIT);
            status.setComparison(1);
            filter[0] = status;
            WorkItem[] items = wfWorkitemHandler.getWorkItems(sessionID, filter);
            
            // 作業項目IDから、プロセス変数[申請書番号]を取得し、
            // 申請書番号を元に個別テーブルから申請の内容を取得
            ArrayList appList = new ArrayList();
            Map wids = new HashMap();
            for (int i = 0; i < items.length; i++) {
                WorkItem item = items[i];
                String wid = item.getID();
                
                String appID = wfWorkitemHandler.getWorkItemAttributeValue(
                        sessionID, wid, Constants.APPLICATION_NO).getValue();
                
                AppTransactionDAO appTransDao = DAOFactory.getAppTransactionDAO();
                AppTransaction appTrans = appTransDao.getAppTransactionByAppIDUserID(appID, userBean.getUserID());
                if (appTrans != null && (appTrans.getAppStatus()).equals(StatusConstants.STATUS_TRANS_WAIT)) {
                    Application app = DAOFactory.getApplicationDAO().getApplicationByID(appID);
                    wids.put(appID, wid);
                    
                    appList.add(app);
                } else {
                    // ログインユーザが人事部の一般社員の場合、承認可能
                    RoleManagerRemote rmr = SingletonServices.getInstance().getRoleManager();
                    Role[] roles = rmr.getAttachedRoles(userBean.getUser());
                    List roleList = new ArrayList();
                    for (int j =0; j < roles.length; j++) {
                        roleList.add(roles[j].getID());
                    }
                    if (!roleList.contains(AppTransactionDAO.JINJI_BUCHO_ROLE) && 
                            !roleList.contains(AppTransactionDAO.JINJI_KACHO_ROLE)) {
                        appTrans = appTransDao.getAppTransactionByAppIDRoleID(appID, AppTransactionDAO.JINJI_ROLE);
                        if (appTrans != null && (appTrans.getAppStatus()).equals(StatusConstants.STATUS_TRANS_WAIT)) {
                            Application app = DAOFactory.getApplicationDAO().getApplicationByID(appID);
                            wids.put(appID, wid);
                            
                            appList.add(app);
                        }
                    }                    
                }
            }
            
            if (appList.size() == 0) {
                // 作業可能な項目がない
                List errMsgs = new ArrayList();
                ResourceManager rm = ResourceManager.getInstance();
                errMsgs.add(rm.getValue("error.nolist"));
                request.setAttribute("errorMsg", errMsgs.toArray());
                return mapping.findForward(Constants.ERROR);
            }            
            
            Application[] application = (Application[]) appList.toArray(new Application[appList.size()]);
            
            request.setAttribute("applications", application);
            request.getSession().setAttribute("wids", wids);

            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);
        }
    }
}