/*
 * 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.lang.reflect.Array;
import java.util.Collection;

import woolpack.utils.UtilsConstants;

/**
 * 一覧型を変換する{@link Convertable}。
 * 適用しているパターン：Proxy。
 * @author nakamura
 *
 */
public class CollectionConverter implements Convertable {
	private final Convertable convertable;
	
	/**
	 * コンストラクタ。
	 * @param convertable 単純型を変換するための委譲先。
	 * @throws NullPointerException 引数が null の場合。
	 */
	public CollectionConverter(final Convertable convertable){
		convertable.getClass();
		this.convertable = convertable;
	}

	public Object convert(final Object beforeValue, final Class toType, final String propertyName){
		final Collection collection = UtilsConstants.toCollection(beforeValue);
		if(toType.isArray()){
			final Class componentType = toType.getComponentType();
			final Object afterArray = Array.newInstance(componentType, collection.size());
			int i=0;
			final boolean primitiveFlag = componentType.isPrimitive();
			for(final Object before:collection){
				final Object after = convertable.convert(before, componentType, propertyName);
				if(!primitiveFlag || after != null){
					// 値が null でプリミティブの場合は値を設定しない(配列作成時の初期値のまま)。
					Array.set(afterArray, i, after);
				}
				i++;
			}
			return afterArray;
		}else if(Collection.class.isAssignableFrom(toType)){
			return collection;
		}else{
			final Object value = collection.iterator().next();
			return convertable.convert(value, toType, propertyName);
		}
	}

	public Convertable getConvertable() {
		return convertable;
	}
}
