package com.infoepoch.pms.dispatchassistant.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 读取properties文件属性工具类
 *
 * @author liudx
 */
public class PropertiesUtils {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);

    /**
     * 基础配置文件
     */
    private static final Properties BASE_PROPS = new Properties();
    /**
     * 活动配置文件，如demo、dev、prod
     */
    private static final Properties ACTIVITY_PROPS = new Properties();

    static {
        // 读取基础配置文件
        InputStream baseIns = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.yml");
        InputStream activityIns = null;
        try {
            // 加载基础配置文件
            BASE_PROPS.load(baseIns);
            // 读取活动配置文件
            activityIns = PropertiesUtils.class.getClassLoader().getResourceAsStream(
                    "application-" + BASE_PROPS.getProperty("spring.profiles.active") + ".yml");
            // 加载活动配置文件
            ACTIVITY_PROPS.load(activityIns);
        } catch (Exception ex) {
            logger.info("加载配置文件失败！！！", ex);
        } finally {
            if (baseIns != null) {
                try {
                    baseIns.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (activityIns != null) {
                try {
                    activityIns.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private PropertiesUtils() {
        // private constructor
    }

    /**
     * 根据key读取properties文件属性值
     */
    public static String getValue(String key) {
        try {
            if (StringUtils.isNotBlank(ACTIVITY_PROPS.getProperty(key))) {
                return ACTIVITY_PROPS.getProperty(key);
            }
            return BASE_PROPS.getProperty(key, "");
        } catch (Exception ex) {
            logger.error("读取属性【{}】失败", key, ex);
            return null;
        }
    }


}
