/*******************************************************************************
 * Copyright (c) 2005 IBM Corporation
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial implementation
 *******************************************************************************/

package org.eclipse.ercp.eswt.sample;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;

/**
 * This class retrieves strings from a resource bundle,
 * formatting them with MessageFormat when required.
 * <p>
 * Note that if the appropriate resource file is not available,
 * or an invalid key is looked up, or resource bundle support
 * is not available, the key itself will be returned as the
 * associated message. This means that the <em>KEY</em> should
 * a reasonable human-readable (english) string.
 */

public class Msg
{
	// ResourceBundle holding the nls messages.
	private static ResourceBundle bundle=null;

	// Attempt to load the message bundle.
	public Msg() {
	}
	
	/**
	 * Retrieves a message which has no arguments.
	 *
	 * @param		msg String
	 *				the key to look up.
	 * @return		String
	 *				the message for that key in the system
	 *				message bundle.
	 */
	public static String getString (String msg)
	{
		if (bundle == null)
		{
			setLocale(Locale.getDefault());
		}		
		try
		{
			if(bundle == null){
				return msg;
			}else{
				return bundle.getString(msg);
			}
		}
		catch (MissingResourceException e)
		{
			return msg;
		}
	}
	
	/**
	 * Changes the locale of the messages.
	 *
	 * @param		locale Locale
	 *				the locale to change to.
	 */
	static public void setLocale (final Locale locale)
	{
		try
		{
			bundle = (ResourceBundle)AccessController.doPrivileged(new PrivilegedAction()
			{
				public Object run()
				{
					return ResourceBundle.getBundle("org.eclipse.ercp.eswt.sample.nls.ExternalMessages", locale); //$NON-NLS-1$
				}
			});
		}
		catch (MissingResourceException e)
		{
			bundle = null;
		}
	}
}