/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.ejb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.transaction.TransactionManager;

import org.jfox.ejb.handler.Interceptor;
import org.jfox.ejb.meta.Protocol;
import org.jfox.jndi.InitialContextHelper;
import org.jfox.system.AbstractComponent;
import org.jfox.tm.TxManager;

/**
 * EJB Container 实现，Container 是一个 singleton 类，一个 Container 可以布署多种 ejb ，
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class ContainerImpl extends AbstractComponent implements Container {
    // singleton instance
    private static Container instance = null;

    // jndi instance
    static Context INITIAL_CONTEXT = null;

    // loaded bean buckets
    private Map buckets = new HashMap();

    private BucketFactory bucketFactory = BucketFactory.getInstance();

    private List interceptors = new ArrayList();

    // 指定用于绑定在 Home 上的默认的协议
    protected Protocol remoteProtocol = Protocol.JRMP;
    protected Protocol localProtocol = Protocol.LOCAL;

    private ContainerImpl() {
//    bucketFactory = BucketFactory.getInstance();
    }

    public static synchronized Container getInstance() {
        if(instance == null) {
            instance = new ContainerImpl();
        }
        return instance;
    }

    public TransactionManager getTransactionManager() {
        return TxManager.getInstance();
    }

    public Context getInitialContext() {
        return INITIAL_CONTEXT;
    }

    protected void doInit() throws Exception {
        INITIAL_CONTEXT = InitialContextHelper.getInitialContext();
    }

    protected synchronized void doDestroy() throws Exception {
        for(Iterator it = buckets.values().iterator(); it.hasNext();) {
            ((BucketSupport) it.next()).destroy();
        }
        INITIAL_CONTEXT = null;
        buckets = new HashMap();
    }

    public Iterator listBuckets() {
        return buckets.keySet().iterator();
    }

    /**
     * create a bean bucket and bind it's home to jndi
     *
     * @param meta
     */
    public synchronized void createBucket(BucketMetaData meta) throws Exception {
        Bucket bucket = bucketFactory.createBucket(meta);
        bucket.init();
        buckets.put(meta.getEJBDescriptor().getEjbName(), bucket);
    }

    /**
     * remove the bucket from container , 发生在 undeploy 一个 bean 的时候
     */
    public synchronized void dropBucket(String ejbName) throws Exception {
        buckets.remove(ejbName);
        ((Bucket) buckets.get(ejbName)).destroy();
    }

    /**
     * container 可能对该方法调用进行一些统一的调控，如：安全验证等，然后 forward 给 bucket 执行
     *
     * @return
     * @throws Exception
     */
    public Object invoke(Invocation invocation) throws Exception {
        logger.debug("invoke " + invocation.toString());
        String ejbName = invocation.getObjectId().getEjbName();
        Bucket bucket = getBucket(ejbName);

        if(invocation.getObjectId().isHome()) { // EJBHome 方法
            invocation.setMethod(bucket.getHomeMethod(invocation));
            preInvokeHome(invocation);
            Object result = bucket.invokeHome(invocation);
            postInvokeHome(invocation);
            return result;
        }
        else { // Bean 方法
            invocation.setMethod(bucket.getBeanMethod(invocation));
            preInvokeBean(invocation);
            Object result = bucket.invokeBean(invocation);
            postInvokeBean(invocation);
            return result;
        }

    }

    public void addInterceptor(Interceptor interceptor) throws Exception {
        interceptor.setContainer(this);
        synchronized(interceptors) {
            interceptors.add(interceptor);
        }
    }

    public synchronized Iterator interceptors() {
        return interceptors.iterator();
    }

    public Protocol getRemoteProtocol() {
        return remoteProtocol;
    }

    public void setRemoteProtocol(Protocol remoteProtocol) {
        this.remoteProtocol = remoteProtocol;
    }

    public Protocol getLocalProtocol() {
        return localProtocol;
    }

    public void setLocalProtocol(Protocol localProtocol) {
        this.localProtocol = localProtocol;
    }

    public Bucket getBucket(String ejbName) {
        return (Bucket) buckets.get(ejbName);
    }

    private void preInvokeHome(Invocation invocation) throws Exception {
        for(Iterator it = this.interceptors(); it.hasNext();) {
            Interceptor interceptor = (Interceptor) it.next();
            interceptor.preInvokeHome(invocation);
        }
    }

    private void preInvokeBean(Invocation invocation) throws Exception {
        for(Iterator it = this.interceptors(); it.hasNext();) {
            Interceptor interceptor = (Interceptor) it.next();
            interceptor.preInvokeBean(invocation);
        }
    }

    private void postInvokeHome(Invocation invocation) throws Exception {
        for(Iterator it = this.interceptors(); it.hasNext();) {
            Interceptor interceptor = (Interceptor) it.next();
            interceptor.preInvokeHome(invocation);
        }
    }

    private void postInvokeBean(Invocation invocation) throws Exception {
        for(Iterator it = this.interceptors(); it.hasNext();) {
            Interceptor interceptor = (Interceptor) it.next();
            interceptor.preInvokeBean(invocation);
        }
    }

    public static void main(String[] args) {

    }
}