/* $Id: AutomaticActivityBehavior.java,v 1.2 2007/11/05 09:50:54 nito Exp $
 *
 * Copyright (c)ARGO 21, Corporation. 2005, 2006.  All rights reserved.
 * 
 * This file is part of Nautica Workflow Core.
 * 
 *  Nautica Workflow Core is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; either version 2.1 of the License, or
 *  (at your option) any later version.
 * 
 *  Nautica Workflow Core 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 Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Nautica Workflow Core; 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.engine;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.co.argo21.nautica.workflow.dataaccess.ActivityBean;
import jp.co.argo21.nautica.workflow.dataaccess.ActivityDAO;
import jp.co.argo21.nautica.workflow.dataaccess.AppExecutionBean;
import jp.co.argo21.nautica.workflow.dataaccess.AppExecutionDAO;
import jp.co.argo21.nautica.workflow.dataaccess.DefinitionBean;
import jp.co.argo21.nautica.workflow.dataaccess.DefinitionDAO;
import jp.co.argo21.nautica.workflow.dataaccess.ProcessBean;
import jp.co.argo21.nautica.workflow.dataaccess.VariableBean;
import jp.co.argo21.nautica.workflow.dataaccess.VariableDAO;
import jp.co.argo21.nautica.workflow.dataaccess.WorkItemBean;
import jp.co.argo21.nautica.workflow.dataaccess.WorkItemDAO;
import jp.co.argo21.nautica.workflow.dataaccess.WorkflowDAOFactory;
import jp.co.argo21.nautica.workflow.definition.ActivityDefinition;
import jp.co.argo21.nautica.workflow.definition.ApplicationDefinition;
import jp.co.argo21.nautica.workflow.definition.ParticipantDefinition;
import jp.co.argo21.nautica.workflow.definition.ProcessDefinition;
import jp.co.argo21.nautica.workflow.definition.TransitionDefinition;
import jp.co.argo21.nautica.workflow.jms.WorkflowMessage;
import jp.co.argo21.nautica.workflow.omg.WorkflowException;
import jp.co.argo21.nautica.workflow.util.StringManager;
import jp.co.argo21.nautica.workflow.util.UniqueKeyGenerator;
import jp.co.argo21.nautica.workflow.wfmc.ActivityState;
import jp.co.argo21.nautica.workflow.wfmc.Attribute;
import jp.co.argo21.nautica.workflow.wfmc.ToolAgent;

/**
 * 自動実行アクティビティの状態ごとの動作を定義するクラスである。
 *
 * @author  nito(Argo 21, Corp.)
 * @version $Revision: 1.2 $
 * @since   Nautica Workflow 1.0
 */
public class AutomaticActivityBehavior
extends AbstractActivityBehavior
{

	/**
	 * 自動実行アクティビティの状態ごとの動作を生成する。
	 */
	public AutomaticActivityBehavior()
	{
	}

	/**
	 * 固有の中止処理を行う。
	 *
	 * @param pd プロセス定義
	 * @param ad アクティビティ定義
	 * @param proc プロセス
	 * @param act アクティビティ
	 * @throws Exception 任意の例外
	 * @see jp.co.argo21.nautica.workflow.engine.ActivityBehavior#abort(jp.co.argo21.nautica.workflow.definition.ProcessDefinition, jp.co.argo21.nautica.workflow.definition.ActivityDefinition, jp.co.argo21.nautica.workflow.engine.ProcessInternal, jp.co.argo21.nautica.workflow.engine.ActivityInternal, boolean)
	 */
	public void abort(ProcessDefinition pd, ActivityDefinition ad,
			ProcessInternal proc, ActivityInternal act, boolean checkChild)
	throws Exception
	{
		ActivityBean abean = act.getBean();
		String pid = abean.getProcessID();
		String aid = abean.getActivityID();

		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();

		//関連する作業項目の取得
		WorkItemDAO wiDAO = daoFactory.getWorkItemDAO();
		WorkItemBean wibean = wiDAO.findByProcessIDANDActivityID(pid, aid);

		String wid = wibean.getID();
		AppExecutionDAO aeDAO = daoFactory.getAppExecutionDAO();
		List<AppExecutionBean> aebeans = aeDAO.findByStarterID(wid);
		
		//アプリケーションの停止を試みる
		for (AppExecutionBean aebean : aebeans) {
			//ツールエージェントの取得
			String appName = aebean.getAppName();
			int handle = aebean.getExecId();
			ToolAgentManager tam = ToolAgentManager.getInstance();
			ToolAgent agent = tam.getToolAgent(appName);

			try {
				//アプリケーションの停止
				agent.terminateApplication(handle, wid);
			} catch (Exception ex) {
				// アプリケーション停止時に例外が発生しました。
				String msg = StringManager.get("W0002");
				eLog.warn(msg, ex);
			}
		}

		//関連する作業項目の削除
		wiDAO.deleteByProcessIDANDActivityID(pid, aid);
		
		//該当アクティビティを中断させる。
		ActivityDAO actDAO = daoFactory.getActivityDAO();
		Timestamp ts = DataAccessManager.getAccessTime();
		actDAO.updateState(act.getBean(), ActivityState.CLOSED_ABORTED, ts);
	}

	/**
	 * 固有の開始処理を行う。
	 *
	 * @param pd プロセス定義
	 * @param ad アクティビティ定義
	 * @param proc プロセス
	 * @param act アクティビティ
	 * @throws Exception 任意の例外
	 * @see jp.co.argo21.nautica.workflow.engine.ActivityBehavior#start(jp.co.argo21.nautica.workflow.definition.ProcessDefinition, jp.co.argo21.nautica.workflow.definition.ActivityDefinition, jp.co.argo21.nautica.workflow.engine.ProcessInternal, jp.co.argo21.nautica.workflow.engine.ActivityInternal)
	 */
	public void start(ProcessDefinition pd, ActivityDefinition ad,
			ProcessInternal proc, ActivityInternal act)
	throws Exception
	{
		ProcessBean pbean = proc.getBean();
		String pdid = pbean.getProcDefinitionID();
		ActivityBean abean = act.getBean();
		String pid = abean.getProcessID();
		String aid = abean.getActivityID();
		String performerID = ad.getPerformerID();
		String appID = ad.getApplicationID();
		List<String> aparams = ad.getApplicationParameters();
		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();

		//プロセス定義の正式名を取得する。
		DefinitionDAO defDAO = daoFactory.getDefinitionDAO();
		DefinitionBean defbean = defDAO.findByPrimaryKey(pdid);
		String defID = defbean.getProcessDefinitionID();

		//実行許可者の検索　
		ParticipantDefinition partd = getParticipantDefinition(defID, performerID);		
		if (partd == null) {
			//実行許可者が見つからない。定義ミスの可能性あり。
			act.terminate();
			String msg = StringManager.get("F0002");
			eLog.fatal(msg);
			throw new WorkflowException(msg);
		}
		
		//アプリケーション定義の検索
		ApplicationDefinition appd = getApplicationDefinition(defID, appID);
		if (appd == null) {
			//アプリケーションが見つからない。定義ミスの可能性あり。
			act.terminate();
			String msg = StringManager.get("F0003");
			eLog.fatal(msg);
			throw new WorkflowException(msg);
		}
		
		//パラメータ情報の作成
		Iterator<String> apit = aparams.iterator();
		Attribute[] attrs = new Attribute[aparams.size()];
		for (int i = 0; apit.hasNext(); i++) {
			String varID = apit.next();
			VariableDAO varDAO = daoFactory.getVariableDAO();
			VariableBean vbean = varDAO.findByDefinitionID(pid, varID);
			attrs[i] = vbean;
		}
		
		//該当アクティビティを開始させる。
		ActivityDAO actDAO = daoFactory.getActivityDAO();
		Timestamp ts = DataAccessManager.getAccessTime();
		actDAO.updateState(act.getBean(), ActivityState.OPEN_RUNNING, ts);
		
		//作業項目の登録
		WorkItemBean wbean = new WorkItemBean();
		wbean.setID(UniqueKeyGenerator.generate(WorkItemBean.ID_PREFIX));
		wbean.setProcessID(pid);
		wbean.setActivityID(aid);
		wbean.setParticipantName(partd.getName());
		wbean.setParticipantType(partd.getType());
		WorkItemDAO workDAO = daoFactory.getWorkItemDAO();
		workDAO.insert(wbean);
		
		//ツールエージェントの取得
		String appName = appd.getName();
		ToolAgentManager tam = ToolAgentManager.getInstance();
		ToolAgent agent = tam.getToolAgent(appName);

		try {
			//アプリケーションの起動
			@SuppressWarnings("unused")
			int tahandle = agent.invokeApplication(appName, wbean.getID(), attrs);
		} catch (Exception ex) {
			// アプリケーションの実行中にエラーが起こりました。
			String E0104 = StringManager.get("E0104") + "(app name = " + appName + ")";
			eLog.fatal(E0104, ex);
			act.terminate();
		}
	}

	/**
	 * 固有の停止処理を行う。
	 *
	 * @param pd プロセス定義
	 * @param ad アクティビティ定義
	 * @param proc プロセス
	 * @param act アクティビティ
	 * @throws Exception 任意の例外
	 * @see jp.co.argo21.nautica.workflow.engine.ActivityBehavior#terminate(jp.co.argo21.nautica.workflow.definition.ProcessDefinition, jp.co.argo21.nautica.workflow.definition.ActivityDefinition, jp.co.argo21.nautica.workflow.engine.ProcessInternal, jp.co.argo21.nautica.workflow.engine.ActivityInternal, boolean)
	 */
	public void terminate(ProcessDefinition pd, ActivityDefinition ad,
			ProcessInternal proc, ActivityInternal act, boolean checkChild)
	throws Exception
	{
		ProcessBean pbean = proc.getBean();
		String pid = pbean.getID();
		ActivityBean abean = act.getBean();
		String aid = abean.getActivityID();
		String bid = abean.getBlockID();

		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();

		//関連する作業項目の取得
		WorkItemDAO wiDAO = daoFactory.getWorkItemDAO();
		WorkItemBean wibean = wiDAO.findByProcessIDANDActivityID(pid, aid);

		String wid = wibean.getID();
		AppExecutionDAO aeDAO = daoFactory.getAppExecutionDAO();
		List<AppExecutionBean> aebeans = aeDAO.findByStarterID(wid);
		
		//アプリケーションの停止を試みる
		for (AppExecutionBean aebean : aebeans) {
			//ツールエージェントの取得
			String appName = aebean.getAppName();
			int handle = aebean.getExecId();
			ToolAgentManager tam = ToolAgentManager.getInstance();
			ToolAgent agent = tam.getToolAgent(appName);

			try {
				//アプリケーションの停止
				agent.terminateApplication(handle, wid);
			} catch (Exception ex) {
				// アプリケーション停止時に例外が発生しました。
				String msg = StringManager.get("W0002");
				eLog.warn(msg, ex);
			}
		}

		//関連する作業項目の削除
		wiDAO.deleteByProcessIDANDActivityID(pid, aid);
		
		VariableDAO varDAO = daoFactory.getVariableDAO();
		List<VariableBean> vars = varDAO.findByProcessIDAsList(pid);
		List<TransitionDefinition> trs = ConditionEvaluator.evaluate(pd, ad, vars, true);
		
		List<ActivityBean> acts = new ArrayList<ActivityBean>();
		for (TransitionDefinition tr : trs) {
			ActivityDefinition dest = tr.getDestination();
			
			//遷移先アクティビティの生成
			ActivityBean ab = createActivity(pd, dest, pbean, bid);
			acts.add(ab);
		}
		
		if (acts.size() == 0) {
			//遷移先が見つからない。定義ミスの可能性あり。
			suspend(pd, ad, proc, act);
			String msg = StringManager.get("F0001");
			eLog.fatal(msg);
			return;
		}
		
		//該当アクティビティを中止させる。
		ActivityDAO actDAO = daoFactory.getActivityDAO();
		Timestamp ts = DataAccessManager.getAccessTime();
		actDAO.updateState(act.getBean(), ActivityState.CLOSED_TERMINATED, ts);

		//遷移先アクティビティをメッセージキューに登録する。
		for (ActivityBean ab : acts) {
			String abid = ab.getActivityID();
			WorkflowMessage sarmsg = new StartActivityRequestMessage(pid, abid);
			SystemMessageTransporter mt = new SystemMessageTransporter(StartActivityRequestWatcher.NAME);
			mt.sendMessage(sarmsg);
		}
	}
}
