/*
 * This file is part of the DistSim distributed simulation framework (wrapper)
 * Copyright (C) 2007 Ulf Hermann
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package brn.distsim.wrapper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Package {

	private String url;

	private String localPath;

	private File outFile;

	public Package(String url, String localPath) {
		this.url = url;
		this.localPath = localPath;
	}

	public void download() throws IOException {
		File dir = new File(localPath);
		dir.mkdirs();
		URL inUrl = new URL(url);
		String fileName = new File(inUrl.getFile()).getName();
		outFile = new File(localPath + "/" + fileName);
		OutputStream out = null; 
		InputStream in = null;
		try {
      out = new FileOutputStream(outFile);
  		in = inUrl.openStream();
  		int read = 0;
  		byte[] data = new byte[1024];
  		while ((read = in.read(data)) > 0)
  			out.write(data, 0, read);
		} finally {
		  if (null != in)
		    in.close();
		  if (null != out)
		    out.close();
		}
	}

	public void unzip() throws IOException {
    System.out.println("unzipping package " + url + " at " + localPath);
    ZipFile zipFile = null;
    FileOutputStream fos = null;
    BufferedOutputStream dest = null;
    BufferedInputStream is = null;

    try {
      zipFile = new ZipFile(outFile, ZipFile.OPEN_READ);
      Enumeration zipFileEntries = zipFile.entries();
      while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        //System.out.println("Extracting: " + entry);

        File destFile = new File(localPath, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
          is = new BufferedInputStream(zipFile.getInputStream(entry));
          int currentByte;
          byte[] data = new byte[1024];
          // write the current file to disk
          fos = new FileOutputStream(destFile);
          dest = new BufferedOutputStream(fos, 1024);

          // read and write until last byte is encountered
          while ((currentByte = is.read(data, 0, 1024)) != -1) {
            dest.write(data, 0, currentByte);
          }
          dest.flush();
          dest.close();
          dest = null;
          fos.close();
          fos = null;
          is.close();
          is = null;
        }
      }
    } finally {
      if (null != zipFile)
        zipFile.close();
      if (null != dest)
        dest.close();
      if (null != is)
        is.close();
      if (null != fos)
        fos.close();
    }
	}

	public void delete() {
		File dir = new File(localPath);
		deleteDir(dir);
	}

	private boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i=0; i<children.length; i++) {
        boolean success = deleteDir(new File(dir, children[i]));
        if (!success) {
          return false;
        }
      }
    }
    // The directory is now empty (or it is a file) so delete it
    return dir.delete();
	}

}
