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

export default function Settings() {
    const plantTypes = useTracker(() => {
        return PlantTypesCollection.find();
    });

    const espIds = useTracker(getAllEspIds);

    var selectedEspId;
    var selectedAlias = "";
    var selectedType;
    var selectedMode = null;

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

    const handleChangeAlias = (e) => {
        if (e.target.value === "") {
            console.log("Nickname cannot be empty!");
        } else {
            selectedAlias = e.target.value;
        }
    }

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

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

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

    const handleSendData = (e) => {
        var payload = "";
        var nmValue = null;
        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 (selectedMode === "Growth") {nmValue = 450}
        if (selectedMode === "Bloom") {nmValue = 700}


        console.log("Payload: " + payload);
        console.log("Alias: " + selectedAlias);
        console.log("ID: " + selectedEspId);
        console.log("Type: " + selectedType);
        console.log("Mode: " + selectedMode);

        if ((payload === "") || (nmValue === null) || (selectedEspId === undefined) || (selectedAlias === "") || (selectedType === undefined) || (selectedMode === null)) {alert("Nickname is empty or no device/type/mode selected!");} else {
            var doc = ConfiguredDevicesCollection.findOne({deviceId: selectedEspId});
            if (doc === undefined) {ConfiguredDevicesCollection.insert({deviceId: selectedEspId, alias: selectedAlias, type: selectedType, mode: selectedMode});} else {
                ConfiguredDevicesCollection.update({_id: doc._id}, {$set: {alias: selectedAlias, type: selectedType, mode: selectedMode}});
            }

            Meteor.call('mqttPublish', {
                topic: 'smartgarden/commands/' + selectedEspId + '/soil',
                payload: payload
            }, (err, res) => {
                if (err) {
                    alert(err);
                } else {
                    console.log('success')
                }
            })

            Meteor.call('mqttPublish', {
                topic: 'smartgarden/commands/' + selectedEspId + '/automatic',
                payload: JSON.stringify({
                    'irrigation': 'true',
                    'light': 'true'
                })
            }, (err, res) => {
                if (err) {
                    alert(err);
                } else {
                    console.log('success')
                }
            })

            Meteor.call('mqttPublish', {
                topic: 'smartgarden/commands/' + selectedEspId + '/light',
                payload: JSON.stringify({
                    'minLX': 500,
                    'nm': nmValue
                })
            }, (err, res) => {
                if (err) {
                    alert(err);
                } else {
                    console.log('success')
                }
            })
        }
    }


    if ((plantTypes.length <= 0) || (espIds.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 autoComplete='off'>
                        <Form.Group>
                            <Form.Label>Name:</Form.Label>
                            <Form.Control
                                type="text"
                                id="alias"
                                autoFocus ref={(input) => {this.nameInput=(input)}}
                                placeholder="Enter a device nickname..."
                                onChange={handleChangeAlias}/>
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>Device:</Form.Label>
                            <Form.Control as="select" type="text" onChange={handleChangeDevice}>
                                <option></option>
                                {espIds.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>
                        <Form.Group>
                            <Form.Label>Mode:</Form.Label>
                            <Form.Control as="select" type="text" onChange={handleChangeMode}>
                                <option></option>
                                <option key="0" value="Growth">Growth</option>
                                <option key="1" value="Bloom">Bloom</option>
                            </Form.Control>
                        </Form.Group>
                        <Button type={"sendData"} onClick={handleSendData} >Send</Button>
                    </Form>

                </Container>

            </>
        )
    }
}