import React from 'react'
import {
    SensorDataCollection,
    ActiveDeviceCollection,
    ConfiguredDevicesCollection,
    PlantTypesCollection
} from "../../client/main";
import {useTracker} from 'meteor/react-meteor-data';
import { Card, CardDeck, Table } from "react-bootstrap";

export default function Overview() {
    const deviceName = useTracker(() => {
        return ActiveDeviceCollection.find().fetch()[0];
    });

    const sensorData = useTracker(() => {
        if (deviceName === null || deviceName === undefined) {
            return [];
        } else {
            return SensorDataCollection.find({device_id: deviceName.deviceName}, {
                sort: {timestamp: -1},
                limit: 61
            }).fetch().reverse();
        }
    });

    const configuredDevices = useTracker(() => {
        return ConfiguredDevicesCollection.find().fetch();
    });

    function getDirt(type) {
        const plantType = PlantTypesCollection.findOne({plantType: type});
        return plantType.dirtType
    }


    if ((sensorData.length <= 0)) {
        return (
            <CardDeck>
                <Card>
                    <Card.Body>
                        <Card.Title>Loading!</Card.Title>
                        <Card.Text>Please wait...</Card.Text>
                    </Card.Body>
                </Card>
            </CardDeck>
        )
    } else {
        return (
            <>
                <Table striped bordered hover responsive>
                    <thead>
                        <tr key={'head'}>
                            <th key={'#'}>#</th>
                            <th key={'name'}>Device Name</th>
                            <th key={'type'}>Plant Type</th>
                            <th key={'dirt'}>Dirt Type</th>
                        </tr>
                    </thead>
                    <tbody>
                        {configuredDevices.map((device, index) => {
                            return <tr key={'body' + index}>
                                <td key={'#-' + index}>{index}</td>
                                <td key={'name-' + index}>{device.deviceName}</td>
                                <td key={'type-' + index}>{device.type}</td>
                                <td key={'dirt-' + index}>{getDirt(device.type)}</td>
                            </tr>
                        })}
                    </tbody>
                </Table>
                <br></br>
                <h4>If your device is not visible, go to Settings to configure it first.</h4>
            </>
        )
    }
}