
/**
 * The Crusher class uses a Priority Queue which uses the CrusherQueue as a base class.
 * 
 * @author Ahmed Messaoud
 * @see CrusherQueue
 */
public class Crusher extends Resource {
	CrusherQueue q;
	
	public Crusher(String name) {
		super(name);
		q = new CrusherQueue();
	}
	
	/**
	 * The goTo method is used to advise the given Truck to come to this Crusher 
	 * 
	 * @param t The Truck to come to this Crusher
	 * @return	Wether the Truck was successfully added to the Crusher's queue
	 * @see Truck#finishedShovel()
	 */
	public boolean goTo(Truck t){
		return q.add(t);
	}
	
	/**
	 * Returns the Queue used for this Crusher
	 * 
	 * @return the CrusherQueue for this Crusher
	 * @see CrusherQueue
	 */
	public CrusherQueue getQueue(){
		return q;
	}

	@Override
	public void run() {
		while(this.getContinueRunning()){
			Truck t = q.poll();
			
			if( t != null ){
				try{
					if( this.isIdleling() ){
						try{
							this.stopIdleling();
						}catch( NotIdlelingException e ){ e.printStackTrace(); }
					}
					//Truck was in the queue
					if( t.getTruckSize() == TruckSize.FiftyTons )
						sleep(getSleepTime(4, 0.5));
					else
						sleep(getSleepTime(2, 0.5));
				}catch(InterruptedException e){ e.printStackTrace(); }
				//Finished the crushing operation, advise the truck
				t.finishedCrushing();
			}else if( !this.isIdleling() && t == null ){
				try{
					this.startIdleling();
				}catch( AlreadyIdlelingException e ){ e.printStackTrace(); }
			}
		}
	}

}
