import React from 'react';
import { Meteor } from 'meteor/meteor';
import ReactDOM from 'react-dom';
import App from '../imports/ui/App';
import 'bootstrap/dist/css/bootstrap.min.css';
import startMqttObserver from "../mongo-mqtt";
import {publish} from "../imports/api/mqttApi";

export const PlantTypesCollection = new Meteor.Collection('plantTypes');
export const SensorDataCollection = new Meteor.Collection('sensorData');
export const ActiveDeviceCollection = new Meteor.Collection('activeDevice');
export const ConfiguredDevicesCollection = new Meteor.Collection('configuredDevices');

Meteor.startup(() => {
  // If this code is on the meteor server-side, publish all MongoDB collections for the client-side,
  // start the mqtt-observer script to push data to the database and define the mqttPublish method to be accessible from the client-side.
  if(Meteor.isServer) {
    Meteor.publish('plantTypesCollection', function() {
      return PlantTypesCollection.find();
    })

    Meteor.publish('sensorDataCollection', function() {
      return SensorDataCollection.find();
    })

    Meteor.publish('activeDeviceCollection', function() {
      return ActiveDeviceCollection.find();
    })

    Meteor.publish('configuredDevicesCollection', function() {
      return ConfiguredDevicesCollection.find();
    })

    startMqttObserver()

    Meteor.methods({
      'mqttPublish'({ topic, payload }) {
        publish(topic, payload)
      }
    })
  }

  // If this code is on the meteor client-side, subscribe all published MongoDB collections from the server-side and render the application.
  if (Meteor.isClient) {
    Meteor.subscribe('plantTypesCollection');
    Meteor.subscribe('sensorDataCollection');
    Meteor.subscribe('activeDeviceCollection');
    Meteor.subscribe('configuredDevicesCollection');

    ReactDOM.render(<App />, document.getElementById('root'));
  }
});