package com.palmnest.application.core.util;

import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;

public class PhoneConfig {

	static ResourceBundle resourceObj = null;

	public static String chinannr_config = "phone_config.properties";

	/**
	 * 辅助手 appid
	 */
	public static String APPID = "";

	/**
	 * 辅助手唯一key appkey
	 */
	public static String APPKEY = "";

	/**
	 * 辅助手版本号 VERSION_PHONE
	 */
	public static String VERSION_PHONE = "";

	/**
	 * 辅助手请求地址 VERSION_PHONE
	 */
	public static String PHONEURL = "";

	//测试请加上 test 如 真实环境为：APPID   测试环境为： APPID_TEST
	static {
		try {
			resourceObj = getResourceObj(chinannr_config);
			String currentEnv = GetResValue("phone_config", "current_env");
			String envPrefix = "_test";
			if (StringUtils.isNotEmpty(currentEnv) && currentEnv.equals("prod")) {
				envPrefix = "";
			}
			APPID = resourceObj.getString("appid" + envPrefix);
			APPKEY = resourceObj.getString("appkey" + envPrefix);
			VERSION_PHONE = resourceObj.getString("version_phone");
			PHONEURL = resourceObj.getString("phoneurl" + envPrefix);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据资源文件名返回一个资源文件对象
	 *
	 * @param properties_fileName 资源文件文件名
	 * @throws Exception
	 * @return 返回 ResourceBundle(资源文件对象)
	 */
	public static ResourceBundle getResourceObj(String properties_fileName) throws Exception {
		if (null == properties_fileName || "".equals(properties_fileName)) throw new Exception("请传入一个有效的资源文件名!");
		String ext = properties_fileName.substring(properties_fileName.lastIndexOf(".") + 1);
		String prefix = properties_fileName.substring(0, properties_fileName.lastIndexOf("."));
		if (!ext.toLowerCase().equals("properties")) throw new Exception("您传入的文件名,不是一个有效的资源文件!");

		ResourceBundle resourseObj = null;
		try {
			resourseObj = ResourceBundle.getBundle(prefix);  //只需通过文件名前缀来读取资源文件即可
		} catch (Exception e) {
			System.out.println("查找文件错误:找不到\"" + properties_fileName + "\",请确定您的\"" + properties_fileName + "\"是否放在src目录下!");
			throw e;
		}
		return resourseObj;
	}

	/**
	 * 根据资源文件和资源文件定义的键获取对应的值
	 *
	 * @param properties_fileName_prefix 资源文件名,如果此参数为null 或 "" 则默认为 hh.com.resource.resource.properties
	 * @param resourceKey                用来查找资源文件对应值的键的名字
	 * @return
	 * @throws Exception
	 */
	public static String GetResValue(String properties_fileName_prefix, String resourceKey) {
		String properties_fileName = ((properties_fileName_prefix == null || "".equals(properties_fileName_prefix)) ? "resource" : properties_fileName_prefix) + ".properties";
		ResourceBundle rb = null;
		try {
			rb = getResourceObj(properties_fileName);
			String key_value = rb.getString(resourceKey);
			if (null == key_value || "".equals(key_value))
				throw new Exception("根据您所提供的键:" + resourceKey + ",无法从" + properties_fileName + "文件中找到对应的值,请检查是否添加了此键!");
			return key_value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
