import React from 'react';
import {Container, Segment, Grid, List, Label} from 'semantic-ui-react';
import DevField from './DeviceField';

class ModbusPreview extends React.Component {
    state = {
        list: []
    }

    tick = null

    componentDidMount(){
        this.getList()
        this.tick = setInterval(this.runTick, 10000);
    }

    componentWillUnmount(){
        clearInterval(this.tick);
    }

    runTick = () => {
        this.getList();
    }

    getList = () => {
        let {getRequest, showDialog} = this.props;
        fetch('/api/modbus/getalliostatus', getRequest())
            .then(response=>response.json())
            .then(json => {
                if(json.status != 1) return showDialog(json.message);
                let dev = json.data.rt.device || [];
                let status = json.data.record || [];
                for(let i in dev) { 
                    dev[i].list = [];
                    for(let j in status){
                        if(status[j].node == dev[i].node){
                            dev[i].list.push(status[j]);
                        }
                    }
                }

                this.setState({
                    list: dev
                });
            })
    }

    render() {
        let {i18n} = this.props;
        return (
            <Container fluid style={{paddingLeft: '10px', paddingRight: '10px'}}>
                <Grid columns={3}>
                    {
                        this.state.list.map((t,idx) => (
                            <DevField key={idx} i18n={i18n} data={t} />
                        ))
                    }
                </Grid>
            </Container>
        )
    }
}

export default ModbusPreview;