1import React, { useCallback, useMemo } from 'react';
2import { Select } from '@grafana/ui';
3import { SelectableValue } from '@grafana/data';
4
5import { Field } from '../Field';
6import { AzureQueryEditorFieldProps, AzureMonitorOption } from '../../types';
7import { setAggregation } from './setQueryValue';
8
9interface AggregationFieldProps extends AzureQueryEditorFieldProps {
10  aggregationOptions: AzureMonitorOption[];
11  isLoading: boolean;
12}
13
14const AggregationField: React.FC<AggregationFieldProps> = ({
15  query,
16  variableOptionGroup,
17  onQueryChange,
18  aggregationOptions,
19  isLoading,
20}) => {
21  const handleChange = useCallback(
22    (change: SelectableValue<string>) => {
23      if (!change.value) {
24        return;
25      }
26
27      const newQuery = setAggregation(query, change.value);
28      onQueryChange(newQuery);
29    },
30    [onQueryChange, query]
31  );
32
33  const options = useMemo(() => [...aggregationOptions, variableOptionGroup], [
34    aggregationOptions,
35    variableOptionGroup,
36  ]);
37
38  return (
39    <Field label="Aggregation">
40      <Select
41        menuShouldPortal
42        inputId="azure-monitor-metrics-aggregation-field"
43        value={query.azureMonitor?.aggregation}
44        onChange={handleChange}
45        options={options}
46        width={38}
47        isLoading={isLoading}
48      />
49    </Field>
50  );
51};
52
53export default AggregationField;
54