package eu.dnetlib.enabling.resultset.push;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import eu.dnetlib.enabling.resultset.AbstractObservableResultset;

/**
 * a push resultset which holds it's data in a transient cache.
 *
 * @author marko
 *
 */
public class TransientPushResultSetImpl extends AbstractObservableResultset implements PushResultSet {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(TransientPushResultSetImpl.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * dao.
	 */
	private final transient TransientPushResultSetDao dao;

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

	/**
	 * constructed by the transient push resultset factory.
	 *
	 * @param dao dao
	 */
	public TransientPushResultSetImpl(final TransientPushResultSetDao dao) {
		super();
		this.dao = dao;
		setOpen(true);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.resultset.push.PushResultSet#addElements(java.util.List)
	 */
	@Override
	public void addElements(final List<String> elements) {
		log.debug("adding to push RS: " + elements);

		if (isOpen())
			dao.addElements(getIdentifier(), elements);
		else
			throw new IllegalStateException("cannot write to a closed push resultset");
	}

	@Override
	public int getNumberOfResults() {
		return dao.getSize(getIdentifier());
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.resultset.ResultSet#getResults(int, int)
	 */
	@Override
	public List<String> getResults(final int fromPosition, final int toPosition) {

		final int size = getNumberOfResults();
		int toPos = toPosition;
		int fromPos = fromPosition;
		if (fromPos > size)
			fromPos = size;
		if (toPos > size)
			toPos = size;

		log.debug("calling get elements: " + getIdentifier() + " from " + fromPos + " to " + toPos);
		return dao.getElements(getIdentifier(), fromPos, toPos);
	}

	public TransientPushResultSetDao getDao() {
		return dao;
	}

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

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


}
