/* 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 java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import org.jfox.deployment.NestedModule;
import org.jfox.deployment.application.EARModule;
import org.jfox.ejb.meta.XmlUtil;
import org.jfox.framework.deploy.DeployException;
import org.jfox.framework.deploy.Deployer;
import org.jfox.framework.util.JarUtils;
import org.jfox.jndi.enc.EnterpriseContext;

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

public class NestedWebModule extends WebModule implements NestedModule {
    public static final String Target = "webapps" + File.separator;
    private EARModule earModule;

    //enterprise context
    private EnterpriseContext enc = new EnterpriseContext();

    private WebDescriptor webDescriptor;

    public NestedWebModule(EARModule earModule, File warFile, String webConext) throws DeployException {
        super(warFile, webConext);
        this.earModule = earModule;
        init();
    }

    protected void init() throws DeployException {
        try {
            JarUtils.extract(getModuleFile(), getTempDeployDirectory());

            // parse web.xml for ejb-ref etc...
            URL url = getDescriptorURL();
            webDescriptor = new WebDescriptor(this);
            webDescriptor.processXML(XmlUtil.getDocument(url).getDocumentElement());

        }
        catch(Exception e) {
            throw new DeployException("extract web module " + getModuleFile() + " error", e);
        }

    }

    public URL getDescriptorURL() {
        try {
            return new File(getTempDeployDirectory(), "WEB-INF/web.xml").toURL();
        }
        catch(Exception e) {
            return null;
        }
    }

    public void deploy(Deployer deployer) throws DeployException {
        deployer.deploy(this);
    }

    public EARModule getEARModule() {
        return earModule;
    }

    public File getTempDeployDirectory() {
        File dir = new File(earModule.getTempDeployDirectory(), Target + getWebContext());
        if(!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    public URLClassLoader getClassLoader() {
        return earModule.getClassLoader();
//    return (URLClassLoader)this.getClass().getClassLoader();
    }

    /**
     * only nested web module need parse Web Descriptor
     * the not nested WebModule let WebContainer do all of this
     *
     * @return
     */
    public WebDescriptor getWebDescriptor() {
        return webDescriptor;
    }

    /**
     * get the EnterpriseContext java:comp/env
     *
     * @return
     */
    public EnterpriseContext getEnterpriseContext() {
        return enc;
    }

    public static void main(String[] args) {

    }
}

