/**
 *############################################################################
 * A component of the Greenstone Librarian Interface, part of the Greenstone
 * digital library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Author: David Bainbridge, NZDL Project, University of Waikato, NZ
 *
 * Copyright (C) 2005 New Zealand Digital Library Project
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *############################################################################
 */

package org.greenstone.gatherer.util;


import java.io.*;
import java.util.*;
import java.util.zip.*;


public class UnzipTools
{
    static public void unzipFile(String zip_file_path, String base_directory_path)
    {
	try {
	    ZipFile zip_file = new ZipFile(new File(zip_file_path), ZipFile.OPEN_READ);
	    
	    Enumeration e = zip_file.entries(); 
	    while (e.hasMoreElements()) {
		ZipEntry zip_entry = (ZipEntry) e.nextElement();
		File zip_entry_file = new File(base_directory_path + zip_entry.getName());
		// System.err.println("    Unzipping: " + zip_entry_file.getAbsolutePath());

		// Directory case
		if (zip_entry.isDirectory()) {
		    // Create named directory, if it doesn't already exist
		    if (!zip_entry_file.exists() && !zip_entry_file.mkdirs()) {
			System.err.println("Error: unable to create directory " + zip_entry_file);
		    }
		}

		// File case
		else {
		    // Write out file to disk

		    // Make sure its parent directory exists.
		    File dir = new File(zip_entry_file.getParent());
		    dir.mkdirs();

		    // Set up input stream
		    InputStream zis = zip_file.getInputStream(zip_entry); 
		    BufferedInputStream bzis = new BufferedInputStream(zis); 
		    DataInputStream dbzis = new DataInputStream(bzis);

		    // Set up output stream
		    FileOutputStream fzos = new FileOutputStream(zip_entry_file);
		    BufferedOutputStream bfzos = new BufferedOutputStream(fzos);

		    byte[] buf = new byte[1024];
		    int len;
		    while ((len = dbzis.read(buf)) >= 0) {
			bfzos.write(buf,0,len);
		    }

		    dbzis.close();
		    bzis.close();
		    zis.close();

		    bfzos.close();
		    fzos.close();
		}
	    }

	    zip_file.close();
	} 
	catch (Exception exception) {
	    exception.printStackTrace();
	}
    }
}
