
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Indexer {

    private static String ROOT = "/Users/milnep/Java/Launcher/Index";
    private static String INDEX_FILE = ROOT + ".txt";

    private static void writeFile(File file, byte[] b) {
        try {
            OutputStream w = new BufferedOutputStream(new FileOutputStream(file));
            w.write(b);
            w.close();
        } catch (IOException e) {
            throw new RuntimeException("Oof");
        }
    }

    private static Set packageList(String urlName) throws IOException {
        Set packagelist = new HashSet();
        URL url = new URL(urlName);
        File localFile = Launcher.localLocationOf(url);
        if (!localFile.exists()) {
            Launcher.downloadAndInstallClass(url, localFile);
        }
        ZipFile zf = new ZipFile(localFile);
        Enumeration e = zf.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                continue;
            }
            int lastSlash = name.lastIndexOf('/');
            if (lastSlash == -1) {
                continue;
            }
            name = name.substring(0, lastSlash);
            packagelist.add(name.replace('/', '.'));
        }
        return packagelist;
    }

    public static void register(String url, Collection packages) throws IOException {
        byte[] contents = ("<a href=\"" + url + "\">link</a>").getBytes();
        for (Iterator it = packages.iterator(); it.hasNext();) {
            String packageName = (String) it.next();
            String subdir = packageName.replace('.', '/');
            File f = new File(ROOT + '/' + subdir + ".html");
            f.getParentFile().mkdirs();
            f.createNewFile();
            writeFile(f, contents);
        }
    }

    private static void register(String[] args) throws IOException {
        String urlName = args[0];
        Collection packagelist;
        if (args.length == 1) {
            packagelist = packageList(urlName);
        } else {
            String[] tmp = new String[args.length - 1];
            System.arraycopy(args, 1, tmp, 0, tmp.length);
            packagelist = Arrays.asList(tmp);
        }
        register(urlName, packagelist);
    }

    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            BufferedReader r = new BufferedReader(new FileReader(new File(INDEX_FILE)));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                String[] args1 = line.split("\\s+");
                register(args1);
            }
            r.close();
        } else {
            register(args);
        }
    }

}

