import java.util.*;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long startTime;
		long endTime;
		
		Shovel s1 = new Shovel("Shovel 1");
		Shovel s2 = new Shovel("Shovel 2");
		Shovel s3 = new Shovel("Shovel 3");
		Shovel s4 = new Shovel("Shovel 4");
		
		Crusher c = new Crusher("Crusher 1");
//		SharedCrusher c2 = new SharedCrusher("Crusher 2", c.getQueue());
//		Resource[] dependants = {s1, s2, s3, c, c2};
		Resource[] dependants = {s1, s2, s3, s4, c};
		
		//set deamon status on dependant resources
		for( Resource r : dependants ){
			r.setDaemon(true);
		}
		
		//Create trucks and assign them to specific Shovels and Crushers
		Truck t1 = new Truck("Truck 1", TruckSize.TwentyTons, s1, c);
		Truck t2 = new Truck("Truck 2", TruckSize.TwentyTons, s1, c);
		Truck t3 = new Truck("Truck 3", TruckSize.TwentyTons, s2, c);
		
		Truck t4 = new Truck("Truck 4", TruckSize.TwentyTons, s2, c);
		Truck t5 = new Truck("Truck 5", TruckSize.TwentyTons, s3, c);
		Truck t6 = new Truck("Truck 6", TruckSize.TwentyTons, s3, c);
		
		Truck t7 = new Truck("Truck 7", TruckSize.TwentyTons, s4, c);
		Truck t8 = new Truck("Truck 8", TruckSize.TwentyTons, s4, c);
//		Truck t9 = new Truck("Truck 9", TruckSize.TwentyTons, s3, c);
		
		//Resources store all the resource base classes - used to instantiate and stop threading
//		Resource[] resources = {t1, t2, t3, t4, t5, t6, t7, t8, t9, s1, s2, s3, c, c2};
//		Resource[] resources = {t1, t2, t4, t5, t7, t8, s1, s2, s3, c, c2};
		Resource[] resources = {t1, t2, t3, t4, t5, t6, t7, t8, s1, s2, s3, s4, c};
		
		//Start all resources
		for( Resource r : resources ){
			r.start();
		}
		//set the start time
		startTime = System.currentTimeMillis();
		
		//wait until completed
		//Every min is 100ms -> 8hrs = 100*60*8 = 
		while( (System.currentTimeMillis() - startTime) < 48000 ){
			try{
				Thread.sleep(100);
			}catch(Exception e){}
		}
		
		//Stop all threads
		for( Resource r : resources ){
			r.setContinueRunning(false);
		}
		
		//continue waiting until crusher and shovel finished their last set
		System.out.println("...Waiting for shovels and crushers to finish.");
		boolean threadsFinished = false;	
		while( !threadsFinished ){
			for( Resource r : dependants ){
				//iterate through the threads
				if( r.getState() == Thread.State.RUNNABLE  ){
					threadsFinished = false;
					break;
				}else
					threadsFinished = true;
			}
		}
		System.out.println("All resources have been stopped");
		
		//set end time
		endTime = System.currentTimeMillis();
		
		//print out statistics
		long elapsedTime = endTime - startTime;
		System.out.println("==============================");
		for( Resource r : resources ){
			System.out.println(r.getResourceName() + " utilization ratio = " + (1d-((double)r.getIdleTime()/(double)elapsedTime)));
		}
		
	}

}
