package pregozip;

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

/*******************************************************************************
 * <p>Class ZipWriter</p>
 * <p>Copyright: Copyright (c) 2002</p>
 * @author Markus Wilthaner
 * @version 1.0
 * <p>An extension to File, this class offers functions for adding files to
 * a zip archive.</p>
 *******************************************************************************
 */

public class ZipWriter extends File {
  private ZipOutputStream zOut;
  private boolean init = false;
  private int fileCount = 0;

 /*****************************************************************************
  * <p>Constructor</p>
  * <p>Creates the archive filename. Throws an exception, if the archive
  * already exists.</p>
  *****************************************************************************/
  public ZipWriter(String filename) throws Exception {
    super(filename);

    // If source archive already exists
    if(this.exists()) {
      throw new Exception("Target archive already exists");
    }

    // Open the ZipOutputStream
    zOut = new ZipOutputStream( new FileOutputStream (this) );
    zOut.setMethod(zOut.DEFLATED);
    zOut.setLevel(5);
  }

/*****************************************************************************
  * addFile
  * <p>Writes a File (fIn) with the relative path (relativePath) into the
  * archive.</p>
  *****************************************************************************/
  public void addFile(File fIn, String relativePath) throws Exception {
    FileInputStream tFINS = new FileInputStream(fIn);
    final int bufLength = 1024;
    byte[] buffer = new byte[bufLength];
    int readReturn = 0;

    // Set next Entry
    zOut.putNextEntry(new ZipEntry(relativePath));

    do {
      readReturn = tFINS.read(buffer);
      if(readReturn != -1) { zOut.write(buffer, 0, readReturn); }
    } while(readReturn != -1);

    zOut.closeEntry();
    fileCount++;
  }

  public int getFileCount() {
    return fileCount;
  }

 /*****************************************************************************
  * <p>closeArchive</p>
  * <p>Closes the archive if it is still open.
  *****************************************************************************/
  public void closeArchive() throws Exception {
    if(zOut != null) {
      zOut.finish();
      zOut.close();
    }
  }

 /*****************************************************************************
  * <p>Deconstructor</p>
  * <p>If the user forgot to close the archive, the deconstructor will close
  * it.</p>
  *****************************************************************************/
  public void finalize() throws Exception {
    if(zOut != null) {
      zOut.finish();
      zOut.close();
    }
  }
}
