package com.armundia.core.websocket.annotation;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


public class PackageUtil {
	private PackageUtil() {
		
	}

    public static List<Class<?>> getClasses(String packageName) {
        List<Class<?>> classes = new ArrayList<>();
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                String classPath = resource.getFile();
                File directory = new File(classPath);
                addClasses(packageName, classes, directory);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classes;
    }
    
    private static void addClasses(String packageName, List<Class<?>> classes, File directory) {
        if (directory.isDirectory()) {
            for (File file : directory.listFiles()) {
                if (file.getName().endsWith(".class")) {
                    String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                    Class<?> clazz;
					try {
						clazz = Class.forName(className);
						classes.add(clazz);
					} catch (ClassNotFoundException | NoClassDefFoundError e) {}
                } else if (file.isDirectory()) {
					addClasses(packageName + '.' + file.getName(), classes, file);
				}
            }
        }
    }
}