package org.teiid.query.function.aggregate;

import java.util.List;

import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.query.sql.symbol.AggregateSymbol.Type;
import org.teiid.query.util.CommandContext;

public class FirstLastValueFunction extends SingleArgumentAggregateFunction {
	private Type type;
	private Object result;

	public FirstLastValueFunction(Type type) {
		this.type = type;
	}

	@Override
	public void reset() {
		result = null;
	}

	@Override
	public void addInputDirect(Object input, List<?> tuple, CommandContext commandContext) throws TeiidProcessingException, TeiidComponentException {
		if (type == Type.FIRST_VALUE) {
			if (result == null)
				result = input;
		} else if (type == Type.LAST_VALUE) {
			result = input;
		}
	}

	@Override
	public Object getResult(CommandContext commandContext) throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException, TeiidProcessingException {
		return result;
	}
}
