package org.opengroupware.jope.rules;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opengroupware.jope.foundation.NSObject;

public class RuleAssignment extends NSObject
  implements RuleCandidate, RuleAction
{
  protected static Log log = LogFactory.getLog("JoRules");

  protected String keyPath;
  protected Object value;
  
  public RuleAssignment(String _keyPath, Object _value) {
    this.keyPath = _keyPath;
    this.value   = _value;
  }
  
  /* accessors */
  
  public String keyPath() {
    return this.keyPath;
  }
  
  public Object value() {
    return this.value;
  }
  
  /* operations */
  
  public boolean isCandidateForKey(String _key) {
    if (_key == null)
      return true;
    
    // TODO: perform a real keypath check
    return _key.equals(this.keyPath);
  }
  
  public Object fireInContext(RuleContext _ctx) {
    // TODO: shouldn't we apply the value on ctx ?
    return this.value();
  }
  
  /* representations */
  
  public String valueStringRepresentation() {
    if (this.value == null)
      return "null";
    
    if (this.value instanceof Number)
      return this.value.toString();

    if (this.value instanceof Boolean)
      return ((Boolean)this.value).booleanValue() ? "true" : "false";
    
    return "\"" + this.value.toString() + "\"";
  }
  
  public String stringRepresentation() {
    return this.keyPath() + " = " + this.valueStringRepresentation();
  }
  
  /* description */
  
  @Override
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.keyPath != null)
      _d.append(" kp=" + this.keyPath);
    if (this.value != null)
      _d.append(" value=" + this.value);
  }
}
