package org.opengroupware.jope.eocontrol;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.opengroupware.jope.foundation.NSException;
import org.opengroupware.jope.foundation.NSObject;

/*
 * EODataSource
 * 
 * An EODataSource performs a query against some 'entity', in EOF usually a
 * database table (which is mapped to an EOEntity.
 */
public abstract class EODataSource extends NSObject {

  protected Exception            lastException      = null;
  protected EOFetchSpecification fetchSpecification = null;
  
  /* accessors */
  
  public void setFetchSpecification(EOFetchSpecification _fs) {
    // TODO: in SOPE we also notify that fetch specification change to allow
    //       caches to refresh (eg EOCachedDataSource).
    this.fetchSpecification = _fs;
  }
  
  public EOFetchSpecification fetchSpecification() {
    return this.fetchSpecification;
  }
  
  /* error handling */
  
  public Exception lastException() {
    return this.lastException;
  }
  public void resetLastException() {
    this.lastException = null;
  }
  
  /* operations */
  
  public abstract Iterator iteratorForObjects();
  
  public List fetchObjects() {
    return this.iteratorToList(this.iteratorForObjects());
  }
  
  protected List iteratorToList(Iterator _iterator) {
    if (_iterator == null)
      return null;
    
    try {
      List<Object> results = new ArrayList<Object>(16);
      while (_iterator.hasNext())
        results.add(_iterator.next());
      
      return results;
    }
    catch (NSException e) {
      this.lastException = e;
      return null;
    }
    catch (Exception e) {
      this.lastException = e;
      return null;
    }
  }
  
  /* details */
  
  public Exception qualifyWithRelationshipKey(String _key, Object _master) {
    this.lastException = new NSException
      ("this datasource does not implement qualification");
    return this.lastException;
  }
  
  /* changes */
  
  public Object createObject() {
    this.lastException = new NSException
      ("this datasource does not implement createObject");
    return null;
  }

  public Exception updateObject(Object _object) {
    this.lastException = new NSException
      ("this datasource does not implement update");
    return this.lastException;
  }

  public Exception insertObject(Object _object) {
    this.lastException = new NSException
      ("this datasource does not implement insert");
    return this.lastException;
  }

  public Exception deleteObject(Object _object) {
    this.lastException = new NSException
      ("this datasource does not implement delete");
    return this.lastException;
  }
}
