package v6.apps.zelvak;

import java.util.List;

public class BlockState extends AbstractState {
	
	private boolean opened;
	
	private final ParsingFunction function;
	
	private final List<Object> arguments;
	
	public BlockState(State state, ParsingContext context, ParsingFunction function, List<Object> arguments) {
		super(state, context);
		this.function = function;
		this.arguments = arguments;
	}

	@Override
	public Application getApplication() throws WTFException {
		throw new WTFException("Unexpected end.");
	}

	@Override
	public State process(char c) throws WTFException {
		if(Character.isWhitespace(c)){
			return this;
		}
		if(c == '{'){
			opened = true;
			//System.out.println("opened");
			return new InitialState(this, context.makeSubContext());
		}
		if(c == '}'){
			if(!opened){
				throw new WTFException("Unexpected '}'.");
			}
			//System.out.println("closed");
			arguments.add(context.buildApplication());
			context.addCommand(function.applyArguments(arguments));
			return parent;
		}
		throw new WTFException("Unexpected character");
	}

}
