
package mapping;


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

/**
 * @author kokaly
 *
 */
public class LPAS_DG_MS_ThreadFCFS implements Runnable {

	private boolean alive;
	private Thread thisThread;
	private LPAS_DG_MS lpas_dg_ms;
	
	
	public LPAS_DG_MS_ThreadFCFS(LPAS_DG_MS lpas_dg_ms) {
		this.setAlive(true);
		this.setLpas_dg_ms(lpas_dg_ms);
	}
	public synchronized boolean isAlive() {
		return alive;
	}
	public synchronized void setAlive(boolean alive) {
		this.alive = alive;
	}
	public LPAS_DG_MS getLpas_dg_ms() {
		return lpas_dg_ms;
	}
	public void setLpas_dg_ms(LPAS_DG_MS lpas_dg_ms) {
		this.lpas_dg_ms = lpas_dg_ms;
	}

	public void startThread() {
		System.out.println("LPAS Thread started");
		thisThread = new Thread(this);
		thisThread.start();
	}

	public void stopThread() {
		this.setAlive(false);
		thisThread.interrupt();
		thisThread = null;
	}
	
	public void run() {
		Server server = null;
		int serverID; 
		IDsQueue <Integer>q = this.getLpas_dg_ms().getMapper().getAvailableServersQueue();
		while (this.isAlive()) {
			if ( !q.isEmpty() ) {
				serverID = q.peak();
				server = this.getLpas_dg_ms().getMapper().getServersTable().get(serverID);
				
				/*Any server in the available queue should satisfy this condition.
				 Just to be sure that the server is not busy nor down. */	 
				if (server.getNumberOfActiveJobs() == 0 &&  
						!this.getLpas_dg_ms().getMapper().getServersTable().isServerDown(serverID) ) {
					System.out.println("LPAS_THREAD: sendJobForServer( " + serverID + ")" );
					int result = this.getLpas_dg_ms().sendJobForServer( serverID );
					if (result < 0) {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							if ( !isAlive() )
								return;
						}
					}
				}
			} else { // is empty
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
