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

import org.jfox.deployment.J2EEClassLoader;
import org.jfox.deployment.J2EEModule;
import org.jfox.framework.deploy.DeployException;
import org.jfox.framework.deploy.Deployer;
import org.jfox.framework.util.JarUtils;
import org.jfox.system.JFoxMeta;

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

public class WebModule extends J2EEModule {
    private File warFile;
    private String baseDeployDirectory = JFoxMeta.getJFoxHome() + "/" + File.separator + "temp" + File.separator;

    private J2EEClassLoader loader;
    private String webContext;

    public WebModule(File warFile) throws DeployException {
        this.warFile = warFile;
        // trim the ".war"
        this.webContext = warFile.getName().substring(0, warFile.getName().length() - 4);
        init();
    }

    protected WebModule(File warFile, String webContext) {
        this.warFile = warFile;
        this.webContext = webContext;
    }

    protected void init() throws DeployException {
        try {
            JarUtils.extract(warFile, getTempDeployDirectory());
        }
        catch(IOException e) {
            throw new DeployException("extract web module " + warFile + " error", e);
        }
    }

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

    public File getModuleFile() {
        return warFile;
    }

    /**
     * just return the Thread ContextClassLoader
     *
     * @return
     */
    public URLClassLoader getClassLoader() {
        if(loader == null) {
            loader = new J2EEClassLoader(new URL[]{}, this.getClass().getClassLoader());
        }
        return loader;
    }

    public File getTempDeployDirectory() {
        File dir = new File(baseDeployDirectory, warFile.getName() + File.separator + "webapp" + File.separator  + webContext);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

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

    public String getWebContext() {
        return webContext;
    }

    public static void main(String[] args) {

    }
}

