package sharin.sql.runner.processor;

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

import sharin.sql.runner.ResultSetProcessor;
import sharin.util.PropertyUtils;
import sharin.util.SqlUtils;

public class MapResultSetProcessor implements ResultSetProcessor {

    public Object prepare(ResultSet rs) {
        ResultSetMetaData metaData = SqlUtils.getMetaData(rs);
        int columnCount = SqlUtils.getColumnCount(metaData);
        String[] columnLabels = new String[columnCount];

        for (int i = 0; i < columnCount; i++) {
            columnLabels[i] = SqlUtils.getColumnLabel(metaData, i + 1);
        }

        return columnLabels;
    }

    public Object process(ResultSet rs, Object context) {
        String[] columnLabels = (String[]) context;
        Map<String, Object> result = new HashMap<String, Object>();

        for (int i = 0; i < columnLabels.length; i++) {
            PropertyUtils.setNestedPropertyValue(result, columnLabels[i],
                    SqlUtils.getObject(rs, i + 1));
        }

        return result;
    }
}
