package jp.sourceforge.glad.jdbc.iteration;

import java.sql.ResultSet;
import java.sql.SQLException;

import jp.sourceforge.glad.collection.closure.Closure;
import jp.sourceforge.glad.collection.exception.BreakException;
import jp.sourceforge.glad.collection.exception.ContinueException;
import jp.sourceforge.glad.collection.iteration.IterationHandler;
import jp.sourceforge.glad.collection.iteration.IterationHandlerSupport;
import jp.sourceforge.glad.jdbc.SqlRuntimeException;

public class ResultSetIterationHandler
        extends IterationHandlerSupport<ResultSet>
        implements IterationHandler<ResultSet> {

    private final ResultSet resultSet;
    private final boolean close;

    public ResultSetIterationHandler(ResultSet resultSet) {
        this(resultSet, true);
    }

    public ResultSetIterationHandler(ResultSet resultSet, boolean close) {
        this.resultSet = resultSet;
        this.close = close;
    }

    protected void doIterate(Closure<ResultSet> callback) throws Exception {
        while (resultSet.next()) {
            try {
                callback.execute(resultSet);
            } catch (ContinueException e) {
                continue;
            } catch (BreakException e) {
                break;
            }
        }
    }

    @Override
    protected void close() throws SQLException {
        if (close) {
            resultSet.close();
        }
    }

    @Override
    protected void handleCheckedException(Exception e) {
        if (SQLException.class.isInstance(e)) {
            handleSQLException(SQLException.class.cast(e));
        } else {
            super.handleCheckedException(e);
        }
    }

    protected void handleSQLException(SQLException e) {
        throw new SqlRuntimeException(e);
    }

}
