/* 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.huihoo.jfox;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jfox.mx.MxServer;
import org.jfox.mx.ObjectName;
import org.jfox.mx.loading.MxLoading;

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

public class Startup {
  private static String jfoxHome = null;
  private static String configXML = "jfox.xml";

  private static String[] dirctoryClassPath = {"conf",};
  // 需要加载的 jar 所在的目录
  private static String[] jarClassPath = {"lib", "dist"};
//  private static Logger logger ;

  public Startup() {
//    logger = Logger.getLogger(Startup.class.getName());
    jfoxHome = System.getProperty("jfox.home");
  }

  public void startup() throws Exception {
    MxServer mx = MxServer.getInstance();
    MxLoading mxLoading = (MxLoading)mx.createMX("org.jfox.mx.loading.MxLoading", new ObjectName(":comp=MxLoading"));

    URL[] jars = getJarURLs();
    for(int i=0; i<jars.length; i++){
      mxLoading.addLiberary(jars[i]);
    }
    Thread.currentThread().setContextClassLoader(mxLoading.getClassLoader());

    URL[] classpath = mxLoading.mx_getURLs();
    for(int i=0; i<classpath.length; i++){
      System.out.println("class path => " + classpath[i].toString());
    }
    mxLoading.mx_loadMx(configXML);

  }

  private URL[] getJarURLs() throws Exception {
    List urls = new ArrayList();

    for(int i=0; i<dirctoryClassPath.length; i++){
      String url = jfoxHome + File.separator + dirctoryClassPath[i];
      urls.add(new File(url).toURL());
    }

    for (int i = 0; i < jarClassPath.length; i++) {
      String url = jfoxHome + File.separator + jarClassPath[i];
      loadJars(urls,new File(url));
    }
    return (URL[])urls.toArray(new URL[]{});
  }

  private void loadJars(List jarList, File dir) throws Exception {
    File[] jars = dir.listFiles(new java.io.FileFilter() {
      public boolean accept(File pathname) {
        String name = pathname.getName();
        return pathname.isDirectory() || name.endsWith(".jar") || name.endsWith(".zip");
      }
    }
    );
    for(int i=0; i< jars.length; i++){
      if(jars[i].isFile()) {
        jarList.add(jars[i].toURL());
      }
      else {
        loadJars(jarList,jars[i]);
      }
    }
  }

  public static void main(String[] args) throws Exception {
    System.out.println("JFox Java Application by huihoo.org !");
    Thread.currentThread().setName("JFox");
    File jfoxHome = new File("../");
    System.setProperty("jfox.home", jfoxHome.getCanonicalPath());
    System.out.println("jfox.home => " + System.getProperty("jfox.home"));
    System.out.println("configuration file => " + System.getProperty("jfox.home") + File.separator + "conf" + File.separator + configXML);
    new Startup().startup();
  }

}