package hibergui;

import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;

public class Util {

	public static final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
	public static final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);

	public static final String ensure(String s) {
		return s == null ? "" : s;
	}
	
	public static final <T> Set<T> ensure(Set<T> s) {
		return s == null ? new HashSet<T>() : s;
	}

	public static final <T> List<T> ensure(List<T> list) {
		return list == null ? new ArrayList<T>() : list;
	}

	public static final <K, V> Map<K, V> ensure(Map<K, V> map) {
		return map == null ? new HashMap<K, V>() : map;
	}

	public static final String ensureString(Date d) {
		return d == null ? "" : dateFormat.format(d);
	}
	
	public static final String ensureString(Integer i) {
		return i == null ? "" : i.toString();
	}
	
	public static final String ensureString(Character c) {
		return c == null ? "" : c.toString();
	}
	
	public static final <T> List<T> ensureList(Collection<T> c) {
		return 
			c == null 
				? new ArrayList<T>() 
				: ((c instanceof List) 
						? (List<T>) c
						: new ArrayList<T>(c));
	}

	public static final Object ensure(Object o, String prop) {
		try {
			Object p = PropertyUtils.getProperty(o, prop);
			if (p != null)
				return p;
			Class<?> propType = PropertyUtils.getPropertyType(o, prop);
			if (propType.isAssignableFrom(List.class))
				p = new ArrayList();
			else if (propType.isAssignableFrom(Set.class)) 
				p = new HashSet();
			else if (propType.isAssignableFrom(Map.class)) 
				p = new HashMap();
			else
				p = propType.newInstance();
			PropertyUtils.setProperty(o, prop, p);
			return p;
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
