package de.dhbwstuttgart.environment;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;

import java.util.*;

/**
 * Hilft beim Durchsuchen von Packages
 * Benutzt die Reflections-Library (https://github.com/ronmamo/reflections)
 * Hilfe dazu: http://stackoverflow.com/a/9571146
 */
public class PackageCrawler {

	final DirectoryClassLoader classLoader;
	public PackageCrawler(DirectoryClassLoader classLoader) {
		this.classLoader = classLoader;
	}
	
    public Set<Class<?>> getClassesInPackage(String packageName) {
        var res = new HashSet<Class<?>>();

        try (ScanResult result = new ClassGraph()
            .enableClassInfo()
            .enableSystemJarsAndModules()
            .addClassLoader(classLoader)
            .acceptPackages(packageName)
            .scan()) {

            for (var info : result.getAllClasses()) {
                try {
                    var clazz = Class.forName(info.getName());
                    res.add(clazz);
                } catch (ClassNotFoundException ignored) {}
            }
        };

        return res;
    }

  public Map<String, Integer> getClassNames(String packageName){
      Map<String, Integer> nameList = new HashMap<>();
    Set<Class<?>> classes = getClassesInPackage(packageName);
      if(packageName.equals("java.lang") && ! classes.contains(Object.class)) {
        classes.add(Object.class);
      }
    for(Class c : classes){
      nameList.put(c.getName(), c.getTypeParameters().length);
    }
    return nameList;
  }
}
