/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.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.4 $
 *   
 */
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();
   }
}
      



