package eu.dnetlib.enabling.resultset;

import java.util.List;

import com.google.common.collect.Lists;

/**
 * Resultset backing implementation.
 * 
 * @author marko
 * 
 */
public class LocalResultSetImpl extends AbstractObservableResultset implements ResultSet {

	/**
	 * rsId.
	 */
	private String identifier;

	/**
	 * this listener will provide the data to this local resultset by listening to events.
	 */
	private ResultSetListener listener;

	/**
	 * Construct a new local ResultSet which pulls data from the listener. If the listener implements ResultSetAware, it
	 * will be injected with this instance.
	 * 
	 * @param listener
	 *            a resultset listener
	 */
	public LocalResultSetImpl(final ResultSetListener listener) {
		super();
		this.listener = listener;

		if (listener instanceof ResultSetAware)
			((ResultSetAware) listener).setResultSet(this);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.enabling.resultset.ResultSet#getNumberOfResults()
	 */
	@Override
	public int getNumberOfResults() {
		return listener.getSize();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.enabling.resultset.ResultSet#getResults(int, int)
	 */
	@Override
	public List<String> getResults(final int fromPosition, final int toPosition) {
		int toPos = toPosition;
		int fromPos = fromPosition;
		if (!isOpen()) {
			final int size = getNumberOfResults();
			
			if (size == 0)
				return Lists.newArrayList();
			
			if (fromPos > size)
				return Lists.newArrayList();

			if (toPos > size)
				toPos = size;
		}
		
		if (fromPos < 1)
			fromPos = 1;
		if (toPos < fromPos)
			toPos = fromPos;

		return listener.getResult(fromPos, toPos);
	}

	@Override
	public String getIdentifier() {
		return identifier;
	}

	@Override
	public void setIdentifier(final String identifier) {
		this.identifier = identifier;
	}

	public ResultSetListener getListener() {
		return listener;
	}

	public void setListener(final ResultSetListener listener) {
		this.listener = listener;
	}

}
