import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;


public class Analyzer {

    // TODO add data structure to keep statistics

    public static void main(final String[] args) throws IOException {
        final String jarFileName = args[0];
        System.out.println("Analyzing "+jarFileName);
        final JarFile jar = new JarFile(jarFileName);
        analyzeJar(jar);
        // TODO output statistics
    }

    private static void analyzeJar(final JarFile jar) throws IOException {
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            analyzeJarEntry(entry, jar);
        }
    }

    private static void analyzeJarEntry(final JarEntry entry, final JarFile jar) throws IOException {
        if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
            System.out.println(" File "+entry.getName());
            final InputStream is = jar.getInputStream(entry);
            final ClassReader classReader = new ClassReader(is);
            final ClassNode classNode = new ClassNode();
            classReader.accept(classNode, ClassReader.SKIP_FRAMES);
            analyzeClass(classNode);
        }
    }

    private static void analyzeClass(final ClassNode classNode) {
        System.out.println("  Class "+classNode.name);
        final List<MethodNode> methods = classNode.methods;
        for (final MethodNode methodNode : methods) {
            analyzeMethod(methodNode);
        }

    }

    private static void analyzeMethod(final MethodNode methodNode) {
        System.out.println("    Method "+methodNode.name+methodNode.desc);
        // TODO implement required analysis
    }

    // TODO possibly add extra methods (adding classes is fine, too)

}
