package org.opengroupware.jope.eocontrol;

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

/*
 * EOArrayDataSource
 * 
 * Takes a Java List object and performs arbitary queries on that using
 * KVC.
 * 
 * Note that modifications directly affect the given array!
 */
public class EOArrayDataSource extends EODataSource {
  
  List<Object> objects = null;
  
  public EOArrayDataSource(List<Object> _objects) {
    this.objects = _objects;
  }

  /* operations */
  
  public Iterator iteratorForObjects() {
    List results = this.fetchObjects();
    if (results == null)
      return null;
    
    return results.iterator();
  }
  
  public List fetchObjects() {
    List list = new ArrayList<Object>(this.objects);
    
    EOFetchSpecification fs = this.fetchSpecification();
    if (fs != null) {
      EOQualifier q = fs.qualifier();
      if (q != null)
        list = q.filterCollection(list);
      
      EOSortOrdering.sort(list, fs.sortOrderings());
    }
    return list;
  }
  
  /* modifications */
  
  public Exception updateObject(Object _object) {
    /* Well, unless we have some other identifier to find the object in the
     * array the update already took place ;-)
     */
    return null; /* means no error */
  }

  @SuppressWarnings("unchecked")
  public Exception insertObject(Object _object) {
    if (_object == null) /* we ignore null inserts */
      return null;
    
    if (this.objects.contains(_object)) {
      this.lastException = new Exception("object already contained.");
      return this.lastException;
    }
    
    if (this.objects == null)
      this.objects = new ArrayList(2);
    
    this.objects.add(_object);
    return null; /* means no error */
  }
  
  public Exception deleteObject(Object _object) {
    if (_object == null) /* we ignore null inserts */
      return null;
    
    if (this.objects == null || !this.objects.contains(_object)) {
      this.lastException = new Exception("object not contained.");
      return this.lastException;
    }
    
    this.objects.remove(_object);
    return null; /* means no error */  
  }
  
  /* description */

  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.objects == null)
      _d.append(" no-array");
    else
      _d.append(" count=" + this.objects.size());
  }
}
