/*
 * 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 woolpack.utils.CheckUtils;

/**
 * 変換前の値が null である、または変換前の値の型が変換後の型と等しい、または変換後の型が{@link Object}または null
 * の場合は変換前の値を返し、それ以外の場合は委譲する{@link Convertable}。
 * 
 * @author nakamura
 * 
 */
public class DelegationIfNecessityConverter implements Convertable {
	private final Convertable convertable;

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

	public Object convert(final Object beforeValue, final Class toType,
			final String propertyName) {
		if (beforeValue == null || toType == null
				|| beforeValue.getClass().equals(toType)
				|| Object.class.equals(toType)) {
			return beforeValue;
		} else {
			return convertable.convert(beforeValue, toType, propertyName);
		}
	}

	public Convertable getConvertable() {
		return convertable;
	}
}
