/*
 * Copyright 2013 Future Systems
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.araqne.logdb.query.aggregator;

import java.util.List;

import org.araqne.logdb.QueryParseException;
import org.araqne.logdb.Row;
import org.araqne.logdb.query.expr.Expression;

public class First extends AbstractAggregationFunction {
	private Object first;

	public First(List<Expression> exprs) {
		super(exprs);

		if (exprs.size() != 1) {
			// String note = exprs.size() + " parameters to first function";
			// throw new QueryParseException("invalid-parameter-count", -1, note);
			throw new QueryParseException("91020", -1, -1, null);
		}
	}

	@Override
	public String getName() {
		return "first";
	}

	@Override
	public void apply(Row map) {
		Object obj = exprs.get(0).eval(map);

		if (first == null && obj != null)
			first = obj;
	}

	public Object getFirst() {
		return first;
	}

	public void setFirst(Object first) {
		this.first = first;
	}

	@Override
	public Object eval() {
		return first;
	}

	@Override
	public void clean() {
		first = null;
	}

	@Override
	public AggregationFunction clone() {
		First f = new First(exprs);
		f.first = first;
		return f;
	}

	@Override
	public void merge(AggregationFunction func) {
		// ignore subsequent items
	}

	@Override
	public Object[] serialize() {
		Object[] l = new Object[1];
		l[0] = first;
		return l;
	}

	@Override
	public void deserialize(Object[] values) {
		first = values[0];
	}

	@Override
	public String toString() {
		return "first(" + exprs.get(0) + ")";
	}
}
