/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.jfox.ejb.plugin;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;

import javax.ejb.EJBException;

import org.jfox.ejb.Invocation;
import org.jfox.ejb.Bulk;

/**
 * 对于一个 Bean 的调用链,Bulk 利用调用链来完成具体的操作
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public abstract class InvokerChain {
  protected List invokers = new ArrayList();

  public InvokerChain() {

  }

  public static Object nextInvokeHome(Bulk bulk,Invocation invocation, Iterator iter) throws Exception {
    if(iter.hasNext()){
      return ((Invoker)iter.next()).invokeHome(bulk, invocation,iter);
    }
    else {
      throw new EJBException("No Invoker");
    }
  }

  public static Object nextInvokeBean(Bulk bulk, Invocation invocation, Iterator iter) throws Exception {
    if(iter.hasNext()){
      return ((Invoker)iter.next()).invokeBean(bulk, invocation,iter);
    }
    else {
      throw new EJBException("No Invoker");
    }
  }

  public synchronized void addInvoker(Invoker invoker){
    for(int i=0;i<invokers.size();i++){
      // already have
      if(invokers.get(i).getClass().getName().equals(invoker.getClass().getName())){
        return;
      }
    }
    invokers.add(invoker);
    Collections.sort(invokers);
  }

  public synchronized void removeInvoker(String invokerClassName){
    for(int i=0;i<invokers.size();i++){
      if(invokers.get(i).getClass().getName().equals(invokerClassName)){
        invokers.remove(i);
        return;
      }
    }
  }

  public String[] listInvokers(){
    List invokerStringArray = new ArrayList();
    for(int i=0; i<invokers.size(); i++){
      invokerStringArray.add(invokers.get(i).getClass().getName());
    }
    return (String[])invokerStringArray.toArray(new String[]{});
  }

  public abstract Object invokeHome(Bulk bulk, Invocation invocation) throws Exception;

  public abstract Object invokeBean(Bulk bulk, Invocation invocation) throws Exception;
}