package pulling.availability_imposer;

import java.util.Date;
import java.util.GregorianCalendar;

public class CPU_Eater implements Runnable {

	private double percentage;
	private double forHowLong; // In minutes
	private boolean alive = true;
	
	private Thread thisThread;
	
	public CPU_Eater(double percentage, double forHowLong) {
		this.setPercentage(percentage);
		this.setForHowLong(forHowLong);
	}
	
	public double getPercentage() {
		return percentage;
	}

	public synchronized void setPercentage(double percentage) {
		this.percentage = percentage;
	}

	public synchronized double getForHowLong() {
		return forHowLong;
	}

	public synchronized void setForHowLong(double forHowLong) {
		this.forHowLong = forHowLong;
	}

	public synchronized boolean isAlive() {
		return alive;
	}

	public synchronized void setAlive(boolean alive) {
		this.alive = alive;
	}

	
	public void startThread() {
		thisThread = new Thread(this);
		thisThread.start();
	}
	
	public void stopThread() {
		boolean wasAlive = this.isAlive();
		this.setAlive(false);
		if (wasAlive) {
			thisThread.interrupt();
			thisThread = null;
		}
	}
	

	public void run() {	

		long cycleTime = 100;
		int busyTime = (int) (getPercentage() * cycleTime);
		
		GregorianCalendar now = new GregorianCalendar();
		GregorianCalendar timeToStop = new GregorianCalendar();
		GregorianCalendar timeToExitLoop = new GregorianCalendar();
		timeToExitLoop.add(GregorianCalendar.SECOND, (int) Math.round( (this.getForHowLong() - Math.floor(this.getForHowLong()) )*60  ) );
		timeToExitLoop.add(GregorianCalendar.MINUTE, (int) this.getForHowLong());
		while (now.before(timeToExitLoop) && this.isAlive()) {
			try {
				Thread.sleep(cycleTime - busyTime);
			} catch (InterruptedException e) {
				if (!isAlive())
					System.out.print("Interupted");
					return; 
			}
			now.setTime(new Date());
			timeToStop.setTime( new Date() );
			timeToStop.add(GregorianCalendar.MILLISECOND, busyTime);
			while (now.before(timeToStop) && this.isAlive()) {
				now.setTime(new Date());
			}	
		}
	}
	
	public static void main(String[] args) {
		CPU_Eater eater1 = new CPU_Eater(0.5 , 5);
		CPU_Eater eater2 = new CPU_Eater(0.5 , 5);
		CPU_Eater eater3 = new CPU_Eater(0.5 , 5);
		eater1.startThread();
		eater2.startThread();
		eater3.startThread();
	}

}
