package taskspaces.system;
import java.io.*;

/**
 * This is a generic Task distribution Agent for
 * applications.
 * @author Rob Markel, Matthew Keoshkrian
 * @version 2.0
 */
public class TaskAgent extends Agent
{
   /** Holds a subclass of Task */
   Task t;

   /** Array of tasks to send */
   int[] taskList;
   
   /** Username of the one who started the application */
   String user;
   
   /** The application name of this application. */
   String appName;
   

   /**
    * Constructor accepts a subclass of Task.
    * @param t The refrence to a Task
    * @param taskList The refrence to a list of tasks.
    */
   public TaskAgent(Task t,int[] taskList, String user, String appName)
   {
      this.t=t;
      this.taskList=taskList;
      this.user=user;
      this.appName=appName;
   }

   /**
    * Called when Agent is sent to a Space. The Agent will increment the 
    * Task data, pass it to a cloned instance of the Task object, and
    * send it to a registered Node.
    * @return void
    */
   public void run()
   {
      boolean value = false;
      
      try 
	  {
      	File dir = new File("./logs/");
      	value = dir.mkdir();
      	logWriteName = "./logs/" + user + "." + appName;
      	logWrite = new PrintWriter(new FileWriter(logWriteName, true));
      }
      catch (IOException e) { System.out.println(value); e.printStackTrace(); }
      
      try
      {
         int i = 1;
         print("TaskAgent: length of tasklist = "+(taskList.length-1));
	 
         while(i<taskList.length)
         {
            if(space.nodes.size()>0)
            {
               i++;
               Task newTask=(Task)t.next();
               int id = newTask.getId();
               print("TaskAgent: id = "+id);

               if(taskList[id] == 0)
               {
               	// Wait until the task has been sent out. Keeps from unsent tasks being lost.
               	while( space.sendOut(newTask) == false );
               	print("TaskAgent: Agent Sending Task " + id + "/" + (taskList.length-1));
               }
            }
            else {Thread.sleep(500);}
         }
      } catch(Exception e) {e.printStackTrace();}
   }
}
