/* $Id: ConcurrentEndActivityBehavior.java,v 1.6 2008/01/16 00:09:48 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.List;

import jp.co.argo21.nautica.workflow.dataaccess.ActivityBean;
import jp.co.argo21.nautica.workflow.dataaccess.ActivityDAO;
import jp.co.argo21.nautica.workflow.dataaccess.ConcurrencyBlockBean;
import jp.co.argo21.nautica.workflow.dataaccess.ConcurrencyBlockDAO;
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.WorkflowDAOFactory;
import jp.co.argo21.nautica.workflow.definition.ActivityDefinition;
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.util.StringManager;
import jp.co.argo21.nautica.workflow.wfmc.ActivityState;

/**
 * 並行処理終了アクティビティの状態ごとの動作を定義するクラスである。
 *
 * @author  nito(Argo 21, Corp.)
 * @version $Revision: 1.6 $
 * @since   Nautica Workflow 1.0
 */
public class ConcurrentEndActivityBehavior
extends AbstractActivityBehavior
{
	private static final String CONCURRENCY_LOCK = "__CONCURRENCY_LOCK__";

	/**
	 * 並行処理終了アクティビティの状態ごとの動作を生成する。
	 */
	public ConcurrentEndActivityBehavior()
	{
		super();
	}

	/**
	 * 固有の中止処理を行う。
	 *
	 * @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 bid = abean.getBlockID();

		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();
		ConcurrencyBlockDAO cbDAO = daoFactory.getConcurrencyBlockDAO();
		
		LockManager lockManager = LockManager.getInstance();
		LockManager.Lock lock = lockManager.getLock(CONCURRENCY_LOCK);
		synchronized(lock) {
			//自分のブロックを削除する。
			cbDAO.delete(pid, bid);
		}
		
		//該当アクティビティを中断させる。
		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#complete(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 complete(ProcessDefinition pd, ActivityDefinition ad,
			ProcessInternal proc, ActivityInternal act)
	throws Exception
	{
		ProcessBean pbean = proc.getBean();
		String pid = pbean.getID();
		ActivityBean abean = act.getBean();
		String bid = abean.getBlockID();

		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();
		ConcurrencyBlockDAO cbDAO = daoFactory.getConcurrencyBlockDAO();
		
		String ubid = null;
		LockManager lockManager = LockManager.getInstance();
		LockManager.Lock lock = lockManager.getLock(CONCURRENCY_LOCK);
		synchronized(lock) {
			ConcurrencyBlockBean cbbean = cbDAO.findByPrimaryKey(pid, bid);
			if (cbbean == null) return;
			
			ubid = cbbean.getUpperBlockID();
			//自分のブロックを削除する。
			cbDAO.delete(pid, bid);
		}

		VariableDAO varDAO = daoFactory.getVariableDAO();
		List<VariableBean> vars = varDAO.findByProcessIDAsList(pid);
		List<TransitionDefinition> trs = ConditionEvaluator.evaluate(pd, ad, vars, false);
		
		List<ActivityBean> acts = new ArrayList<ActivityBean>();
		for (TransitionDefinition tr : trs) {
			ActivityDefinition dest = tr.getDestination();
			
			//遷移先アクティビティの生成
			//退避していたブロックIDを復帰させている
			ActivityBean ab = createActivity(pd, dest, pbean, ubid);
			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_COMPLETED, ts);
			
		//遷移先アクティビティをメッセージキューに登録する。
		for (ActivityBean ab : acts) {
			String aid = ab.getActivityID();
			WorkflowMessage sarmsg = new StartActivityRequestMessage(pid, aid);
			SystemMessageTransporter mt = new SystemMessageTransporter(StartActivityRequestWatcher.NAME);
			mt.sendMessage(sarmsg);
		}
	}

	/**
	 * 固有の開始処理を行う。
	 *
	 * @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
	{
		ActivityBean abean = act.getBean();
		String pid = abean.getProcessID();
		String aid = abean.getActivityID();
		String bid = abean.getBlockID();

		//該当アクティビティを開始させる。
		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();
		ActivityDAO actDAO = daoFactory.getActivityDAO();
		ConcurrencyBlockDAO cbDAO = daoFactory.getConcurrencyBlockDAO();
		Timestamp ts = DataAccessManager.getAccessTime();
		actDAO.updateState(act.getBean(), ActivityState.OPEN_RUNNING, ts);

		LockManager lockManager = LockManager.getInstance();
		LockManager.Lock lock = lockManager.getLock(CONCURRENCY_LOCK);
		synchronized(lock) {
			int actcount = actDAO.findOpeningActivityCountByBlockID(pid, bid);
			int sbcount = cbDAO.findSubblockExistenceByBlockID(pid, bid);
			
			//ブロック内のアクティビティがすべて完了した場合
			if (actcount == 1 && sbcount == 0) {
				//自分自身しかオープンされていない
				//メッセージキューに完了要求登録
				WorkflowMessage earmsg = new EndActivityRequestMessage(pid, aid);
				SystemMessageTransporter mt = new SystemMessageTransporter(EndActivityRequestWatcher.NAME);
				mt.sendMessage(earmsg);
			}
		}
	}

	/**
	 * 固有の停止処理を行う。
	 *
	 * @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();
		ActivityBean abean = act.getBean();
		String pid = abean.getProcessID();
		String bid = abean.getBlockID();

		WorkflowDAOFactory daoFactory = DataAccessManager.getDAOFactory();
		ConcurrencyBlockDAO cbDAO = daoFactory.getConcurrencyBlockDAO();

		String ubid = null;
		LockManager lockManager = LockManager.getInstance();
		LockManager.Lock lock = lockManager.getLock(CONCURRENCY_LOCK);
		synchronized(lock) {
			ConcurrencyBlockBean cbbean = cbDAO.findByPrimaryKey(pid, bid);
			if (cbbean == null) return;
			
			ubid = cbbean.getUpperBlockID();
			//自分のブロックを削除する。
			cbDAO.delete(pid, bid);
		}

		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, ubid);
			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 aid = ab.getActivityID();
			WorkflowMessage sarmsg = new StartActivityRequestMessage(pid, aid);
			SystemMessageTransporter mt = new SystemMessageTransporter(StartActivityRequestWatcher.NAME);
			mt.sendMessage(sarmsg);
		}
	}
}
