/**
 * 
 */
package org.seamframework.sql;

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

public class Result implements Iterable<Tuple> {

	private final ResultSet rs;
	private final int columns;
	private final List<Expression<?>> selections;

	Result(ResultSet rs,  int columns, List<Expression<?>> selections) {
		this.rs = rs;
		this.columns = columns;
		this.selections = selections;
	}

	public List<Expression<?>> getSelections() {
		return selections;
	}
	
	public ResultSet getResultSet() {
		return rs;
	}

	public Iterator<Tuple> iterator() {
		return new Iterator<Tuple>() {
			boolean more;
			{
				try {
					more = rs.next();
				}
				catch (SQLException sqle) {
					throw new RuntimeException(sqle);
				}
			}
			
			@Override
			public boolean hasNext() {
				return more;
			}
			
			@Override
			public Tuple next() {
				if (!more) {
					throw new NoSuchElementException();
				}
				try {
					List<Object> row = new ArrayList<Object>(columns);
					for (int i=1; i<=columns; i++) {
						//Expression<?> e = selections.get(i);
						row.add( rs.getObject(i) );
					}
					if ( !rs.next() ) {
						more=false;
						rs.close();
					}
					return new Tuple(selections, row);
				}
				catch (SQLException sqle) {
					throw new RuntimeException(sqle);
				}
			}
			
			@Override
			public void remove() {
				if (!more) {
					throw new NoSuchElementException();
				}
				try {
					rs.deleteRow();
				}
				catch (SQLException sqle) {
					throw new RuntimeException(sqle);
				}
			}
		};
	}
}