package com.muchinfo.mtp3common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 属性工具类
 *
 */
public class PropertyUtils extends PropertyPlaceholderConfigurer {

    private static Map<String, String> propertyMap = new HashMap<String, String>();

    public static int serverId;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        propertyMap = new HashMap<>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            propertyMap.put(keyStr, value);
        }
    }

    public static String getValue(String name) {
        String value = propertyMap.get(name);
        if (value == null || value.isEmpty()) {
            return "";
        } else {
            return value;
        }
    }

    public static void setValue(String name, String value) {
        propertyMap.put(name, value);
    }

    private static Map<String, ResourceBundle> configMap = new HashMap<String, ResourceBundle>();

    private static synchronized void loadResource(String propertyFileName) {
        ResourceBundle resource = ResourceBundle.getBundle(propertyFileName);
        configMap.put(propertyFileName, resource);
    }

    public static String getValue(String name, String propertyFileName) {
        ResourceBundle resource = configMap.get(propertyFileName);
        if (resource == null) {
            loadResource(propertyFileName);
            resource = configMap.get(propertyFileName);
        }
        String keyValue = "";
        try {
            // 中文乱码， 改为GBK  -- 改为GBK后部署后为乱码！！！
            keyValue = new String(resource.getString(name).getBytes(), "UTF-8");
//            keyValue = new String(resource.getString(name).getBytes(), "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return keyValue;
    }
}
