package eu.dnetlib.data.collector.plugins.datasets;

import java.io.IOException;
import java.util.Iterator;

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

/**
 * The Class DatasetsByProjectIterator.
 */
public class DatasetsByJournalIterator implements Iterable<String>, Iterator<String> {

	/** The current iterator. */
	private Iterator<String> currentIterator;

	/** The current project. */
	private PangaeaJournalInfo currentJournal;

	private Iterator<PangaeaJournalInfo> inputIterator;

	/** The logger. */
	private static final Log log = LogFactory.getLog(DatasetsByProjectIterator.class);

	public DatasetsByJournalIterator(final Iterator<PangaeaJournalInfo> iterator) {
		this.inputIterator = iterator;
		this.currentJournal = extractNextLine();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#hasNext()
	 */
	@Override
	public boolean hasNext() {
		// CASE WHEN WE REACH THE LAST ITEM ON CSV
		// OR WE HAD SOME PROBLEM ON GET NEXT CSV ITEM
		if (this.currentJournal == null) { return false; }
		// IN THIS CASE WE HAVE ANOTHER DATASETS
		// FOR THE CURRENT PROJECT AND RETURN TRUE
		if (currentIterator != null && currentIterator.hasNext()) { return true; }
		// OTHERWISE WE FINISHED TO ITERATE THE CURRENT
		// SETS OF DATASETS FOR A PARTICULAR PROJECT
		// SO WE HAVE TO RETRIEVE THE NEXT ITERATOR WITH
		// ITEMS
		this.currentJournal = extractNextLine();

		while (this.currentJournal != null) {
			currentIterator = getNextIterator();
			// IF THE NEXT ITERATOR HAS ITEMS RETURN YES
			// OTHERWISE THE CICLE CONTINUE
			if (currentIterator.hasNext()) { return true; }
			this.currentJournal = extractNextLine();
		}
		return false;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#next()
	 */
	@Override
	public String next() {
		return this.currentIterator.next();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#remove()
	 */
	@Override
	public void remove() {}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Iterable#iterator()
	 */
	@Override
	public Iterator<String> iterator() {
		if (this.currentJournal != null) {
			currentIterator = getNextIterator();
			return this;
		}
		return null;

	}

	private Iterator<String> getNextIterator() {
		QueryField q = new QueryField();
		RequestField r = new RequestField();
		r.setQuery(q);
		q.getTerm().put("ft-techkeyword", this.currentJournal.getJournalId());

		return new DatasetsIterator(r, "", this.currentJournal).iterator();
	}

	/**
	 * Extract next line.
	 *
	 * @return the map
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private PangaeaJournalInfo extractNextLine() {

		if (this.inputIterator.hasNext() == false) { return null; }
		return this.inputIterator.next();

	}
}
