package org.jerrymouse.gaes.mavenPlugin.mojos.gae;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.jerrymouse.gaes.mavenPlugin.install.DownloadZip;
import org.jerrymouse.gaes.mavenPlugin.install.Environment;
import org.jerrymouse.gaes.mavenPlugin.install.UnZipGae;

/**
 */
public class InstallGaeMojo extends AbstractMojo {

	File downloadFile;

	/**
	 * 
	 * @parameter
	 */
	File downloadPath;

	/**
	 * @parameter default-value="1.2.2"
	 */
	String gaeVersion = "1.2.2";

	/**
	 * @parameter
	 */
	File installPath;

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

	/**
	 * if you want to reInstall Gae ,set it true
	 * 
	 * @parameter expression="${reInstall}" default-value="false"
	 */
	boolean reInstall;

	public static String APPENGINE_HOME = "appengine_home";

	private void downloadZip() {
		if (downloadPath == null) {
			downloadPath = new File(getGaesPath().getAbsoluteFile()
					+ "/download");
		}
		getLog().info(
				"download version " + gaeVersion + " to "
						+ downloadPath.getAbsolutePath());
		DownloadZip downloadManager = new DownloadZip(gaeVersion, downloadPath);
		downloadFile = downloadManager.download();
	}

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (!hasInstall() || reInstall) {
			install();
		} else {
			getLog().info("The Gae has installed");
		}
	}

	public File getGaesPath() {
		return new File(System.getenv("HOME") + "/.gaes");
	}

	public boolean hasInstall() {
		String appengine_home = System.getenv("appengine_home");
		log.trace(appengine_home);
		return new File(appengine_home).exists();
	}

	void install() {
		downloadZip();
		unZip();
		// setEnv();
	}

	@SuppressWarnings("unused")
	@Deprecated
	private void setEnv() {
		Environment environment = Environment.newInstance();
		environment.setEnv(APPENGINE_HOME, installPath + "/appengine-java-sdk-"
				+ gaeVersion);
	}

	private void unZip() {
		if (installPath == null) {
			installPath = getGaesPath();
		}
		getLog().info(
				"unzip " + downloadFile.getAbsolutePath() + " to "
						+ installPath.getAbsolutePath());
		UnZipGae unZipGae = new UnZipGae(downloadFile, installPath);
		unZipGae.unZip();
	}

}
