/* 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.deployment.web;

import javax.naming.Context;

import org.jfox.framework.ComponentException;
import org.jfox.framework.ComponentMeta;
import org.jfox.framework.Registry;
import org.jfox.jndi.enc.AbstractEnterpriseContextContainer;
import org.jfox.jndi.enc.EnterpriseContext;
import org.jfox.jndi.enc.EnterpriseContextInvocationHandler;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class WebEnterpriseContextContainer extends AbstractEnterpriseContextContainer {
    private static WebEnterpriseContextContainer instance = new WebEnterpriseContextContainer();

    private AbstractWebContainer webContainer = null;

    public WebEnterpriseContextContainer() {
        ComponentMeta[] metas = Registry.getInstance().getComponentMetasbyImplemetation(AbstractWebContainer.class);
        if(metas == null || metas.length == 0) {
            throw new RuntimeException("no WebContainer registered.");
        }
        try {
            webContainer = (AbstractWebContainer) metas[0].getComponentInstance();
        }
        catch(ComponentException e) {
            throw new RuntimeException("Web container instance error");
        }
    }

    public static WebEnterpriseContextContainer getInstance() {
        return instance;
    }


    public Context getCurrentEnterpriseContext() {
        String webContext = (String) currName.get();
        if(webContext == null) {
            return new EnterpriseContext();
        }
        return ((NestedWebModule) webContainer.getWebModule(webContext)).getEnterpriseContext();
    }

    public EnterpriseContextInvocationHandler getEnterpriseContextInvocationHandler() {
        return new EnterpriseContextInvocationHandler(getCurrentEnterpriseContext());
    }

    public static void main(String[] args) {

    }
}
