package org.jerrymouse.gaes.mavenPlugin.install;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;

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

public class DownloadZip implements Observer {

	static String GAEBASEPATH = "	http://googleappengine.googlecode.com/files/";

	double currentProgress;

	private Download download;

	private File downloadPath;

	private File downloadFile;

	private String version;

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

	public DownloadZip(String gaeVersion, File downloadPath) {
		version = gaeVersion;
		this.downloadPath = downloadPath;
		download = new Download(createURL(), createDownloadFile(), this);
	}

	private File createDownloadFile() {
		if (!downloadPath.exists())
			downloadPath.mkdirs();
		String path = downloadPath.getAbsolutePath() + "/" + fileName();
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
		downloadFile = file;
		return downloadFile;
	}

	private URL createURL() {
		try {
			return new URL(GAEBASEPATH + fileName());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public File download() {
		log.info("start downloading");
		download.download();
		return downloadFile;
	}

	public String fileName() {
		return "appengine-java-sdk-" + version + ".zip";
	}

	@Override
	public void update(Observable o, Object arg) {
		Download download = (Download) o;
		double rant = download.getRant();
		if (download.getRant() - currentProgress > 0.01) {
			if ((int) (rant * 10) - (int) (currentProgress * 10) > 0)
				System.out.println("          " + download.getRantStr());
			System.out.print("*");
			currentProgress = download.getRant();
		}
	}

}
