package me.km;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class PackageHelper {
    public static ArrayList<Class> getClasses(String packageName) {
        URL jar = getPath();
        if(jar != null) {
            try {
                ZipInputStream zip = new ZipInputStream(jar.openStream());
                ArrayList<Class> classes = new ArrayList<>();
                String path = packageName.replace(".", "/");
                while(true) {
                    ZipEntry e = zip.getNextEntry();
                    if(e == null) {
                        break;
                    }
                    String name = e.getName();
                    if(name.startsWith(path)) {
                        name = name.replace("/", ".").substring(0, e.getName().length() - 6);
                        try {
                            classes.add(Class.forName(name));
                        } catch(ClassNotFoundException ex) {
                        }
                    }
                }
                return classes;
            } catch(IOException ex) {
            }
        }
        return new ArrayList<>();
    }

    private static URL getPath() {
        try {
            String s;
            try {
                s = KajetansMod.class.getProtectionDomain().getCodeSource().getLocation().getPath();
                s = s.substring(5, s.length() - 25);
            } catch(Exception ex) {
                s = "../build/libs/km-1.0.jar";
            }

            File f = new File(s);
            if(!f.exists()) {
                for(int i = 0; i < 20; i++) {
                    System.out.println(f + " does not exist");
                }
            }

            return new URL("file:" + s);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
