/*
 * 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.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ArrayConverter<T> extends AbstractConverter<T> {
	private ConverterFactory factory;
	
	public ArrayConverter(Class<T> type, ConverterFactory factory) {
		super(type);
		this.factory = factory;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected T convertValue(Object value) {
		Class cType = type.getComponentType();
		Converter conv = factory.getConverter(cType);

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

			Object array = Array.newInstance(cType, size);
			for (int i = 0; i < size; i++) {
				Object v = Array.get(value, i);
				v = conv.convert(v);
				Array.set(array, i, v);
			}
			return (T)array; 
		}
		else if (value instanceof Iterable) {
			List list = new ArrayList();
			Iterator it = ((Iterable)value).iterator();
			while (it.hasNext()) {
				list.add(conv.convert(it.next()));
			}

			Object array = Array.newInstance(cType, list.size());
			int index = 0;
			for (Object v : list) {
				Array.set(array, index++, v);
			}
			return (T)array; 
		}
		else {
			Object array = Array.newInstance(cType, 1);
			value = conv.convert(value);
			Array.set(array, 0, value);
			return (T)array;
		}
	}
}
