package org.eclipse.hawk.sqlite.iteration;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

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

public class StatementIterable<T> implements Iterable<T> {
	private static final Logger LOGGER = LoggerFactory.getLogger(StatementIterable.class);
	private final StatementSupplier stmtSupplier;
	private final ResultSetFunction<T> resultToEdge;

	public StatementIterable(StatementSupplier stmtSupplier, ResultSetFunction<T> fn) {
		this.stmtSupplier = stmtSupplier;
		this.resultToEdge = fn;
	}

	@Override
	public Iterator<T> iterator() {
		try {
			PreparedStatement stmt = stmtSupplier.get();
			stmt.execute();

			List<T> results = new ArrayList<>();
			try (ResultSet rs = stmt.getResultSet()) {
				while (rs.next()) {
					results.add(resultToEdge.apply(rs));
				}
			}
			return results.iterator();
		} catch (SQLException e) {
			LOGGER.error(e.getMessage(), e);
			return Collections.emptyIterator();
		}
	}
}