package com.persagy.dmp.common.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

public class ResourceUtil {

    /**jar同级config目录前缀*/
    private static final String FILE_CONFIG_PATH="file:./config/{}";
    /**Classpath路径前缀*/
    private static final String FILE_CLASSPATH_PATH="classpath:./{}";

    /***
     * @Description: 校验资源文件是否存在
     * @param subConfigFilePath : jar包同级目录下的配置文件
     * @return : com.alibaba.fastjson.JSONArray
     * @author: lijie
     * @Date:2020/6/6 19:43
     * Update By lijie 2020/6/6 19:43
     */
    public static boolean checkResoucesExist(String subConfigFilePath) throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        return checkResoucesExist(resolver.getResources(StrUtil.format(FILE_CONFIG_PATH,subConfigFilePath)));
    }
    /***
     * @Description: 校验资源文件是否存在
     * @return : com.alibaba.fastjson.JSONArray
     * @author: lijie
     * @Date:2020/6/6 19:43
     * Update By lijie 2020/6/6 19:43
     */
    public static boolean checkResoucesExist(Resource[] resolverResources) throws IOException {
        if (resolverResources.length <= 0) {
            return false;
        }
        boolean exist = true;
        for (Resource resource : resolverResources) {
            if (!resource.exists()) {
                exist = false;
                break;
            }
        }
        return exist;
    }

    /***
     * Description: 获取资源文件方法
     * @param subConfigFilePath : 配置文件路径
     * @param subClasspathFilePath : classpath下的文件
     * @return : org.springframework.core.io.Resource[]
     * @author : lijie
     * @date :2021/3/1 14:25
     * Update By lijie 2021/3/1 14:25
     */
    public static Resource[] getResource(String subConfigFilePath, String subClasspathFilePath)
            throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resolverResources = resolver.getResources(StrUtil.format(FILE_CONFIG_PATH,subConfigFilePath));
        if (checkResoucesExist(resolverResources)){
            return resolverResources;
        }
        Resource[] classPathResources = resolver.getResources(StrUtil.format(FILE_CLASSPATH_PATH, subClasspathFilePath));
        if (!checkResoucesExist(classPathResources)){
            return new Resource[0];
        }
        return classPathResources;
    }

}
