/* $Id: ShowStatusListAction.java,v 1.14 2005/08/26 04:45:19 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.Iterator;
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.Application;
import jp.co.argo21.nautica.workflow.sample.model.dao.AppTransactionDAO;
import jp.co.argo21.nautica.workflow.sample.model.dao.ApplicationDAO;
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.WorkflowEngineHandler;
import jp.co.argo21.nautica.workflow.soap.message.Filter;
import jp.co.argo21.nautica.workflow.soap.message.Process;

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.14 $
 * @since   Nautica Workflow 0.9
 */
public class ShowStatusListAction 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();
        List appIDList = new ArrayList();
        List errMsgs = new ArrayList();
        ResourceManager rm = ResourceManager.getInstance();
        
        try {
            // ユーザがフローに参加している申請の申請書番号を取得
            AppTransaction[] apptsByUser = DAOFactory.getAppTransactionDAO().getAppTransactionsByUserID(userbean.getUserID());
            addAppID(appIDList, apptsByUser);

            // ユーザのロールがフローに含まれる申請の申請書番号を取得
            RoleManagerRemote roleManager = SingletonServices.getInstance().getRoleManager();
            Role[] roles = roleManager.getAttachedRoles(userbean.getUser());
            AppTransactionDAO apptDAO = DAOFactory.getAppTransactionDAO();
            for (int i = 0; i < roles.length; i++) {
                AppTransaction[] apptsByRole = apptDAO.getAppTransactionsByRoleID(roles[i].getID());
                addAppID(appIDList, apptsByRole);
            }
            
            // 取得した申請書番号をもとに、プロセスが実行中である申請を取得
            WorkflowEngineHandler engineHandler = SingletonServices.getInstance().getWfEngineHandler();
            List appList = new ArrayList();
            ApplicationDAO appDAO = DAOFactory.getApplicationDAO();
            Filter[] filters = new Filter[2];
            Iterator ite = appIDList.iterator();
            while (ite.hasNext()) {
                String appID = (String) ite.next();
                
                // フィルターをセット
                Filter namefilter = new Filter();
                namefilter.setType(5001);
        		namefilter.setFilterString(appID);
        		namefilter.setComparison(1);
        		filters[0] = namefilter;    		
                Filter statefilter = new Filter();
                statefilter.setType(5002);
                statefilter.setFilterName("ProcessState");
        		statefilter.setFilterString("open.running");
        		statefilter.setComparison(1);
        		filters[1] = statefilter;
        		
        		Process[] processes = engineHandler.getProcesses(sessionID, filters);
        		for (int i = 0; i < processes.length; i++) {
        		    Application app = appDAO.getApplicationByID(appID);
        		    appList.add(app);
        		}
            }
                    
            if (appList.size() == 0) {
                //フローに自分が関わる申請がない
                errMsgs.add(rm.getValue("error.nolist"));
                request.setAttribute("errorMsg" , errMsgs.toArray());
                return mapping.findForward(Constants.ERROR);
            }
            
    		Application[] apps = (Application[])appList.toArray(new Application[appList.size()]);
    				
    		request.setAttribute("applications", apps);
            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();
            // エンジン接続に失敗（プロセス・権限取得失敗）
            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);     
        }
    }
    
    /**
     * リストに含まれていない申請書番号を追加して返す。
     * 
     * @param list 申請書番号のリスト
     * @param appts 申請トランザクション
     * @throws Exception 任意の例外
     */
    private void addAppID(List list, AppTransaction[] appts) throws Exception {
        for (int i = 0; i < appts.length; i++) {
            String id = appts[i].getAppID();
            AppTransactionDAO appTransDao = DAOFactory.getAppTransactionDAO();
            AppTransaction appTrans = appTransDao.getAppTransactionByAppIDBlockID(id, 0);            
            if (!list.contains(id) && (StatusConstants.STATUS_TRANS_APPLY).equals(appTrans.getAppStatus())) {
                list.add(id);
            }
        }
    }
}
