package de.ivu.elect.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicLong;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class CountingZipInputStream extends ZipInputStream {

  private final AtomicLong byteCount = new AtomicLong(0L);

  private final AtomicLong fileCount = new AtomicLong(0L);

  public CountingZipInputStream(InputStream in) {
    super(in);
  }

  public CountingZipInputStream(InputStream in, Charset charset) {
    super(in, charset);
  }

  @Override
  public ZipEntry getNextEntry() throws IOException {
    ZipEntry nextEntry = super.getNextEntry();
    if (nextEntry == null) {
      return null;
    }
    fileCount.incrementAndGet();
    return nextEntry;
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    int read = super.read(b, off, len);
    addBytes(read);
    return read;

  }

  @Override
  public long skip(long n) throws IOException {
    long skip = super.skip(n);
    addBytes(skip);
    return skip;
  }

  @Override
  public int read() throws IOException {
    int read = super.read();
    if (read > -1) {
      addBytes(1);
    }
    return read;
  }

  @Override
  public int read(byte[] b) throws IOException {
    int read = super.read(b);
    addBytes(read);
    return read;
  }

  private void addBytes(long read) {
    if (read > 0) {
      byteCount.addAndGet(read);
    }
  }

  public long getByteCount() {
    return byteCount.get();
  }

  public long getFileCount() {
    return fileCount.get();
  }
}
