package ws.prova;

/*
 * Copyright (C) 2002-2007 <a href="mailto:a.kozlenkov@city.ac.uk">Alex Kozlenkov</a>
 *
 * This library 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 of the License, or (at your option) any later version.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import org.mandarax.kernel.Prerequisite;
import org.mandarax.kernel.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * Class encapsulating a long activity run in a separate thread
 * <p>Title: </p>
 * <p>Description: Execute a long activity </p>
 * <p>Copyright: Copyright (C) 2002-2007</p>
 * <p>Company: City University, London, United Kingdom </p>
 *
 * @author Alex Kozlenkov
 * @version 2.0 <25 March 2007>
 */

public class Task implements ITask {
	private String tid;
	private RMessageQueue queue;
	private Prerequisite p = null;
	private boolean swing;
	private reagent prova;
	private Query query;

	public Task(reagent prova, Query query) {
		queue = null;
		this.prova = prova;
		this.query = query;
	}

	public Task(RMessageQueue _queue, String _tid, Prerequisite _p) {
		// Use prerequisite for job definition
		queue = _queue;
		tid = _tid;
		p = _p;
		try {
			// If we are working in a non-Windows terminal (e.g., SSH),
			//     the following code traps
			swing = javax.swing.SwingUtilities.isEventDispatchThread();
		} catch (Throwable t) {
			swing = false;
		}
	}

	protected void asynch() {
		prova.execute(query);
	}

	/**
	 * Execute the task given its definition as a Prerequisite stored in this object
	 */
	public void execute() {
		if (queue == null) {
			asynch();
			return;
		}
		List objs = new ArrayList();
		objs.add(tid);
		String content;
		if (!swing) {
			content = "[[id,%0]," + queue.agent() + ",return,[";
		} else {
			content = "[[id,%0]," + queue.agent() + ",swing,[return,";
		}
		RMessage rmsg = null;
		try {
			List ret = new ArrayList();
			ws.prova.calc.CalcClauseSet.consumeGoalProcessing(null, p, null, ret);
			if (ret.get(0) == null) {
				// If the called method is void
				//    or a null is returned from the method
				//    consumeGoalProcessing puts a string "null" into the list 'ret'
				rmsg = new RMessage(content + "null]]", objs.toArray());
			} else {
				objs.addAll(ret);
				rmsg = new RMessage(content + "%1" + "]]", objs.toArray());
			}
			rmsg.setProtocol("self");
			queue.add(rmsg);
		} catch (Exception x) {
			x.printStackTrace(System.err);
		}
	}
}
