import de.simflex.gui.windows.SfxHtmlPanel;
import de.simflex.simulator.scheduler.Event;
import de.simflex.units.ModelNode;
import de.simflex.units.PermanentUnit;
import de.simflex.units.TemporaryUnit;

/**
* @author mg
* 
*/
public class Put extends PermanentUnit {

	protected PermanentUnit destpu;//Ziel PU

	public Put( ) {
		setVrmlFile( "null.wrl" );
	}

	protected void receive( ){
		if( debug ) System.out.println( this + " receiving...." );
		addTemporaryUnit( (TemporaryUnit)((PermanentUnit)incomingBuffer
				.removeTop( )).release( ) );
		temporaryUnit.setStatus( this, TemporaryUnit.BE_RECEIVED );
		destpu = (PermanentUnit)model.getUnitByIdentity( matrix.getNextPermanentUnit(
				getIdentity( ), temporaryUnit ) );
		if( debug ) System.out.println( "Ziel: " + destpu );
		setState( RECEIVED );
		scheduler.setRelativeEvent( new Event( 10, this,
				PermanentUnit.WORK_BEGIN ) );
	}

	protected void work_begin( ){
		if( debug ) System.out.println( this + " starts driving...." );
		setState( WORKING );
		double length = ((Car)getParent( )).moveTo( destpu );
		double fahrzeit = Math.abs( length ) * 2;
		scheduler.setRelativeEvent( new Event( fahrzeit, this,
				PermanentUnit.WORK_END ) );
	}

	protected void work_end( ){
		if( debug ) System.out.println( this + " ends driving...." );
		scheduler.setRelativeEvent( new Event( 4, this, PermanentUnit.CANCEL ) );
	}

	public void cancel( ){
		if( debug ) System.out.println( this + " cancelling..." );
		if( temporaryUnit != null ){
			temporaryUnit.setStatus( this, TemporaryUnit.BE_CANCELED );
		}
		setState( CANCELED );
		destpu.announce( this );
	}

	public TemporaryUnit release( ){
		if( debug ) System.out.println( this + " is releasing....." );
		if( ((PermanentUnit)((ModelNode)getParent( )).getChild( 0 ))
				.getIncomingBuffer( ).size( ) > 0 )
													scheduler
															.setRelativeEvent( new Event(
																	0,
																	(PermanentUnit)((ModelNode)getParent( ))
																			.getChild( 0 ),
																	PermanentUnit.RECEIVE ) );
		((PermanentUnit)getParent( )).setOccupied( false );
		setState( EMPTY );
		TemporaryUnit temp = temporaryUnit;
		removeTemporaryUnit( temp );
		matrix.check( );
		return temp;
	}

	//Static Methods
	public static String description( ){
		return "" + "<br><br>" + "See also: "
				+ SfxHtmlPanel.addDocHyperlink( Get.class );
	}
}