package v6.apps.zelvak;

import java.util.LinkedList;
import java.util.List;

public class FunctionCallState extends AbstractState implements ArgumentState{

	private final ParsingFunction function;
	
	private final List<Object> arguments = new LinkedList<Object>();
	
	private final State parent;
	
	private boolean expectingComma = false;
	
	public FunctionCallState(State state, String name, ParsingContext context) throws WTFException{
		super(context);
		this.function = context.getFunction(name);
		if(this.function == null){
			throw new WTFException("Unknown function :"+name);
		}
		this.parent = state;
	}
	
	@Override
	public Application getApplication() throws WTFException {
		throw new WTFException("Program is not complete.");
	}

	@Override
	public State process(char c) throws WTFException {
		if(c == ')'){
			if(function.requiresBody()){
				return new BlockState(parent, context, function, arguments);
			}else{
				context.addCommand(function.applyArguments(arguments));
				return parent;
			}
		}
		if(Character.isWhitespace(c)){
			return this;
		}
		if(Character.isDigit(c) || c == '-' || c == '+'){
			if(expectingComma){
				throw new WTFException("Expected ',' or ')', digit found");
			}
			expectingComma = true;
			return new NumberExpressionState(this, context).process(c);
		}
		if(c == ','){
			expectingComma = false;
			return this;
		}
		throw new WTFException("Unrecognized character: "+c);
	}

	@Override
	public void addArgument(Object arg) {
		arguments.add(arg);
	}
	
}
