package com.njcn.csharmonic.utils;

import org.influxdb.annotation.Measurement;

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

/**
 * Description:
 * Date: 2023/6/2  15:08【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
public class CsReflectUitl {


    /*
    * 获取po报下，所有有@Measurement注解的实体类;
    */
    public static HashMap<String,Class<?>> getEntityClassesByAnnotation() {
        HashMap<String,Class<?>> result = new HashMap<>();
        List<Class<?>> classes = CsReflectUitl.getClasses("com.njcn.harmonic.pojo.influx");
        for (Class<?> clazz : classes) {
            if (clazz.isAnnotationPresent(Measurement.class)) {
                Measurement annotation = (Measurement) clazz.getAnnotation(Measurement.class);
                result.put(annotation.name(),clazz) ;
            }
        }
        return result;
    }

    public static List<Class<?>> getClasses(String packageName) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        try {
            String path = packageName.replace(".", "/");
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(path);
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                if (resource.getProtocol().equals("file")) {
                    String filePath = URLDecoder.decode(resource.getFile(), "UTF-8");
                    findClassesInPackage(packageName, filePath, classes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classes;
    }

    private static void findClassesInPackage(String packageName, String packagePath, List<Class<?>> classes) {
        File packageDir = new File(packagePath);
        if (!packageDir.exists() || !packageDir.isDirectory()) {
            return;
        }
        File[] files = packageDir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                findClassesInPackage(packageName + "." + file.getName(), file.getAbsolutePath(), classes);
            } else if (file.getName().endsWith(".class")) {
                String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6);
                try {
                    Class<?> clazz = Class.forName(className);
                    classes.add(clazz);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }




}
