import React from 'react'
import {Col, Form, Row, Card, CardDeck, Button, Container} from "react-bootstrap";
import { Meteor } from 'meteor/meteor';
import {getAllEspNames} from "../api/espNames";
import {getAllPlantTypes} from "../api/plantTypes";
import {ConfiguredDevicesCollection, PlantTypesCollection, ActiveDeviceCollection, SensorDataCollection} from "../../client/main";
import {useTracker} from 'meteor/react-meteor-data';

export default function Settings() {
    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 plantTypes = useTracker(() => {
        return PlantTypesCollection.find();
    });

    var selectedEspName;
    var selectedType;

    const payloadVegi = plantTypes.fetch()[0];
    const payloadCacti = plantTypes.fetch()[1];
    const payloadFlower = plantTypes.fetch()[2];

    const handleChangeName = (e) => {
        if (e.target.value === "") {
            console.log("No device selected!");
        } else {
            selectedEspName = e.target.value;
        }
    }

    const handleChangeType = (e) => {
        if (e.target.value === "") {
            console.log("No type selected!");
        } else {
            selectedType = e.target.value;
        }
    }

    const handleTest = (e) => {
        var payload = "";
        if (selectedType === "Vegetables") {payload = JSON.stringify(payloadVegi.data.soilMoisture);}
        if (selectedType === "Cacti") {payload = JSON.stringify(payloadCacti.data.soilMoisture);}
        if (selectedType === "Flowers") {payload = JSON.stringify(payloadFlower.data.soilMoisture);}

        if ((payload === "") || (selectedEspName === undefined) || (selectedType === undefined)) {alert("No device or type selected!");} else {
            Meteor.call('mqttPublish', {
                topic: 'smartgarden/commands/' + selectedEspName + '/soil',
                payload: payload
            }, (err, res) => {
                if (err) {
                    alert(err);
                } else {
                    alert('success')
                }
            })

            var doc = ConfiguredDevicesCollection.findOne({deviceName: selectedEspName});
            if (doc === undefined) {ConfiguredDevicesCollection.insert({deviceName: selectedEspName, type: selectedType});} else {
                ConfiguredDevicesCollection.update({_id: doc._id}, {$set: {type: selectedType}});
            }
        }
    }


    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 (
            <>
                <Container>
                    <Row className="justify-content-md-center">
                        <Col md="auto">
                            <h1>Settings</h1>
                        </Col>
                    </Row>
                    <Row className="justify-content-md-center">
                        <a>Configure your plant here. Based on your settings the smart garden will automate your plant environment.</a>
                    </Row>

                    <br></br>

                    <Form>
                        <Form.Group>
                            <Form.Label>Name:</Form.Label>
                            <Form.Control as="select" type="text" onChange={handleChangeName}>
                                <option></option>
                                {getAllEspNames().map((espName, index) => {
                                    return <option key={index} value={espName}>{espName}</option>
                                })}
                            </Form.Control>
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>Type:</Form.Label>
                            <Form.Control as="select" type="text" onChange={handleChangeType}>
                                <option></option>
                                {getAllPlantTypes().map((type, index) => {
                                    return <option key={index} value={type}>{type}</option>
                                })}
                            </Form.Control>
                        </Form.Group>
                        <Button type={"test"} onClick={handleTest} >Send</Button>
                    </Form>

                </Container>

            </>
        )
    }
}