package eu.dnetlib.data.mdstore.modular;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import eu.dnetlib.data.mdstore.DocumentNotFoundException;
import eu.dnetlib.data.mdstore.MDStoreServiceException;
import eu.dnetlib.data.mdstore.modular.connector.MDStore;
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
import eu.dnetlib.enabling.resultset.ResultSetFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;

import javax.xml.ws.wsaddressing.W3CEndpointReference;
import java.util.List;
import java.util.Map;

public class MDStoreRetriever {

	/** Logger */
	private static final Log log = LogFactory.getLog(MDStoreRetriever.class);

	private MDStoreDao dao;

	private ResultSetFactory resultSetFactory;

	public W3CEndpointReference deliver(final String mdId, final String from, final String until, final String recordFilter) throws MDStoreServiceException {
		final MDStore mdStore = dao.readMDStore(mdId);
		return getResultSetFactory().createResultSet(mdStore.deliver(from, until, recordFilter));
	}

	public Iterable<String> deliver(final String format, final String layout, final String interpretation) throws MDStoreServiceException {
		try {
			return Iterables.concat(Iterables.transform(dao.listMDStores(format, layout, interpretation), new Function<String, Iterable<String>>() {

				@Override
				public Iterable<String> apply(final String mdId) {
					log.debug("bulk deliver of mdId: " + mdId);
					try {
						return dao.readMDStore(mdId).iterate();
					} catch (MDStoreServiceException e) {
						throw new RuntimeException(e);
					}
				}
			}));
		} catch (RuntimeException e) {
			throw new MDStoreServiceException(e);
		}
	}

	public String deliverRecord(final String mdId, final String recordId) throws MDStoreServiceException, DocumentNotFoundException {
		return dao.getMDStore(mdId).getRecord(recordId);
	}

	public MDStoreDao getDao() {
		return dao;
	}

	@Required
	public void setDao(final MDStoreDao dao) {
		this.dao = dao;
	}

    public ResultSetFactory getResultSetFactory() {
        return resultSetFactory;
    }

	@Required
	public void setResultSetFactory(final ResultSetFactory resultSetFactory) {
		this.resultSetFactory = resultSetFactory;
	}

    public List<String> getMDStoreRecords(final String mdId, int pageSize, final int offset, final Map<String, String> queryParam) throws MDStoreServiceException {
        MDStore mdStore = dao.getMDStore(mdId);
        return mdStore.deliver(mdId, pageSize, offset, queryParam);
    }
}
