1import React, { useEffect, useState, ChangeEvent } from 'react';
2import { getBackendSrv } from '@grafana/runtime';
3import { Input } from '@grafana/ui';
4import Page from 'app/core/components/Page/Page';
5import { useNavModel } from 'app/core/hooks/useNavModel';
6import { Rule } from './types';
7import { PipelineTable } from './PipelineTable';
8import { AddNewRule } from './AddNewRule';
9
10export default function PipelineAdminPage() {
11  const [rules, setRules] = useState<Rule[]>([]);
12  const [defaultRules, setDefaultRules] = useState<any[]>([]);
13  const [newRule, setNewRule] = useState<Rule>();
14  const navModel = useNavModel('live-pipeline');
15  const [error, setError] = useState<string>();
16
17  const loadRules = () => {
18    getBackendSrv()
19      .get(`api/live/channel-rules`)
20      .then((data) => {
21        setRules(data.rules ?? []);
22        setDefaultRules(data.rules ?? []);
23      })
24      .catch((e) => {
25        if (e.data) {
26          setError(JSON.stringify(e.data, null, 2));
27        }
28      });
29  };
30
31  useEffect(() => {
32    loadRules();
33  }, []);
34
35  const onSearchQueryChange = (e: ChangeEvent<HTMLInputElement>) => {
36    if (e.target.value) {
37      setRules(rules.filter((rule) => rule.pattern.toLowerCase().includes(e.target.value.toLowerCase())));
38    } else {
39      setRules(defaultRules);
40    }
41  };
42
43  return (
44    <Page navModel={navModel}>
45      <Page.Contents>
46        {error && <pre>{error}</pre>}
47        <div className="page-action-bar">
48          <div className="gf-form gf-form--grow">
49            <Input placeholder="Search pattern..." onChange={onSearchQueryChange} />
50          </div>
51        </div>
52
53        <PipelineTable rules={rules} onRuleChanged={loadRules} selectRule={newRule} />
54
55        <AddNewRule
56          onRuleAdded={(r: Rule) => {
57            console.log('GOT', r, 'vs', rules[0]);
58            setNewRule(r);
59            loadRules();
60          }}
61        />
62      </Page.Contents>
63    </Page>
64  );
65}
66