import { useEffect , useCallback , useMemo } from 'react' ; import { i18n } from '@osd/i18n' ; import { IAggConfig } from 'src/plugins/data/public' ; type AggFilter = string [ ] ; const DEFAULT_METRIC = 'custom' ; const CUSTOM_METRIC = { text : i18n . translate ( 'visDefaultEditor.controls.customMetricLabel' , { defaultMessage : 'Custom metric' , } ) , value : DEFAULT_METRIC , } ; function useCompatibleAggCallback ( aggFilter ) { return useCallback ( isCompatibleAggregation ( aggFilter ) , [ aggFilter ] ) ; } /**
 * the effect is used to set up a default metric aggregation in case,
 * when previously selected metric has been removed
 */ function useFallbackMetric ( setValue , aggFilter , metricAggs ? , value ? , fallbackValue ? ) { const isCompatibleAgg = useCompatibleAggCallback ( aggFilter ) ; useEffect ( ( ) => { if ( metricAggs && value && value !== DEFAULT_METRIC ) { const respAgg = metricAggs . filter ( isCompatibleAgg ) . find ( ( aggregation ) => aggregation . id === value ) ; if ( ! respAgg && value !== fallbackValue ) { setValue ( fallbackValue ) ; } } } , [ setValue , isCompatibleAgg , metricAggs , value , fallbackValue ] ) ; } /**
 * this makes an array of available options in appropriate format for EuiSelect,
 * calculates if an option is disabled
 */ function useAvailableOptions ( aggFilter , metricAggs = [ ] , defaultOptions = [ ] ) { const isCompatibleAgg = useCompatibleAggCallback ( aggFilter ) ; const options = useMemo ( ( ) => [ ... metricAggs . map ( ( respAgg ) => ( { text : i18n . translate ( 'visDefaultEditor.controls.definiteMetricLabel' , { defaultMessage : 'Metric: {metric}' , values : { metric : safeMakeLabel ( respAgg ) , } , } ) , value : respAgg . id , disabled : ! isCompatibleAgg ( respAgg ) , } ) ) , CUSTOM_METRIC , ... defaultOptions , ] , [ metricAggs , defaultOptions , isCompatibleAgg ] ) ; return options ; } /**
 * the effect is used to set up the editor form validity
 * and reset it if a param has been removed
 */ function useValidation ( setValidity , isValid ) { useEffect ( ( ) => { setValidity ( isValid ) ; return ( ) => setValidity ( true ) ; } , [ isValid , setValidity ] ) ; } function safeMakeLabel ( agg ) { try { return agg . makeLabel ( ) ; } catch ( e ) { return i18n . translate ( 'visDefaultEditor.controls.aggNotValidLabel' , { defaultMessage : '- agg not valid -' , } ) ; } } function isCompatibleAggregation ( aggFilter ) { return ( agg ) => { return ! aggFilter . includes ( `!${ agg . type . name }` ) ; } ; } export { CUSTOM_METRIC , safeMakeLabel , isCompatibleAggregation , useAvailableOptions , useFallbackMetric , useValidation , } ;