/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.el.convert;

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

import woolpack.utils.CheckUtils;
import woolpack.utils.MapBuilder;

/**
 * {@link Convertable#convert(Object, Class, String)}
 * の{@link Class}引数がプリミティブ型の場合、
 * 対応するラッパークラスの{@link Class}インスタンスに置き換えて委譲先に渡す{@link Convertable}。
 * 
 * @author nakamura
 * 
 */
public class ToTypeToWapperConverter implements Convertable {

	private static final Map<Class, Class> PRIMITIVE_TO_WRAPPER_MAP = MapBuilder
			.get(new HashMap<Class, Class>()).put(boolean.class, Boolean.class)
			.put(char.class, Character.class).put(byte.class, Byte.class).put(
					short.class, Short.class).put(int.class, Integer.class)
			.put(long.class, Long.class).put(float.class, Float.class).put(
					double.class, Double.class).get();

	private final Convertable convertable;

	/**
	 * コンストラクタ。
	 * 
	 * @param convertable
	 *            委譲先。
	 * @throws NullPointerException
	 *             引数が null の場合。
	 */
	public ToTypeToWapperConverter(final Convertable convertable) {
		CheckUtils.checkNotNull(convertable);
		this.convertable = convertable;
	}

	public Object convert(final Object beforeValue, final Class toType,
			final String propertyName) {
		Class newClass = PRIMITIVE_TO_WRAPPER_MAP.get(toType);
		if (newClass == null) {
			newClass = toType;
		}
		return convertable.convert(beforeValue, newClass, propertyName);
	}

	public Convertable getConvertable() {
		return convertable;
	}
}
