import { findAllMeasures } from "../../../../utils/index.js";
import { buildTree } from "./datasetHierarchy.js";
import { omit } from "remeda";
const datasetPivotHierarchy = (spec, context)=>{
    const result = {
        ...spec
    };
    const { advancedVSeed } = context;
    const { dataset, datasetReshapeInfo, measures } = advancedVSeed;
    const measureKeys = findAllMeasures(measures).map((m)=>m.id);
    const hierarchyFields = advancedVSeed.encoding?.hierarchy || [];
    const rows = advancedVSeed.encoding?.row || [];
    const columns = advancedVSeed.encoding?.column || [];
    const pivotDims = [
        ...rows,
        ...columns
    ];
    const records = dataset.reduce((pre, cur, index)=>{
        const id = datasetReshapeInfo[index].id;
        const { foldInfo, unfoldInfo } = datasetReshapeInfo[index];
        if (pivotDims.length > 0) {
            const groupedDataset = groupByDimensions(cur, pivotDims);
            pre[id] = groupedDataset.flatMap((data)=>{
                const root = {
                    ...data,
                    children: buildTree(data.children, hierarchyFields, foldInfo, unfoldInfo, measureKeys)
                };
                const rootProps = omit(root, [
                    'children'
                ]);
                const rootTree = root.children.map((child)=>({
                        ...child,
                        ...rootProps
                    }));
                return rootTree;
            });
        } else {
            const tree = buildTree(cur, hierarchyFields, foldInfo, unfoldInfo, measureKeys);
            pre[id] = tree;
        }
        return pre;
    }, {});
    return {
        ...result,
        records: records
    };
};
function groupByDimensions(data, dimKeys) {
    if (0 === dimKeys.length) return data;
    const buckets = new Map();
    for (const item of data){
        const compositeKey = dimKeys.map((k)=>String(item[k])).join('\x00');
        if (!buckets.has(compositeKey)) {
            const dimValues = {};
            for (const k of dimKeys)dimValues[k] = item[k];
            buckets.set(compositeKey, {
                dimValues,
                items: []
            });
        }
        buckets.get(compositeKey).items.push(item);
    }
    const result = [];
    for (const [, { dimValues, items }] of buckets)result.push({
        ...dimValues,
        children: items
    });
    return result;
}
export { datasetPivotHierarchy };

//# sourceMappingURL=datasetPivotHierarchy.js.map