package isrp.utils;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * Java Class Utils Provide a public static method which returns a message of a
 * message resource key.
 */
public class MessageUtil {
	

	protected static ClassLoader getCurrentClassLoader(Object defaultObject) {

		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		if (loader == null) {
			loader = defaultObject.getClass().getClassLoader();
		}

		return loader;
	}

	/**
	 * get message from bundle by 'key'
	 * @param key 
	 * @param context
	 * @return
	 */
	public static String getMessageStringFromBundle(String key,FacesContext context) {
		
		String text = null;
		Object params[]=null;
		ResourceBundle bundle = ResourceBundle.getBundle(context.getApplication().getMessageBundle(), context.getViewRoot().getLocale(),
				getCurrentClassLoader(params));				

		try {
			text = bundle.getString(key);
		} catch (MissingResourceException e) {
			text = "?? key " + key + " not found ??";
		}

		if (params != null) {
			MessageFormat mf = new MessageFormat(text, context.getViewRoot().getLocale());
			text = mf.format(params, new StringBuffer(), null).toString();
		}

		return text;
	}
	
	/**
	 * add message to faces contex
	 * @param faces
	 * @param msgKey
	 */
	public static void addMessageToContext(FacesContext faces, String msgKey){
		String msgString = MessageUtil.getMessageStringFromBundle(msgKey, faces);
		FacesMessage message = new FacesMessage(msgString);
		faces.addMessage(null, message);
	}
	/**
	 * add message to faces contex
	 * @param faces
	 * @param msgKey
	 */
	public static void addMessageToContext(FacesContext faces, String msgKey,String extraMessage){
		String msgString = MessageUtil.getMessageStringFromBundle(msgKey, faces);
		FacesMessage message = new FacesMessage(msgString+extraMessage);
		faces.addMessage(null, message);
	}
}
