package org.opengroupware.jope.eoaccess;

import java.util.Map;

import org.opengroupware.jope.eocontrol.EOFetchSpecification;
import org.opengroupware.jope.eocontrol.EOQualifier;
import org.opengroupware.jope.foundation.NSJavaRuntime;
import org.opengroupware.jope.foundation.NSObject;

/*
 * EOSQLExpressionFactory
 * 
 * TODO: document
 */
public class EOSQLExpressionFactory extends NSObject {

  protected EOAdaptor adaptor;
  protected Class     expressionClass;
  
  public EOSQLExpressionFactory(EOAdaptor _adaptor) {
    this.adaptor = _adaptor;
    
    if (this.adaptor != null)
      this.expressionClass = this.adaptor.expressionClass();
  }
  
  /* accessors */
  
  public EOAdaptor adaptor() {
    return this.adaptor;
  }
  
  /* factory */
  
  public EOSQLExpression createExpression(EOEntity _e) {
    if (this.expressionClass != null) {
      return (EOSQLExpression)NSJavaRuntime.NSAllocateObject
               (this.expressionClass, EOEntity.class, _e);
    }
    return new EOSQLExpression(_e);
  }
  
  public EOSQLExpression expressionForString(String _sql) {
    if (_sql == null || _sql.length() == 0) return null;
    EOSQLExpression e = this.createExpression(null /* entity */);
    e.setStatement(_sql);
    return e;
  }
  
  public EOSQLExpression deleteStatementWithQualifier
    (EOQualifier _qualifier, EOEntity _entity)
  {
    EOSQLExpression e = this.createExpression(_entity);
    e.prepareDeleteExpressionForQualifier(_qualifier);
    return e;
  }
  
  public EOSQLExpression insertStatementForRow
    (Map<String, Object> _row, EOEntity _entity)
  {
    EOSQLExpression e = this.createExpression(_entity);
    e.prepareInsertExpressionWithRow(_row);
    return e;
  }

  public EOSQLExpression updateStatementForRow
    (Map<String, Object> _row, EOQualifier _qualifier, EOEntity _entity)
  {
    EOSQLExpression e = this.createExpression(_entity);
    e.prepareUpdateExpressionWithRow(_row, _qualifier);
    return e;
  }
  
  public EOSQLExpression selectExpressionForAttributes
    (EOAttribute[] _attrs, boolean _lock, EOFetchSpecification _f, EOEntity _e)
  {
    EOSQLExpression e = this.createExpression(_e);
    e.prepareSelectExpressionWithAttributes(_attrs, _lock, _f);
    return e;
  }
  
  /* description */

  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.adaptor != null) _d.append(" adaptor=" + this.adaptor);
  }
}
