package org.jerrymouse.gaes.mavenPlugin.base;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AppCfgClass {
	String libPath;

	public AppCfgClass(String libPath) {
		this.libPath = libPath;
	}

	Log log = LogFactory.getLog(getClass());

	@SuppressWarnings("unchecked")
	void runAppCfg(List<String> args) {
		try {
			Method main = getAppCfgClass().getMethod("main", String[].class);
			String[] mainArgs = args.toArray(InfoBase.ARG_TYPE);
			Object passedArgv[] = { mainArgs };
			log.debug("mainArgs:" + Arrays.toString(mainArgs));
			main.invoke(null, passedArgv);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public Class getAppCfgClass() {
		return getNamedClass("com.google.appengine.tools.admin.AppCfg");
	}

	@SuppressWarnings("unchecked")
	Class getNamedClass(String name) {
		Class appCfgClass = null;
		try {
			appCfgClass = getClassLoader().loadClass(name);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return appCfgClass;
	}

	private URLClassLoader getClassLoader() {
		URLClassLoader classLoader = null;
		try {
			File file = new File(libPath);
			List<URL> urls = new ArrayList<URL>();
			urls.add(file.toURI().toURL());
			classLoader = new URLClassLoader(urls.toArray(new URL[0]));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return classLoader;
	}

}
