package cn.reghao.tnb.sb.util;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author reghao
 * @date 2020-04-08 23:05:38
 */
public class RuntimeClass {
    private final String projRoot = this.getClass().getResource("/").getPath();

    public List<Class> classesInPackage(String pkg) {
        List<String> list = scanPackage(pkg);
        List<Class> classes = new ArrayList<>();
        for (String str : list) {
            try {
                Class clazz = Class.forName(str);
                classes.add(clazz);
            } catch (ClassNotFoundException ignore) {
            }
        }

        return classes;
    }

    private List<String> scanPackage(String pkg) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String pkgPath = pkg.replace(".", "/");
        List<String> classes = new ArrayList<>();
        URL url = classLoader.getResource(pkgPath);
        assert url != null;
        String type = url.getProtocol();
        if ("file".equals(type)) {
            getClassNameFromFile(url.getPath(), classes, false);
        } else if ("jar".equals(type)) {
        }

        return classes;
    }

    private void getClassNameFromFile(String path, List<String> classes, boolean recursiveChild) {
        File file = new File(path);
        for (File file1 : Objects.requireNonNull(file.listFiles())) {
            if (file1.isDirectory() && recursiveChild) {
                getClassNameFromFile(file1.getPath(), classes, recursiveChild);
            } else {
                String filepath = file1.getPath();
                // 引用其他包时，projRoot 的路径不正确
                //String clazz = filepath.replace(this.projRoot, "").replace("/", ".");
                String clazz = filepath.split("/target/classes/")[1].replace("/", ".");
                if (clazz.endsWith(".class")) {
                    classes.add(clazz.replace(".class", ""));
                } else {
                    classes.add(clazz);
                }
            }
        }
    }

    /**
     * TODO 获取 jar 包中的类
     *
     * @param
     * @return
     * @date 2020-04-08 下午11:09
     */
    private List<String> getClassNameFromJar() {
        return null;
    }
}
