import React from 'react'

import { useGridContext, useGridSelector } from '../context/grid-context'
import { getAggregationResults, getRowValues } from '../utils/aggregation'

export const useAggregations = () => {
    const grid = useGridContext()
    const { selectors } = grid

    const aggregationFns = useGridSelector(
        selectors.selectAggregationConfigurations
    )
    const rowIds = useGridSelector(selectors.selectRowIds)

    const { meta, entities } = useGridSelector(selectors.selectRowCollection)

    const aggregations = React.useMemo(() => {
        const values = getRowValues(rowIds, entities, meta, aggregationFns)
        const results = getAggregationResults(aggregationFns, values)
        return results
    }, [aggregationFns, rowIds, meta, entities])

    return aggregations
}
