package org.opengroupware.jope.eoaccess;

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

import org.opengroupware.jope.foundation.NSObject;

/*
 * EOSQLResultIterator
 * 
 * Used by EOSQLDataSource for fetch operations.
 */
public class EOSQLResultIterator extends NSObject implements Iterator {
  
  protected Statement statement     = null; /* we need to close this */
  protected ResultSet resultSet     = null;
  protected Class     recordClass   = null;
  protected Exception lastException = null;
  
  public EOSQLResultIterator(Statement _stmt, ResultSet _rs, Class _recClass) {
    this.statement   = _stmt;
    this.resultSet   = _rs;
    this.recordClass = _recClass;
  }
  
  /* accessors */
  
  public Exception lastException() {
    return this.lastException;
  }
  
  /* operations */
  
  public Exception close() {
    /* Note: does not affect lastException */
    Exception e = null;

    try {
      this.resultSet.close();
      this.resultSet = null;
    }
    catch (SQLException ce) {
      if (e == null) e = ce;
      System.err.println("failed to close a SQL resultset");
    }

    try {
      this.statement.close();
      this.statement = null;
    }
    catch (SQLException ce) {
      if (e == null) e = ce;
      System.err.println("failed to close a SQL statement");
    }
    
    return e;
  }

  public boolean hasNext() {
    try {
      if (this.resultSet.isLast())
        return false;
      if (this.resultSet.isAfterLast())
        return false;
    }
    catch (SQLException e) {
      this.lastException = e;
      return false;
    }
    return true;
  }

  public Object next() {
    // TODO Auto-generated method stub
    return null;
  }

  public void remove() {
    /* not implemented? */
  }
}
