package com.lakala.zf.laop.java.sdk.demo;

import com.lkl.laop.sdk.utils.JsonUtils;

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

/**
 * @author nxj
 * @date 2024/5/17 10:20
 * @description 用于测试demo中接口是否均能正常响应
 */
public class AutoTest {
    public static void main(String[] args) throws Exception {
        String packageName = "com.lakala.zf.laop.java.sdk.demo.v2";
        List<Class<?>> classes = getClasses(packageName);

        String packageName2 = "com.lakala.zf.laop.java.sdk.demo.v3";
        classes.addAll(getClasses(packageName2));

        List<Class<?>> errorClasses = new ArrayList<>();
        for (Class<?> clazz : classes) {
            if (hasMainMethod(clazz)) {
                Method mainMethod = clazz.getDeclaredMethod("main", String[].class);
                try {
                    mainMethod.invoke(null, (Object) new String[0]);
                } catch (Exception e) {
                    errorClasses.add(clazz);
                }

            }
        }
        System.out.println("========接口demo执行完成=======");
        System.out.printf("========失败信息:%s=======%n", JsonUtils.toJSONString(errorClasses));


    }

    private static boolean hasMainMethod(Class<?> clazz) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getName().equals("main")) {
                return true;
            }
        }
        return false;
    }

    private static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class<?>> classes = new ArrayList<>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes;
    }

    private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}
