package org.diagbot.pub.utils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.commons.lang3.LocaleUtils;

import org.diagbot.pub.Constants;

/**
 * 
 * ClassName: ResourceUtil 
 * Function: 配置文件读取 
 * date: 2015年7月10日 下午3:53:34  
 * 
 * @author 楼辉荣(Fyeman) 
 * @version 1.0 
 * @since JDK 1.7
 */
public class ResourceUtil {
	/**
	 * 缺省文件名称
	 */
	public static final String defaultBundle = "application";
	/**
	 * 
	 * @Title: getBundleName
	 * @Description: 缺省文件名
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @return 
	 * @since JDK 1.7
	 */
	public static String getBundleName() {
		return defaultBundle;
	}
	
	/**
	 * 
	 * @Title: getBundle
	 * @Description: 通过当前所在地域读取，默认zh_CN
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @param bundle
	 * @return 
	 * @since JDK 1.7
	 */
	public static ResourceBundle getBundle(String bundle) {
		return getBundle(bundle, LocaleUtils.toLocale(Constants.DEFAULT_LOCALE));
	}

	/**
	 * 
	 * @Title: getBundle
	 * @Description: 通过当前所在地域读取
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @param bundle
	 * @param locale
	 * @return 
	 * @since JDK 1.7
	 */
	public static ResourceBundle getBundle(String bundle, Locale locale) {
		if (locale == null) {
			locale = LocaleUtils.toLocale(Constants.DEFAULT_LOCALE);
		}
		if (bundle == null) {
			return ResourceBundle.getBundle(getBundleName(), locale);
		} else {
			return ResourceBundle.getBundle(bundle, locale);
		}
	}

	/**
	 * 
	 * @Title: getText
	 * @Description: 查找属性值
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @param key
	 * @return 
	 * @since JDK 1.7
	 */
	public static String getText(String key) {
		return getTextByLocale(key, null, null, null);
	}

	public static String getText(String key, Object arg) {
		return getTextByLocale(key, arg, null, null);
	}

	public static String getText(String key, String bundle) {
		return getTextByLocale(key, null, bundle, null);
	}
	
	public static String getText(String key, Object arg, String bundle) {
		return getTextByLocale(key, arg, bundle, null);
	}

	public static String getTextByLocale(String key, Object arg, String bundle, Locale locale) {
		if (arg == null) {
			return getBundle(bundle, locale).getString(key);
		}
		MessageFormat form = new MessageFormat(getBundle(bundle, locale).getString(key));
		if (arg instanceof String) {
			return form.format(new Object[] { arg });
		} else if (arg instanceof Object[]) {
			return form.format(arg);
		} else {
			return "";
		}
	}
}
