package codesize;

import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.apache.bcel.classfile.*;

public class Codesize
{
  static byte buf[] = new byte[2048];
  static ByteArrayOutputStream bufOutputStream = new ByteArrayOutputStream();

  public static class Item {
    int ttlCodeSize;

    Item(int ttlCodeSize) {
      this.ttlCodeSize = ttlCodeSize;
    }

    public int getCodeSize() { return ttlCodeSize; }
  }

  static int processClassInputStream(InputStream inputStream, String filename)
    throws IOException
  {
    int result = 0;

    ClassParser classParser = new ClassParser(inputStream, filename);
    Method methods[] = classParser.parse().getMethods();
    for(int i=0; i<methods.length; i++) {
      Code code = methods[i].getCode();
      if(code != null)
        result += code.getCode().length;
    }

    return result;
  }

  public static Item processZipFile(File zipFile)
  {
    try {
      ZipInputStream inputStream = new ZipInputStream(
        new BufferedInputStream(new FileInputStream(zipFile))
      );
      try {
        return processZipFile(zipFile, inputStream);
      } finally {
        inputStream.close();
      }
    } catch(IOException e) {
      System.err.println("Ignoring " + zipFile + ": " + e.getMessage());
    }
    return null;
  }

  public static Item processZipFile(File zipFile, ZipInputStream inputStream)
    throws IOException
  {
    int ttlCodeSize = 0;

    ZipEntry zipEntry;
    while((zipEntry = inputStream.getNextEntry()) != null) {
      if(zipEntry.getName().toLowerCase().endsWith(".class")) {
      bufOutputStream.reset();
        int nRead;
        while((nRead = inputStream.read(buf, 0, buf.length)) > -1)
          bufOutputStream.write(buf, 0, nRead);

        ttlCodeSize += processClassInputStream(
          new ByteArrayInputStream(bufOutputStream.toByteArray()),
          zipEntry.getName()
        );
      }
    }

    if(ttlCodeSize == 0)
      throw new IOException("total code size is 0");

    return new Item(ttlCodeSize);
  }
}
