package com.ssyf.common.core.helper;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 *
 * @author huwei
 * @date 2023/1/28 16:31
 */
public class ResourceHelper {

    /**
     * 类文件后缀
     */
    public static final String CLASS_SUFFIX = ".class";

    /**
     * 加载指定文件
     * @param resourcePathPattern 文件路径
     * @return
     */
    public static Resource[] loadByPathPattern(String resourcePathPattern) throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        String pattern = resourcePathPattern;
        if(!resourcePathPattern.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)){
            pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourcePathPattern;
        }
        return resourcePatternResolver.getResources(pattern);
    }

    /**
     * 加载指定文件
     * @param packageName 包路径，示例：com.ssyf
     * @return
     * @throws IOException
     */
    public static Resource[] loadInPackage(String packageName) throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        String pattern = ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*" + CLASS_SUFFIX;
        if(!pattern.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)){
            pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + pattern;
        }
        return resourcePatternResolver.getResources(pattern);
    }

    /**
     * 加载指定包路径下的类
     * @param packageName 包路径，示例：com.ssyf
     * @return
     * @throws IOException
     */
    public static List<Class<?>> loadClassInPackage(String packageName) throws Exception {
        List<Class< ? >> result = new ArrayList();
        Resource[] resources = loadInPackage(packageName);
        for (Resource resource : resources) {
            String tempPath =  resource.getURL().getPath().replace("/",".").replace(CLASS_SUFFIX ,"");
            String classPackageName = tempPath.substring(tempPath.indexOf(packageName));
            result.add(Class.forName(classPackageName));
        }
        return result;
    }
}
