package org.eclipse.hawk.sqlite.iteration;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResultSetIterator<T> implements Iterator<T> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ResultSetIterator.class);
	private final ResultSet rs;
	private ResultSetFunction<T> resultToEdge;
	private Boolean hasNext = null;

	public ResultSetIterator(ResultSet rs, ResultSetFunction<T> resultToEdge) {
		this.rs = rs;
		this.resultToEdge = resultToEdge;
	}

	@Override
	public boolean hasNext() {
		if (hasNext == null) {
			try {
				hasNext = rs.next();
				if (!hasNext) {
					rs.close();
				}
			} catch (SQLException e) {
				LOGGER.error(e.getMessage(), e);
				hasNext = false;
			}
		}

		return hasNext;
	}

	@Override
	public T next() {
		if (hasNext()) {
			try {
				final T mapped = resultToEdge.apply(rs);
				hasNext = null;
				return mapped;
			} catch (SQLException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		throw new NoSuchElementException();
	}
}