/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.util.converter;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;


public class CollectionConverter<T extends Collection<?>> extends AbstractConverter<T> {
	protected ConverterFactory factory;
	protected Class elementType;
	
	public CollectionConverter(Class<T> type, Class<?> elementType, ConverterFactory factory) {
		super(type);
		
		this.factory = factory;
		
		this.elementType = elementType;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected T convertValue(Object value) {
		Converter conv = factory.getConverter(elementType);
		Collection coll = createObject();

		if (value.getClass().isArray()) {
			int size = Array.getLength(value);

			for (int i = 0; i < size; i++) {
				Object v = Array.get(value, i);
				v = conv.convert(v);
				coll.add(v);
			}
		}
		else if (value instanceof Collection) {
			coll.addAll((Collection)value);
		}
		else if (value instanceof Iterable) {
			Iterator it = ((Iterable)value).iterator();
			while (it.hasNext()) {
				coll.add(conv.convert(it.next()));
			}
		}
		else {
			value = conv.convert(value);
			coll.add(value);
		}
		return (T)coll; 
	}
}
