package jp.sf.amateras.mirage.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.sf.amateras.mirage.bean.BeanDesc;
import jp.sf.amateras.mirage.bean.PropertyDesc;
import jp.sf.amateras.mirage.naming.NameConverter;
import jp.sf.amateras.mirage.type.ValueType;

// TODO JdbcUtilに統合する？
public class MirageUtil {

	@SuppressWarnings("unchecked")
	public static <T> T createEntity(Class<T> clazz, ResultSet rs,
			ResultSetMetaData meta, int columnCount, BeanDesc beanDesc,
			List<ValueType> valueTypes, NameConverter nameConverter)
			throws InstantiationException, IllegalAccessException, SQLException {

		for(ValueType valueType: valueTypes){
			if(valueType.isSupport(clazz)){
				return (T) valueType.get(clazz, rs, 1);
			}
		}

		T entity = null;
		if(clazz == Map.class){
			entity = (T) new HashMap<String, Object>();
		} else {
			entity = clazz.newInstance();
		}

		for(int i = 0; i < columnCount; i++){
			String columnName = meta.getColumnName(i + 1);
			String propertyName = nameConverter.columnToProperty(columnName);

			PropertyDesc pd = beanDesc.getPropertyDesc(propertyName);

			if(pd != null){
				Class<?> fieldType = pd.getPropertyType();
				for(ValueType valueType: valueTypes){
					if(valueType.isSupport(fieldType)){
						pd.setValue(entity, valueType.get(fieldType, rs, columnName));
						break;
					}
				}
			}
		}
		return entity;
	}
}
