package mapping;

import mapping.data.Server;
import mapping.data.IDsQueue;

/**
 * This Thread is a helper thread for the SLQ_MS objects. It is a thread that
 * iterates over the AvailableServers Queue it asks the FCFS_MS object to map a
 * job for the server in the head of that queue
 * 
 * @author Majd Kokaly, used by Ben Kybartas
 */
public class SLQ_MS_Thread implements Runnable 
{
	/**
	 * This flag tells the thread if it is alive or should kill itself
	 */
	private boolean alive = true;
	
	/**
	 * A Thread object that runs this Runnable class
	 */
	private Thread thisThread;
	
	/**
	 * The SLQ_MS that this thread helps
	 */
	private SLQ_MS slq_ms;
	
	/**
	 * A default constructor
	 */
	public SLQ_MS_Thread(SLQ_MS slq_ms)
	{
		this.setAlive(true);
		this.setSLQ_MS(slq_ms);
	}
	
	public synchronized boolean isAlive()
	{
	return alive;	
	}
	
	public synchronized void setAlive(boolean alive) 
	{
		this.alive = alive;
	}
	
	public SLQ_MS getSLQ_MS()
	{
		return slq_ms;
	}
	
	public void setSLQ_MS(SLQ_MS slq_ms)
	{
		this.slq_ms = slq_ms;
	}
	
	/**
	 * This method starts the thread
	 */
	public void startThread() 
	{
		System.out.println("LPAS Thread started");
		thisThread = new Thread(this);
		thisThread.start();
	}
	
	/**
	 * This method stops the thread
	 */
	public void stopThread()
	{
		this.setAlive(false);
		thisThread.interrupt();
		thisThread = null;
	}
	
	public void run() {
		Server server = null;
		int serverID;
		IDsQueue<Integer> q = this.getSLQ_MS().getMapper().getAvailableServersQueue();
		
		while (this.isAlive()) 
		{
			if (!q.isEmpty())
			{
				serverID = q.peak();
				server = this.getSLQ_MS().getMapper().getServersTable().get(serverID);
				
				/**
				 * Any server in the available server queue should satisfy this
				 * condition. Just to be sure that the server is not busy nor is
				 * it down
				 */
				if (server.getNumberOfActiveJobs() == 0
					&& !this.getSLQ_MS().getMapper().getServersTable().isServerDown(serverID))
				{
					int result = this.getSLQ_MS().sendJobForServer(serverID);
					if (result < 0) 
					{
						try
						{
							Thread.sleep(50);
						}
						catch (InterruptedException e)
						{
							if (!isAlive())
								return;
						}
					}
				}
				else
				{//is empty
					try
					{
						Thread.sleep(30);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
					
				}
			}
		}
	}
}

