/*
  Copyright (C) 2006 Helge Hess

  This file is part of JOPE.

  JOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  JOPE is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with JOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/

package org.opengroupware.jope.appserver;

import java.util.Map;

/*
 * TODO:
 * - keep extraAttributes as arrays for speed
 * - pregenerate HTML for constant extra attributes
 */

public class WODynamicElement extends WOElement {
  
  protected WOAssociation             otherTagString;
  protected Map<String,WOAssociation> extraAttributes;

  public WODynamicElement(String _name, Map<String,WOAssociation> _assocs, 
                          WOElement _template)
  {
  }
  
  /* helpers */
  
  public static WOAssociation grabAssociation
    (Map<String,WOAssociation> _assocs, String _name)
  {
    if (_assocs == null)
      return null;
    
    WOAssociation assoc = _assocs.get(_name);
    if (assoc == null)
      return null;
    
    _assocs.remove(_name);
    return assoc;
  }
  
  /* accessors */
  
  public void setExtraAttributes(Map<String, WOAssociation> _attrs) {
    this.extraAttributes = _attrs;
  }
  
  /* response */
  
  public void appendExtraAttributesToResponse(WOResponse _r, WOContext _c) {
    if (this.extraAttributes == null)
      return;
    
    Object cursor = _c.cursor();
    for (String k: this.extraAttributes.keySet()) {
      String v = this.extraAttributes.get(k).stringValueInComponent(cursor);
      if (v != null) _r.appendAttribute(k, v);
    }
  }
  
  /* description */
  
  public void appendAssocToDescription
    (StringBuffer _d, String _name, WOAssociation _a)
  {
    if (_a == null)
      return;
    
    _d.append(' ');
    _d.append(_name);
    _d.append('=');

    // TODO: make output even smarter ;-)
    if (!_a.isValueConstant()) {
      _d.append(_a);
      return;
    }
    
    /* constant assocs */
    
    Object v = _a.valueInComponent(null);
    
    if (v != null) {
      _d.append('"');
      if (v instanceof String) {
        if (((String)v).length() > 79)
          v = ((String)v).substring(0, 77) + "...";
      }
      _d.append(v);
      _d.append('"');
    }
    else
      _d.append(" null");
  } 
}
