package fw.db.connection.impl;

import fw.common.util.CE;
import fw.common.util.LE;
import fw.db.connection.DBException;
import fw.db.connection.RecordHandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;


/**
 * 通用的EntityBean查询映射处理类<br/>
 * NOTE: 给定的Entity必须符合STREET规定的命名规则
 * @author dzb
 *
 * @param <T>
 */
class RecordHandlerImpl<T> implements RecordHandler<T> {

	private final CE<T> ce;
	//private String[] propNames = nul
	
	public RecordHandlerImpl(Class<T> classOfT) {
		ce = CE.of(classOfT);
		//propNames =LE.getPropertyNames(classOfT);
	}
	
	public T mapping(ResultSet rs, int row) throws DBException {

        try {

            ResultSetMetaData rsm = rs.getMetaData();

            String[] columnNames = new String[rsm.getColumnCount()];
            for (int i=0; i<rsm.getColumnCount(); i++){
                columnNames[i] = rsm.getColumnName(i+1).toLowerCase();
            }

			T bean = ce.create();

            for (String cn : columnNames) {
                Object v = rs.getObject(cn);
                String fn = DBUtils.convColumnNameToPropertyName(cn);
// TODO think about the comment block check logic
//                Field field = ce.getField(fn);
//                v = LE.coerce(v, field.getType());
                LE.setPropertyValue(bean, fn, v);
            }

            return bean;

		} catch (Throwable e) {
			throw new DBException(e);
		}
	}
}
