package org.opengroupware.jope.appserver.elements;

import java.text.ParseException;
import java.util.Map;

import org.opengroupware.jope.appserver.WOAssociation;
import org.opengroupware.jope.appserver.WOContext;
import org.opengroupware.jope.appserver.WOElement;
import org.opengroupware.jope.appserver.WOResponse;

/*
 * WOTextField
 * 
 * Create HTML form textfields.
 * 
 * Sample:
 *   Firstname: WOTextField {
 *     name  = "firstname";
 *     value = firstname;
 *   }
 * 
 * Renders:
 *   <input type="text" name="firstname" value="Donald" />
 * 
 * Bindings (WOInput):
 *   name     [in] - string
 *   value    [io] - object
 *   disabled [in] - boolean
 * Bindings:
 *   size     [in] - int
 */
public class WOTextField extends WOInput {
  
  protected WOAssociation size;
  protected WOFormatter   formatter;

  public WOTextField(String _name, Map<String, WOAssociation> _assocs,
                     WOElement _template)
  {
    super(_name, _assocs, _template);
    
    this.size      = grabAssociation(_assocs, "size");
    this.formatter = WOFormatter.formatterForAssociations(_assocs);
  }

  /* applying formatters */
  
  protected Object parseFormValue(Object _value, WOContext _ctx)
    throws ParseException
  {
    if (this.formatter == null)
      return _value;
    
    return this.formatter.objectValueForString
      ((_value != null ? _value.toString() : null), _ctx);
  }
  
  protected String formValueForObject(Object _value, WOContext _ctx) {
    if (this.formatter == null)
      return _value != null ? _value.toString() : null;
      
    return this.formatter.stringForObjectValue(_value, _ctx);
  }
  
  /* responder */
  
  public void appendToResponse(WOResponse _r, WOContext _ctx) {
    if (_ctx.isRenderingDisabled())
      return;

    _r.appendBeginTag("input");
    _r.appendAttribute("type", "text");
    _r.appendAttribute("name", this.elementNameInContext(_ctx));
    
    if (this.value != null) {
      Object ov = this.value.valueInComponent(_ctx.cursor());
      String s  = this.formValueForObject(ov, _ctx);
      if (s != null)
        _r.appendAttribute("value", s);
    }
    
    if (this.size != null) {
      int s;
      if ((s = this.size.intValueInComponent(_ctx.cursor())) > 0)
        _r.appendAttribute("size", s);
    }
    
    if (this.disabled != null) {
      if (this.disabled.booleanValueInComponent(_ctx.cursor()))
        _r.appendAttribute("disabled", "disabled");
    }
    
    this.appendExtraAttributesToResponse(_r, _ctx);
    // TODO: otherTagString
    
    _r.appendBeginTagClose();
  }
  
  /* description */
  
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    this.appendAssocToDescription(_d, "size", this.size);
  }  
}
