/*
  Copyright (C) 2007 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.publisher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opengroupware.jope.appserver.core.WOComponent;
import org.opengroupware.jope.appserver.core.WOContext;
import org.opengroupware.jope.foundation.NSObject;

/*
 * JoPageInvocation
 * 
 * This callable instantiates a component and runs an action (or 'default').
 * 
 * TODO: document
 */
public class JoPageInvocation extends NSObject implements JoCallable {
  protected static final Log log = LogFactory.getLog("JoClass");

  protected String pageName;
  protected String actionName;
  
  public JoPageInvocation(String _name, String _action) {
    this.pageName   = _name;
    this.actionName = _action != null ? _action : "default";
  }
  public JoPageInvocation(String _name) {
    this(_name, null /* action */);
  }
  
  /* JoCallable */
  
  public Object callInContext(Object _object, JoContext _ctx) {
    WOContext   ctx  = (WOContext)_ctx;
    WOComponent page = ctx.page();
    
    if (page != null) {
      /* first attempt to lookup page based on the current page*/
      page = page.pageWithName(this.pageName);
    }
    else {
      /* otherwise use the application */
      page = ctx.application().pageWithName(this.pageName, ctx);
    }
    
    if (page == null) {
      log.error("could not instantiate page: " + this.pageName);
      return null;
    }
    
    // TODO: do we need to run takeValues or something?
    
    Object result = page.performActionNamed(this.actionName);
    if (log.isDebugEnabled())
      log.debug("action returned object: " + result);
    
    return result;
  }
  
  public boolean isCallableInContext(JoContext _ctx) {
    /* we need a WOContext to be able to instantiate the component */
    return _ctx instanceof WOContext;
  }
  
  /* description */
  
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.pageName != null)
      _d.append(" page=" + this.pageName);
  }
}
