package eu.dnetlib.contract.runner;

import java.util.HashMap;
import java.util.Map;

/**
 * Primitives class autoboxer.
 * Required to reference autoboxed {@link Class} for given primitive {@link Class}.
 * 
 * @author mhorst
 *
 */
public class PrimitivesAutoboxer {

	/**
	 * Mapps primitive java types to their autoboxed wrappers classes. 
	 */
	public static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_MAP = new HashMap<Class<?>, Class<?>>();
	
	static {
		PRIMITIVE_TO_WRAPPER_MAP.put(Byte.TYPE, Byte.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Short.TYPE, Short.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Integer.TYPE, Integer.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Long.TYPE, Long.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Character.TYPE, Character.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Float.TYPE, Float.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Double.TYPE, Double.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Boolean.TYPE, Boolean.class);
		PRIMITIVE_TO_WRAPPER_MAP.put(Void.TYPE, Void.class);
	}
	
	/**
	 * Returns boxed version of primitive class.
	 * If class is not a primitive it is returned as a result.
	 * @param clazz
	 * @return boxed version of primitive class
	 */
	public static Class<?> box(Class<?> clazz) {
//		introduced as a solution to the problem descibed here
//		http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6456930
//		http://www.freshvanilla.org:8080/display/www/Auto-boxing+and+assignment+between+primitives+and+wrappers.
		if (clazz!=null && clazz.isPrimitive()) {
			if (PRIMITIVE_TO_WRAPPER_MAP.containsKey(clazz)) {
				return PRIMITIVE_TO_WRAPPER_MAP.get(clazz);
			} else {
//				shouldn't happen
				throw new RuntimeException(
						"Fault: no mapping defined for primitive: " +
						clazz.getName() + ", cannot get it's autoboxed wrapper!");
			}
		} else {
			return clazz;
		}
	}
}
