package ee.ut.math.tvt2008.salessystem.util;

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

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

/**
 * Translations class to provide multilingual interface.
 */
public class Translations {

	public static final Object language[] = { "ee", "en" };
	public static final Object valik = JOptionPane.showInputDialog(null,
			" ee-eesti\n en-english", "Vali keel/select language",
			JOptionPane.INFORMATION_MESSAGE, null, language, language[0]);
	public static final String keel = valik.toString();
	public static final String LANGUAGE = new String(keel);
	public static final String COUNTRY = new String("ET");

	private static Locale currentLocale = new Locale(Translations.LANGUAGE,
			Translations.COUNTRY);
	private static ResourceBundle messages = ResourceBundle.getBundle(
			"Messages", Translations.currentLocale);

	private static final Logger logger = Logger.getLogger(Translations.class);

	public static void setCurrentLocale(Locale currentLocale) {
		Translations.currentLocale = currentLocale;
	}

	/**
	 * Gets a localized string for the given key.
	 * 
	 * @param key
	 *            the key for the desired string
	 * @return string for the given key
	 */
	public static String getString(String key) {
		String rtrn = null;
		try {
			rtrn = messages.getString(key);
		} catch (MissingResourceException e) {
			rtrn = key;
			logger.warn("missing translation for key \"" + key + "\"");
		}
		return rtrn;
	}

	/**
	 * Gets a localized string for the given key and use it to format given
	 * arguments.
	 * 
	 * @param key
	 *            the key for the desired pattern string
	 * @param params
	 *            objects to be formatted and substituted
	 * @return formatted string for the given key
	 * 
	 * @see MessageFormat#format(java.lang.String, java.lang.Object[])
	 */
	public static String getString(String key, Object... params) {
		return MessageFormat.format(getString(key), params);
	}

	public static void setBundle(ResourceBundle bundle) {
		Translations.messages = bundle;
	}

}
