package jnpf.ureport.build.aggregate;

import jnpf.ureport.build.BindData;
import jnpf.ureport.build.Context;
import jnpf.ureport.definition.value.DatasetValue;
import jnpf.ureport.model.Cell;
import jnpf.ureport.utils.DataUtils;

import java.util.*;


public class GroupAggregate extends Aggregate {
    @Override
    public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
        List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
        List<BindData> list = doAggregate(expr, cell, context, objList);
        return list;
    }

    protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context, List<Map<String, Object>> objList) {
        List<BindData> list = new ArrayList<>();
        String property = expr.getProperty();
        Map<Object, List<Map<String, Object>>> map = new LinkedHashMap<>();
        for (Map<String, Object> obj : objList) {
            List<Map<String, Object>> rowList = new ArrayList<>();
            Object value = obj.get(property) != null ? obj.get(property) : "";
            if (map.containsKey(value)) {
                rowList = map.get(value);
            }
            rowList.add(obj);
            map.put(value, rowList);
        }
        for (Object key : map.keySet()) {
            BindData bindData = new BindData();
            bindData.setValue(key);
            bindData.setDataList(map.get(key));
            list.add(bindData);
        }
        if (list.size() == 0) {
            List<Map<String, Object>> rowList = new ArrayList<>();
            rowList.add(new HashMap<>());
            BindData bindData = new BindData();
            bindData.setValue("");
            bindData.setDataList(rowList);
            list.add(bindData);
        }
        return list;
    }
}
