package codelines;

import animation.CodeLine;
import animation.ControlFlow;
import animation.Memory;

public abstract class DeclareVariable <T> extends CodeLine {

	private boolean oldExists;
	private String name;
	
	public DeclareVariable( String name )
	{
		this.name = name;
	}

	@Override
	public ControlFlow runForward(Memory m) {
		
		oldExists = m.isDefined( name, false );
		T oldVal = m.read( name, false );
		m.declare( name, value( m ), false );
		actions.push( (Memory mem) -> {
			if( !oldExists )
				mem.undeclare( name, false );
			else
				mem.declare( name, oldVal, false );
			return new ControlFlow( ControlFlow.STEP_OVER );
		});
		return new ControlFlow( ControlFlow.STEP_OVER );
	}
	
	abstract protected T value( Memory m );
}
