package de.dass_it.vanhelsing.gui;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
/**
 * Class containing the methods used to access the messages property bundle
 * @author tgoecke
 *
 */
public class PropertyBundle{
	
	private static ResourceBundle properties;
	private static final String path = "de.dass_it.vanhelsing.gui.messages";
	/**
	 * reads the messages property file
	 */
	private static void initialize(){
		Locale l = FacesContext.getCurrentInstance().getViewRoot().getLocale();
		
		if (l == null){
			l = Locale.ENGLISH;
		}
		properties = ResourceBundle.getBundle(path, l);
	}
	/**
	 * method returns a single value of a given key
	 * @param key	key of 
	 * @return	value of the property identified by key. If an exception is thrown, null will be returned
	 */
	public static String getProperty(String key){
		try{
			if (properties == null){
				initialize();
			}
			key = key.toLowerCase();
			return properties.getString(key);
		} catch (Exception e) {
			System.err.println(key+" / "+e.toString());
		}
		return null;
	}
	/**
	 * method to retrieve properties with a partial key. a partial key is the first n characters of a key
	 * 
	 * @param partialKey	first n characters of a property key
	 * @return	an array of values whose keys started with partialKey. an empty array is returned if no matchings have been found 
	 */
	public static String[] getTypeProperties(String partialKey){
		Enumeration<String> keySet = properties.getKeys();
		String key;
		int i = 0;
		ArrayList<String> result = new ArrayList<String>();
		
		while(keySet.hasMoreElements()){
			key = keySet.nextElement();
			if (key.startsWith(partialKey)){
					result.add(getProperty(key));
			}
		}
		result.trimToSize();
		if (result.size()>0) return (String[]) result.toArray();
		return result.toArray(new String[0]);
	}
	public static ArrayList<String> getTypeAttributes(String partialKey){
		Enumeration<String> keySet = properties.getKeys();
		String key;
		ArrayList<String> result = new ArrayList<String>();
		String [] keyComponents;
		while(keySet.hasMoreElements()){
			key = keySet.nextElement();
			if (key.startsWith(partialKey)){
				if (key.contains("type")){
					keyComponents = key.split("\\.");
					result.add(keyComponents[2]);
				}
			}
		}
		result.trimToSize();
		return result;
	}
}

