/**
 * 
 */
package com.trendrr.oss.casting;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.logging.Logger;

import com.trendrr.json.simple.JSONValue;

import com.trendrr.oss.DynMap;


/**
 * @author Dustin Norlander
 * @created Dec 29, 2010
 * 
 */
public class DynMapCaster extends TypeCaster<DynMap> {
	Logger log = Logger.getLogger(DynMapCaster.class.getCanonicalName());
	/* (non-Javadoc)
	 * @see com.trendrr.oss.casting.TypeCaster#doCast(java.lang.Class, java.lang.Object)
	 */
	@Override
	protected DynMap doCast(Class clss, Object object) {
		
		if (object instanceof Map) {
			return toDynMap((Map)object);
		}
		
		if (object instanceof String) {
			//try the json simple here. 
			try {
				Object obj = JSONValue.parseWithException((String)object);
				if (obj instanceof Map){
					return toDynMap((Map)obj);
				}
			} catch (Exception x) {
				log.info("Unable to parse string: " + object + " into a DynMap (" + x.getMessage() + ")");
			}
			return null;
		}
		
		
		Class cls = object.getClass();
		try {
			Method toMap = cls.getMethod("toMap");
			log.info("found toMap method");
			Map mp = (Map)toMap.invoke(object);
			return toDynMap((Map)mp);
			
		} catch (Exception x) {
			log.info("toMap method didn't work for " + object + " into a DynMap (" + x.getMessage() + ")");
		}
		return null;
	}
	
	private DynMap toDynMap(Map map) {
		DynMap mp = new DynMap();
		for (Object key : map.keySet()) {
			mp.put(key.toString(), map.get(key));
		}
		return mp;
	}
}

@@ -1189,17 +1189,65 @@
 )mp);%0A%09%09
-%09
+%7D catch (NoSuchMethodError x) %7B %0A%09%09%09//do nothing.
 %0A%09%09%7D cat
@@ -1424,16 +1424,77 @@
  map) %7B%0A
+%09%09if (map instanceof DynMap) %7B%0A%09%09%09return (DynMap)map;%0A%09%09%7D%0A%09%09%0A
 %09%09DynMap

check if Map is already a DynMap, return if it is. Swallow NoSuchMethod error to avoid annoying log messages