1import React, { PureComponent } from 'react';
2import { DataSourceApi, QueryEditorProps, SelectableValue } from '@grafana/data';
3import { InlineField, Select } from '@grafana/ui';
4import { Resample } from './components/Resample';
5import { Reduce } from './components/Reduce';
6import { Math } from './components/Math';
7import { ClassicConditions } from './components/ClassicConditions';
8import { getDefaults } from './utils/expressionTypes';
9import { ExpressionQuery, ExpressionQueryType, gelTypes } from './types';
10
11type Props = QueryEditorProps<DataSourceApi<ExpressionQuery>, ExpressionQuery>;
12
13const labelWidth = 14;
14export class ExpressionQueryEditor extends PureComponent<Props> {
15  onSelectExpressionType = (item: SelectableValue<ExpressionQueryType>) => {
16    const { query, onChange } = this.props;
17
18    onChange(getDefaults({ ...query, type: item.value! }));
19  };
20
21  renderExpressionType() {
22    const { onChange, query, queries } = this.props;
23    const refIds = queries!.filter((q) => query.refId !== q.refId).map((q) => ({ value: q.refId, label: q.refId }));
24
25    switch (query.type) {
26      case ExpressionQueryType.math:
27        return <Math onChange={onChange} query={query} labelWidth={labelWidth} />;
28
29      case ExpressionQueryType.reduce:
30        return <Reduce refIds={refIds} onChange={onChange} labelWidth={labelWidth} query={query} />;
31
32      case ExpressionQueryType.resample:
33        return <Resample query={query} labelWidth={labelWidth} onChange={onChange} refIds={refIds} />;
34
35      case ExpressionQueryType.classic:
36        return <ClassicConditions onChange={onChange} query={query} refIds={refIds} />;
37    }
38  }
39
40  render() {
41    const { query } = this.props;
42    const selected = gelTypes.find((o) => o.value === query.type);
43
44    return (
45      <div>
46        <InlineField label="Operation" labelWidth={labelWidth}>
47          <Select
48            menuShouldPortal
49            options={gelTypes}
50            value={selected}
51            onChange={this.onSelectExpressionType}
52            width={25}
53          />
54        </InlineField>
55        {this.renderExpressionType()}
56      </div>
57    );
58  }
59}
60