""" Bu kod MQTT den alir FireBase e atar """
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import paho.mqtt.client as mqtt
from time import sleep
import json
import sys

Fb_Coll = "color"  
def main():

    x = open("../ip.json")
    data_ = json.load(x)
    ip = data_["ip"]
    x.close()

    cred = credentials.Certificate("../Login.json")
    firebase_admin.initialize_app(cred)
    Server = ip
    db = firestore.client()

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code "+str(rc))
        client.subscribe("/blue")      
        print("Topics Subscribed Successfully")

    
    def on_message(client, userdata, msg):
        
        topic = msg.topic
        data = msg.payload.decode('UTF-8')
        print("Mqtt'den: Topic: {}, Message: {}".format(topic,data))
        
        if topic =="/blue":
            db.collection(Fb_Coll).document("color").update({ topic: data })
            

        print("SEND")
        sleep(1)

    client = mqtt.Client()
    client.connect(Server, 1883, 60)            
    client.on_connect = on_connect
    client.on_message = on_message

    client.loop_forever()  


if __name__ == "__main__":
    try:
        main()

    except KeyboardInterrupt:
        print("\nPrograms was stopped")  
        sys.exit()

