package org.opengroupware.jope.appserver;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;

import org.opengroupware.jope.foundation.NSJavaRuntime;

public class WODirectAction extends WOAction {
  
  static Class[]  emptyClassArray  = new Class[0];
  static Object[] emptyObjectArray = new Object[0];
  
  public WODirectAction(WOContext _ctx) {
    super(_ctx);
  }
  
  public WOActionResults performActionNamed(String _name) {
    return WODirectAction.performActionNamed(this, _name, this.context());
  }
  public static WOActionResults performActionNamed
    (Object _o, String _name, WOContext _ctx)
  {
    if (_o == null || _name == null)
      return null;
    
    Method m = NSJavaRuntime.NSMethodFromString
      (_o.getClass() , _name + "Action", emptyClassArray);
    
    if (m == null) {
      // TODO: improve logging
      System.err.println("ERROR: did not find method for DA: " + _name +
                         " (object=" + _o + ")");
      return _ctx.application().handleMissingAction(_name, _ctx);
    }
    
    WOActionResults results;
    try {
      results = (WOActionResults)m.invoke(_o, emptyObjectArray);
    }
    catch (InvocationTargetException ite) {
      results = _ctx.application().handleException(ite.getCause(), _ctx);
    }
    catch (IllegalAccessException iae) {
      // TODO: improve logging
      System.err.println("ERROR: invalid access for DA: " + iae);
      results = _ctx.application().handleMissingAction(_name, _ctx);      
    }
    return results;
  }
  
  public WOActionResults defaultAction() {
    return this.pageWithName("Main");
  }
  
  /* form values */
  
  public void takeFormValueArraysForKeyArray(String[] _keys) {
    WORequest r = this.request();

    for (String k: _keys)
      this.takeValueForKey(r.formValuesForKey(k), k);
  }
  public void takeFormValueArraysForKeyArray(Collection<String> _keys) {
    this.takeFormValueArraysForKeyArray((String[])_keys.toArray());
  }
}
