/*
 * 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.castor.castors;

import nuts.core.castor.AbstractCastor;
import nuts.core.castor.CastContext;
import nuts.core.castor.Castor;
import nuts.core.castor.Castors;
import nuts.core.lang.Arrays;
import nuts.core.lang.Types;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ArrayCastor<S, T> extends AbstractCastor<S, T> {
	private Castors castors;
	private Type toComponentType;
	
	public ArrayCastor(Type fromType, Type toType, Castors castors) {
		super(fromType, toType);
		
		this.castors = castors;

		if (!Types.isArrayType(toType)) {
			throw new IllegalArgumentException("The argument is not a array type: " + toType);
		}
		toComponentType = Types.getArrayComponentType(toType);
	}

	private Type getFromComponentType() {
		Type cType = Types.getArrayElementType(fromType);
		return cType == null ? Object.class : cType;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected T convertValue(Object value, CastContext context) {
		if (value.getClass().isArray()) {
			Type fType = value.getClass().getComponentType();
			Castor conv = castors.getCastor(fType, toComponentType);

			int size = Array.getLength(value);
			Object array = Arrays.newInstance(toComponentType, size);
			for (int i = 0; i < size; i++) {
				Object v = Array.get(value, i);
				v = castChild(context, conv, i, v);
				Array.set(array, i, v);
			}
			return (T)array; 
		}
		else if (value instanceof Iterable) {
			Type fType = getFromComponentType();
			Castor conv = castors.getCastor(fType, toComponentType);

			int i = 0;
			List list = new ArrayList();
			Iterator it = ((Iterable)value).iterator();
			while (it.hasNext()) {
				Object v = it.next();
				list.add(castChild(context, conv, i++, v));
			}

			Object array = Arrays.newInstance(toComponentType, list.size());
			int index = 0;
			for (Object v : list) {
				Array.set(array, index++, v);
			}
			return (T)array; 
		}
		else {
			Object array = Arrays.newInstance(toComponentType, 1);
			Castor conv = castors.getCastor(value.getClass(), toComponentType);
			Array.set(array, 0, castChild(context, conv, 0, value));
			return (T)array;
		}
	}
}
