/*
 * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved.
 * See LICENSE in the project root directory.
 */
package edu.jhu.hlt.acute.archivers.zip;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import edu.jhu.hlt.acute.archivers.Archivable;
import edu.jhu.hlt.acute.archivers.Archiver;

/**
 * 
 */
public class ZipArchiver implements Archiver {

  private final ZipArchiveOutputStream zout;
  
  /**
   * Wrap an {@link Path} that represents a 
   * <code>.zip</code> file. This constructor be used when writing to files on disk.
   * 
   * @throws IOException 
   */
  public ZipArchiver(Path path) throws IOException {
    this.zout = new ZipArchiveOutputStream(path.toFile());
  }
  
  /**
   * Wrap an {@link OutputStream}. 
   * <br/>
   * <br/>
   * Do not use this constructor if the {@link OutputStream} is writing to a file. 
   * Use {@link #ZipArchiver(Path)} instead. 
   * 
   * @param out an {@link OutputStream}
   * @see #ZipArchiver(Path)
   */
  public ZipArchiver(OutputStream out) {
    this.zout = new ZipArchiveOutputStream(out);
  }
  
  /*
   * (non-Javadoc)
   * @see edu.jhu.hlt.acute.archivers.Archiver#close()
   */
  @Override
  public void close() throws IOException {
    this.zout.close();
  }

  /* (non-Javadoc)
   * @see edu.jhu.hlt.acute.archivers.Archiver#addEntry(edu.jhu.hlt.acute.archivers.Archivable)
   */
  @Override
  public void addEntry(Archivable arch) throws IOException {
    final String fn = arch.getFileName();
    ZipArchiveEntry entry = new ZipArchiveEntry(fn);
    byte[] cbytes = arch.getBytes();
    entry.setSize(cbytes.length);
    this.zout.putArchiveEntry(entry);
    try (ByteArrayInputStream bis = new ByteArrayInputStream(cbytes)) {
      IOUtils.copy(bis, zout);
      this.zout.closeArchiveEntry();
    }
  }
}

@@ -576,18 +576,17 @@
 %0A%0A/**%0A *
- 
 %0A
+
  */%0Apubl
@@ -674,19 +674,17 @@
 m zout;%0A
-  
 %0A
+
   /**%0A  
@@ -724,17 +724,16 @@
 esents a
- 
 %0A   * %3Cc
@@ -810,25 +810,41 @@
 n disk.%0A   *
- 
+%0A   * @param path
 %0A   * @throw
@@ -857,16 +857,27 @@
 ception 
+on IO error
 %0A   */%0A 
@@ -987,27 +987,25 @@
 ile());%0A  %7D%0A
-  
 %0A
+
   /**%0A   * W
@@ -1032,17 +1032,16 @@
 Stream%7D.
- 
 %0A   * %3Cb
@@ -1037,25 +1037,24 @@
 m%7D.%0A   * %3Cbr
-/
 %3E%0A   * %3Cbr/%3E
@@ -1051,17 +1051,16 @@
    * %3Cbr
-/
 %3E%0A   * D
@@ -1135,17 +1135,16 @@
  a file.
- 
 %0A   * Us
@@ -1180,23 +1180,21 @@
 instead.
- 
 %0A   *
- 
 %0A   * @p
@@ -1355,18 +1355,16 @@
 t);%0A  %7D%0A
-  
 %0A  /*%0A  

Fix up some jdoc errors.