/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.mx.server;

import org.jboss.mx.interceptor.AbstractInterceptor;


/**
 *
 * @author  <a href="mailto:juha@jboss.org">Juha Lindfors</a>.
 * @version $Revision: 1.5.2.3 $
 *   
 */
public class Invocation
   extends InvocationContext   
   implements Dispatcher
{
   private Object[] args;
   private int ic_counter = 0;
   
   // Constructors --------------------------------------------------
   public Invocation() {}
   
   public Invocation(InvocationContext ic)
   {
      addContext(ic);
   }
   
   
   // Public --------------------------------------------------------
   
   public void addContext(final InvocationContext ctx)
   {
      super.copy(ctx);
   }

   public void setArgs(Object[] args)
   {
      this.args = args;
   }

   public Object[] getArgs()
   {
      return args;
   }
         
   public Object dispatch() throws InvocationException
   {
      return dispatch(args);
   }

   public Object dispatch(Object[] args) throws InvocationException
   {
      if (dispatcher == null)
         return Void.TYPE;
  
      return dispatcher.dispatch(args);
   }       

   public AbstractInterceptor nextInterceptor()
   {
      if (interceptors == null)
         return null;
         
      if (ic_counter < interceptors.size())
          return (AbstractInterceptor)interceptors.get(ic_counter++);
      else
         return null;
   }
      
      
   public Object invoke() throws InvocationException
   {
      AbstractInterceptor ic = nextInterceptor();
      
      if (ic == null)
         return dispatch();
      else
         return ic.invoke(this);
         
   }
   
   public String toString()
   {
      return getName() + " " + getType();
   }
}
      



