Passed
Push — master ( 92451b...a1dfdd )
by Guangyu
05:18 queued 11s
created

RealtimeChart.render   A

Complexity

Conditions 1

Size

Total Lines 36
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 36
rs 9.0879
c 0
b 0
f 0
cc 1
1
import React, { Component } from 'react';
2
import { Line } from 'react-chartjs-2';
3
import range from 'lodash/range';
4
import { Card, CardHeader, CardBody, ListGroup, ListGroupItem } from 'reactstrap';
5
import { rgbaColor } from '../../../helpers/utils';
6
import { withTranslation } from 'react-i18next';
7
import uuid from 'uuid/v1';
8
import { APIBaseURL } from '../../../config';
9
import { getCookieValue, createCookie } from '../../../helpers/utils';
10
import { toast } from 'react-toastify';
11
12
13
const dividerBorder = '1px solid rgba(255, 255, 255, 0.15)';
14
const listItemBorderColor = 'rgba(255, 255, 255, 0.05)';
15
16
class RealtimeChart extends Component {
17
  _isMounted = false;
18
  refreshInterval;
19
  refreshTimeout;
20
  state = {
21
    pointList: [],
22
  };
23
24
  componentWillUnmount() {
25
    this._isMounted = false;
26
    clearInterval(this.refreshInterval);
27
    clearTimeout(this.refreshTimeout);
28
  }
29
30
  componentDidMount() {
31
    console.log(this.props);
32
    this._isMounted = true;
33
    // fetch realtime data at the first time
34
    let isResponseOK = false;
35
    if (this.props.distributionSystemID != undefined) {
36
      fetch(APIBaseURL + '/reports/distributionsystem?distributionsystemid=' + this.props.distributionSystemID, {
37
        method: 'GET',
38
        headers: {
39
          "Content-type": "application/json",
40
          "User-UUID": getCookieValue('user_uuid'),
41
          "Token": getCookieValue('token')
42
        },
43
        body: null,
44
45
      }).then(response => {
46
        if (response.ok) {
47
          isResponseOK = true;
48
        }
49
        return response.json();
50
      }).then(json => {
51
        if (isResponseOK) {
52
          console.log(json);
53
          let pointList = [];
54
            json.forEach((currentCircuit, circuitIndex) => {
55
              json[circuitIndex]['points'].forEach((currentPoint, pointIndex) => {
56
                let pointItem = {}
57
                pointItem['circuit'] = currentCircuit['name'];
58
                pointItem['point'] = currentPoint['name'];
59
                pointItem['value'] = currentPoint['value'];
60
                pointItem['units'] = currentPoint['units'];
61
                pointList.push(pointItem);
62
              });
63
            });
64
          if (this._isMounted) {
65
            this.setState({ 
66
              pointList: pointList,
67
            });
68
          }
69
        } else {
70
          toast.error(json.description)
71
        }
72
      }).catch(err => {
73
        console.log(err);
74
      });
75
    };
76
77
    //fetch realtime data at regular intervals
78
    this.refreshInterval = setInterval(() => {
79
      let isResponseOK = false;
80
      fetch(APIBaseURL + '/reports/distributionsystem?distributionsystemid=' + this.props.distributionSystemID, {
81
        method: 'GET',
82
        headers: {
83
          "Content-type": "application/json",
84
          "User-UUID": getCookieValue('user_uuid'),
85
          "Token": getCookieValue('token')
86
        },
87
        body: null,
88
89
      }).then(response => {
90
        if (response.ok) {
91
          isResponseOK = true;
92
        }
93
        return response.json();
94
      }).then(json => {
95
        if (isResponseOK) {
96
          console.log(json);
97
          let pointList = [];
98
          json.forEach((currentCircuit, circuitIndex) => {
99
            json[circuitIndex]['points'].forEach((currentPoint, pointIndex) => {
100
              let pointItem = {}
101
              pointItem['circuit'] = currentCircuit['name'];
102
              pointItem['point'] = currentPoint['name'];
103
              pointItem['value'] = currentPoint['value'];
104
              pointItem['units'] = currentPoint['units'];
105
              pointList.push(pointItem);
106
            });
107
          });
108
          
109
          if (this._isMounted) {
110
            this.setState({ 
111
              pointList: pointList,
112
            });
113
          }
114
        } else {
115
          toast.error(json.description)
116
        }
117
      }).catch(err => {
118
        console.log(err);
119
      });
120
    }, (60 + Math.floor(Math.random() * Math.floor(10))) * 1000); // use random interval to avoid paralels requests 
121
  }
122
123
  render() {
124
    const { t } = this.props;
125
    
126
    return (
127
      <Card className="h-100 bg-gradient">
128
        <CardHeader className="bg-transparent">
129
          <h5 className="text-white">{this.props.distributionSystemName}</h5>
130
          <div className="real-time-user display-1 font-weight-normal text-white">{this.state.latestUpdateDatetime}</div>
131
        </CardHeader>
132
        <CardBody className="text-white fs--1">
133
          <ListGroup flush className="mt-4">
134
          
135
            <ListGroupItem
136
              className="bg-transparent d-flex justify-content-between px-0 py-1 font-weight-semi-bold border-top-0"
137
              style={{ borderColor: listItemBorderColor }}
138
            >
139
              <p className="mb-0">{t('Circuit')}</p>
140
              <p className="mb-0">{t('Point')}</p>
141
              <p className="mb-0">{t('Realtime Value')}</p>
142
              <p className="mb-0">{t('Unit')}</p>
143
            </ListGroupItem>
144
            {this.state.pointList.map(pointItem => (
145
              <ListGroupItem key={uuid()}
146
                className="bg-transparent d-flex justify-content-between px-0 py-1"
147
                style={{ borderColor: listItemBorderColor }}
148
              >
149
                <p className="mb-0">{pointItem['circuit']}</p>
150
                <p className="mb-0">{pointItem['point']}</p>
151
                <p className="mb-0">{pointItem['value']}</p>
152
                <p className="mb-0">{pointItem['units']}</p>
153
              </ListGroupItem>
154
            ))}
155
          </ListGroup>
156
        </CardBody>
157
      </Card>
158
    );
159
  }
160
}
161
162
export default  withTranslation()(RealtimeChart);
163