package cn.reghao.bnt.agent.config;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author reghao
 * @date 2021-03-03 18:47:01
 */
@Slf4j
public class ConfigFile {
    public static String configFilePath(String arg, Class<?> clazz) {
        String configFilePath = null;
        File configFile = new File(arg);
        if (!configFile.exists()) {
            if (arg.startsWith("./")) {
                String filename = arg.replace(".", "")
                        .replace("/", "");
                configFilePath = runningHome(clazz) + "/" + filename;
            } else if (!arg.contains("/")) {
                configFilePath = runningHome(clazz) + "/" + arg;
            } else {
                log.error("相对路径的配置文件必须以 ./configFile 或 configFile 形式指定...");
            }
        } else {
            // 绝对路径
            configFilePath = arg;
        }
        return configFilePath;
    }
    
    /**
     * jar 文件运行目录
     *
     * @param
     * @return
     * @date 2021-03-03 下午6:33
     */
    public static String runningHome(Class<?> clazz) {
        URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
        String jarFilePath = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8);
        if (jarFilePath.endsWith(".jar")) {
            jarFilePath = jarFilePath.substring(0, jarFilePath.lastIndexOf("/") + 1);
        }

        File file = new File(jarFilePath);
        return file.getAbsolutePath();
    }
}
