package xyz.wbsite.frame.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 配置属性获取工具
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2020-11-10
 */
public class PropertiesUtil {

    /**
     * 属性集合缓存
     */
    private static Map<String, Properties> propertiesMap = new HashMap<>();

    /**
     * @param name         属性文件名称
     * @param key          属性关键字
     * @param defaultValue 当取不到值时的默认值
     * @return
     */
    public static String getProp(String name, String key, String defaultValue) {
        Properties properties = propertiesMap.get(name);
        if (properties == null) {
            try {
                properties = new Properties();
                properties.load(ResourceUtil.getInput(name));
                propertiesMap.put(name, properties);
            } catch (IOException ignored) {

            }
        }
        if (properties == null) {
            return "";
        }
        return properties.getProperty(key, defaultValue);
    }

    public static String getProp(String name, String key) {
        return getProp(name, key);
    }

    public static int getPropInt(String name, String key, int defaultValue) {
        String prop = getProp(name, key, String.valueOf(defaultValue));
        // 这边对值不做容错处理，预防因为容错出现难以查找的BUG
        return Integer.parseInt(prop);
    }
}