package eu.dnetlib.enabling.resultset;

import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.wsaddressing.W3CEndpointReference;

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

import eu.dnetlib.enabling.resultset.rmi.ResultSetException;
import eu.dnetlib.enabling.resultset.rmi.ResultSetService;
import eu.dnetlib.enabling.tools.ServiceResolver;

public class CachingResultSetListener implements ResultSetListener {
	private static final Log log = LogFactory.getLog(CachingResultSetListener.class); // NOPMD by marko on 11/24/08 5:02 PM

	
	private ResultSetService service;
	private String rsId;

	private ArrayList<String> storage = new ArrayList<String>();

	public CachingResultSetListener(W3CEndpointReference epr, ServiceResolver serviceResolver) {
		this.service = serviceResolver.getService(ResultSetService.class, epr);
		this.rsId = serviceResolver.getResourceIdentifier(epr);
	}

	@Override
	public List<String> getResult(int fromPosition, int toPosition) {
		if (storage.get(fromPosition) != null)
			return cached(fromPosition, toPosition);
		try {
			List<String> data = service.getResult(rsId, fromPosition, toPosition, "waiting");
			cache(data, fromPosition, toPosition);
			return data;
		} catch (ResultSetException e) {
			throw new IllegalStateException(e);
		}
	}

	private void cache(List<String> data, int fromPosition, int toPosition) {
		for(String value : data)
			storage.set(fromPosition++, value);
	}

	private List<String> cached(int fromPosition, int toPosition) {
		log.info("found cached page " + fromPosition + ", " + toPosition);
		return storage.subList(fromPosition-1, toPosition);
	}

	@Override
	public int getSize() {
		try {
			return service.getNumberOfElements(rsId);
		} catch (ResultSetException e) {
			throw new IllegalStateException(e);
		}
	}

}
