package brn.swans;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Strings {
	public static String toString(Object o, String indent, String fieldDelim) {
		if (null == o)
			return "null";
		
		Field[] fields1 = o.getClass().getDeclaredFields();
		Field[] fields2 = o.getClass().getFields();
		List fields = new ArrayList();
		for (int i=0; i<fields1.length; i++)
			fields.add(fields1[i]);
		for (int i=0; i<fields2.length; i++)
			fields.add(fields2[i]);
		
		
		if (fields.size() == 0)
			return o.toString();
		
		StringBuffer sb = new StringBuffer();
		Iterator it = fields.iterator();
		while(it.hasNext()) {
			Field f = (Field)it.next();
			String cs = f.getType().toString(); // class name of field
			sb.append(fieldDelim).append(indent).append('[')
					.append(f.getName()).append(":");
			try {
				if ("boolean".equals(cs))
					sb.append(f.getBoolean(o));
				else if ("byte".equals(cs))
					sb.append(f.getByte(o));
				else if ("char".equals(cs))
					sb.append(f.getChar(o));
				else if ("double".equals(cs))
					sb.append(f.getDouble(o));
				else if ("float".equals(cs))
					sb.append(f.getFloat(o));
				else if ("int".equals(cs))
					sb.append(f.getInt(o));
				else if ("long".equals(cs))
					sb.append(f.getLong(o));
				else if ("short".equals(cs))
					sb.append(f.getShort(o));
				else if ("class java.lang.String".equals(cs))
					sb.append(f.get(o));
				else { 
					sb.append(toString(f.get(o), "  " + indent, fieldDelim));
				}
				sb.append(']');
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			}

		}
		return sb.toString();
	}

	public static String toString(Object o) {
		return toString(o, "");
	}

	public static String toString(Object o, String indent) {
		return toString(o, indent, "\n");
	}
}