package taskspaces.system;

/**
 * Represents thread which executes Tasks as they become available
 * in the referenced TaskStore.  
 * @author Rob Markel, Matthew Keoshkerian
 * @version 2.0
 */ 
public class Worker extends Communicator implements Runnable 
{
	/** Holds a reference to the local TaskStore. */
	private TaskStore taskStore;

	/** Node incremented ID to identify this Worker */
	private int id;

	/** Reference to the hosting Node. */
	private Node node; 

	/**
	 * Accepts reference to TaskStore started by host Node,
	 * ID number, and reference to host Node.
	 * @param taskStore The refrence to the TaskStore class
	 * @param id The id of the the Worker set by the node
	 * @param node The refrence to the node that created this worker.
	 */
	public Worker(TaskStore taskStore,int id,Node node) 
	{
		this.taskStore=taskStore;
		this.id=id;
		this.node=node;
	}

	/**
	 * Looks for Tasks in the local TaskStore, and executes them
	 * by calling the run method if available. 
	 * @return void
	 */
	public void run() 
	{
		int i=0;
		while(true)
		{
			long maxTasks=node.getMaxTasks();
			try
			{
				/* Retrieve object from object store and execute */
				Object o=taskStore.get();
				node.print("Worker: Worker received: "+o);
				node.setBusy(true);
				((Task)o).run();
				node.setBusy(false);
            
				/* MUST clear messages for next task. */
				node.clearMessages();
				// i++;
	    
				// If we have reached the maximum tasks allowed..
				if(++i==maxTasks) System.exit(0);
	    
				/* Should have to re-register, since entry is deleted on task send */
				registerNode(node.getSpaceAddress(),node.getPort());              
			} catch(Exception e) { e.printStackTrace(); }
		}
	}
}
