/*
 * $Id: Property.java,v 1.5 2008/04/09 10:26:06 nishi Exp $
 */
package galatea.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;

public class Property 
{
	public static boolean getAsBoolean(String name, boolean defval) {
		String s = System.getProperty(name, null);
		if ( s == null ) 
			return defval;
		return (Integer.parseInt(s) != 0);
	}

	public static double getAsDouble(String name, double defval) {
		String s = System.getProperty(name, null);
		if ( s == null ) 
			return defval;
		return Double.parseDouble(s);
	}

	public static int getAsInt(String name, int defval)
	{
		String s = System.getProperty(name, null);
		if ( s == null ) 
			return defval;
		return Integer.parseInt(s);
	}

	public static String getAsStr(String name, String defval)
	{
		String s = System.getProperty(name, null);
		if ( s == null ) 
			return defval;
		return s;
	}

	@SuppressWarnings("unchecked")
	public static String getConfigStrings() {
//		String config = "";
//		for (Enumeration<Object> en = System.getProperties().keys(); en.hasMoreElements(); ) {
//			String key = (String)(en.nextElement());
//			String val = System.getProperty(key);
//			// System.err.printf("%s=%s\n", key, val);
//			config += key + "=" + val + "\n";
//		}
//		return config;
		ArrayList<String> al = new ArrayList<String>();
		for (Enumeration<Object> en = System.getProperties().keys(); en.hasMoreElements(); ) {
			String key = (String)(en.nextElement());
			String val = System.getProperty(key);
			// config += key + "=" + val + "\n";
			String s = key + "=" + val + "\n";
			al.add(s);
		}
		Object[] oa = al.toArray();
		Arrays.sort(oa, new java.util.Comparator(){
			@Override
			public int compare(final Object arg0, final Object arg1) {
				return ((String)arg0).compareTo((String)arg1);
			}});
		String config = "";
		for (int i=0; i < oa.length; i++) {
			config += oa[i];
		}
		return config;
	}

	/**
	 * introduced to avoid "if Util.isWindows() / else" 
	 * @param name
	 * @param defval
	 * @return
	 */
	public static String getForPlatformAsStr(String name, String defval)
	{
		if (Util.isWindows()) {
			return Property.getAsStr( name + ".Windows", defval );
		}
		return Property.getAsStr(name, defval);
	}

	public static boolean getForPlatformAsBoolean(String name, boolean defval) {
		if (Util.isWindows()) {
			return Property.getAsBoolean( name + ".Windows", defval );
		}
		return Property.getAsBoolean(name, defval);
	}

	public static int getForPlatformAsInt(String name, int defval) {
		if (Util.isWindows()) {
			return Property.getAsInt( name + ".Windows", defval );
		}
		return Property.getAsInt(name, defval);
	}

}
