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

import java.lang.reflect.Array;

/**
 * ArrayBeanHandler
 */
public class ArrayBeanHandler<T> extends AbstractJavaBeanHandler<T> {
	/**
	 * Constructor
	 * @param factory bean handler factory
	 * @param type bean type
	 */
	public ArrayBeanHandler(BeanHandlerFactory factory, Class<T> type) {
		super(factory, type);
	}
	
	/**
	 * get read property names
	 * @param array bean object (can be null)
	 * @return property names
	 */
	public String[] getReadPropertyNames(T array) {
		if (array == null) {
			return new String[0];
		}
		
		String[] pns = new String[Array.getLength(array)];
		
		for (int i = 0; i < pns.length; i++) {
			pns[i] = String.valueOf(i);
		}

		return pns;
	}

	/**
	 * get write property names
	 * @param array bean object (can be null)
	 * @return property names
	 */
	public String[] getWritePropertyNames(T array) {
		return getReadPropertyNames(array);
	}

	protected int toIndex(String index) {
		try {
			return Integer.parseInt(index);
		}
		catch (NumberFormatException nfe) {
			throw new IllegalArgumentException("[" + index + "] is not a valid index number.");
		}
	}

	public Class getPropertyType(T array, String propertyName) {
		if (array == null) {
			return Object.class;
		}
		Object val = getPropertyValue(array, propertyName);
		return val == null ? Object.class : val.getClass();
	}
	
	protected Object getElement(T array, int index) {
		return Array.get(array, index);
	}
	
	protected void setElement(T array, int index, Object value) {
		Array.set(array, index, value);
	}
	
	public Object getPropertyValue(T array, String propertyName) {
		int index = toIndex(propertyName);
		return getElement(array, index);
	}
	
	public void setPropertyValue(T array, String propertyName, Object propertyValue) {
		int index = toIndex(propertyName);
		setElement(array, index, propertyValue);
	}
}
