package org.opengroupware.jope.appserver.elements;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opengroupware.jope.appserver.WOActionResults;
import org.opengroupware.jope.appserver.WOAssociation;
import org.opengroupware.jope.appserver.WOContext;
import org.opengroupware.jope.appserver.WODynamicElement;
import org.opengroupware.jope.appserver.WOElement;
import org.opengroupware.jope.appserver.WORequest;
import org.opengroupware.jope.appserver.WOResponse;

/*
 * WOActionURL
 * 
 * Can be used to generate a dynamic link which returns a page (or some other
 * WOActionResults).
 * 
 * Sample .html:
 *   <a href="<#Link/>">login</a>
 * 
 * Sample .wod:
 *   Link: WOActionURL {
 *     actionClass      = "Main";
 *     directActionName = "login";
 *   }
 * 
 * Renders:
 *   <a href="/App/x/LeftMenu/default">[sub-template]</a>
 *   
 * Bindings:
 *   href             [in] - string
 *   directActionName [in] - string
 *   actionClass      [in] - string
 *   pageName         [in] - string
 *   action           [in] - action
 *   
 * TODO: document
 */
public class WOActionURL extends WODynamicElement {
  protected static final Log log = LogFactory.getLog("WOActionURL");
  
  protected WOElement       template;
  protected WOLinkGenerator link;

  public WOActionURL(String _name, Map<String, WOAssociation> _assocs,
                     WOElement _template)
  {
    super(_name, _assocs, _template);
    
    this.link = WOLinkGenerator.linkGeneratorForAssociations(_assocs);
    this.template = _template;
  }

  /* responder */
  
  public void takeValuesFromRequest(WORequest _rq, WOContext _ctx) {
    /* links can take form values !!!! (for query-parameters) */
    
    if (this.link != null)
      this.link.takeValuesFromRequest(_rq, _ctx);
    
    if (this.template != null)
      this.template.takeValuesFromRequest(_rq, _ctx);
  }
  
  public WOActionResults invokeAction(WORequest _rq, WOContext _ctx) {
    if (_ctx.elementID().equals(_ctx.senderID())) {
      if (this.link != null)
        return this.link.invokeAction(_rq, _ctx);

      log.error("no action configured for link invocation");
      return null;
    }
    
    if (this.template != null)
      return this.template.invokeAction(_rq, _ctx);

    return null;
  }
  
  public void appendToResponse(WOResponse _r, WOContext _ctx) {
    if (!_ctx.isRenderingDisabled()) {
      if (this.link != null)
        _r.appendContentHTMLAttributeValue(this.link.fullHrefInContext(_ctx));
    }
    
    if (this.template != null)
      this.template.appendToResponse(_r, _ctx);
  }
  
  /* description */
  
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.link != null) {
      _d.append(" link=");
      _d.append(this.link.toString());
    }
  }  
}
