package net.northking.cctp.element.core.scanner;

import net.northking.cctp.element.core.ResourceLoader;
import net.northking.cctp.element.core.filter.DefaultClassFilter;
import net.northking.cctp.element.core.filter.IClassFilter;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * BeanClassLookup
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public class BeanClassLookup {

    private final static IClassFilter filter = new DefaultClassFilter();

    public static Set<Class<?>> find(ResourceLoader resourceLoader, String basePackage) throws Exception {
        Set<Class<?>> beanClasses = new HashSet<>();
        Collection<String> resources = resourceLoader.filterResources(basePackage);
        if (resources == null || resources.size() == 0) {
            throw new Exception("无意义的组件库,未扫描到任何组件类");
        }
        for (String resource : resources) {
            if (resource.endsWith(".class")) {
                String className = StringUtils.replace(resource, "/", ".");
                className = className.substring(0, className.length() - 6);
                Class<?> cls = Class.forName(className, false, resourceLoader.getClassLoader());
                if (filter.accept(cls)) {
                    beanClasses.add(cls);
                }
            }
        }
        return beanClasses;
    }
}
