import os
import paho.mqtt.client as mqtt
from influxdb_client import InfluxDBClient
from influxdb_client import Point
from influxdb_client.client.write_api import SYNCHRONOUS
import json

import logging
logging.basicConfig(level=logging.DEBUG)
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client()
influx_client = InfluxDBClient(url="http://localhost:8086", token="bjzIaf-hQU6eUf7-Sk9XvmjPNBG6EXuYg6iEjFhHfd2ggdqtL_5WpQxKBCRxWChB31YYXPoVrG2X0faoTZl1Eg==", org="sensors")
write_api = influx_client.write_api(write_options=SYNCHRONOUS)

def messageReceived(client, userdata, message):
    print("received topic" + str(message.topic) + "with payload:" + str(message.payload)) 
    message_as_json = json.loads(message.payload.decode("utf-8"))
   
    #extract fields from json
    CmToWater =  float(message_as_json["uplink_message"]["decoded_payload"]["CmToWater"])
    Temperature1 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp1"])
    Temperature2 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp2"])
    Temperature3 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp3"])
    Temperature4 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp4"])
    Temperature5 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp5"])
    Temperature6 = float(message_as_json["uplink_message"]["decoded_payload"]["Temp6"])
    
    Datapoint = Point("environment_measurement")\
    .field("CmToWater", CmToWater)\
    .field("Temperature1", Temperature1)\
    .field("Temperature2", Temperature2)\
    .field("Temperature3", Temperature3)\
    .field("Temperature4", Temperature4)\
    .field("Temperature5", Temperature5)\
    .field("Temperature6", Temperature6)\

    print("writing Datapoint", Datapoint)
    write_api.write("abfd776339848ad0", "cccp", Datapoint)

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    
    if (rc == 0):
        print("(Success)")
    else: 
        print("(Fail)")

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("#", 0)

appid = "freiland-sensors@ttn"
key = "NNSXS.LDAC6EEMEJNHGGWH44PKTWVB4VJWR7BAOS4CQJY.G7IEQBYOANUEMBGWOLL6WRC6QXYSFWJZLK2GK6J2Z6TNYFT73EEA"
devid = "board1" 

mqttc.username_pw_set(appid, key)
mqttc.on_message = messageReceived
mqttc.on_connect = on_connect
mqttc.connect("eu1.cloud.thethings.network", 1883, 60)


mqttc.loop_forever()