import paho.mqtt.client as mqtt
import sqlite3 # import sqlite
from datetime import date, datetime
import json

# function to connect with topic
def on_connect(client, userdata, flags, rc):  # client method to connect

    if rc == 0:
        print("connected OK Returned code=", rc)  # let us know we connected to the broker

        # TOPICS MUST BE ADDED HERE
        client.subscribe("smarthouse/temp/data")
    else:
        print("Bad connection Returned code=", rc)  # if we can't connect


# function to receive messages
def on_message(client, userdata, msg,):  # client method to get messages from topic
    topic = msg.topic  # for use when we can't decode

    try:
        day = date.today()  # date function call
        clock = datetime.now()  # time function calls
        time_time = clock.strftime("%H:%M:%S") # Just in H-M-S format

        # DECODING CODE GOES HERE FOR EACH SEPARATE TOPIC
        if topic == "smarthouse/temp/data":                   # decodes message from specific topic (sensors)
            data = json.loads(msg.payload.decode("utf-8"))       # decode message, turns it back into array 'data'

            # insert data into database
            connect_db = sqlite3.connect('Database/database.db') # connect to database
            cursor = connect_db.cursor()                         # define cursor
            # transfer data from array to new row in the temperature_sensors table
            cursor.execute("""UPDATE temperature_sensors
                                SET DATE = ?, TIME = ?, TEMPERATURE = ?
                                WHERE ID = ?;""", (data[1], data[2], data[4], data[0]))

            connect_db.commit() # commit changes to database
            connect_db.close()  # close database
        

	# print message with data, time and date to check if it is received and decoded
        print("Received message at : date-" + str(day) + " time-" + str(time_time) + " / data: topic: " + topic + ";  value: \n"
              '''+ str(data)''')
        


             



    except:
        print("Cannot decode data on topic:" + topic)  # cannot decode; print the topic for the non-decodable message

#define client
client = mqtt.Client()

#callback functions
client.on_connect = on_connect
client.on_message = on_message

client.connect("broker.hivemq.com", 1883)  # connect to the broker on an appropriate port

client.loop_forever()  # keep looping forever (allows realtime subscription)