#!C:\Users\Thomas MONZIE\AppData\Local\Programs\Python\Python36\python.exe
import heatzy
import argparse
import sys
import time
import paho.mqtt.client
import threading
import logging

# Fonction (threadee) de notification
def update_state(mqttClient, heatzy_devices, refresh):
    while True:
        for device in heatzy_devices:
            topicString = 'home/heatzy/'+device+'/state'
            mqttClient.publish(topicString, heatzy_devices[device].status())
            print(topicString+':'+heatzy_devices[device].mode)

        time.sleep(refresh)

# Fonction de callback de connexion
def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.connected_flag = True
        print("connected OK Returned code=",rc)
        # Souscription aux cannaux
        for device in client.heatzy_devices:
            topicString = 'home/heatzy/'+device+'/set'
            client.subscribe(topicString,qos=0)
            print('Souscription au topic '+topicString)

    else:
        client.bad_connection_flag = True
        print("Bad connection Returned code=",rc)

# Fonction de callback de message
def on_message(client, userdata, message):
    topic = message.topic.split('/')
    instruction = message.payload.decode("utf-8")
    print(instruction)
    print(topic)

    if instruction == 'ON':
        print('Allumage de '+topic[2])
        client.heatzy_devices[topic[2]].confort()

    else:
        print('Passage en hors gel de '+topic[2])
        client.heatzy_devices[topic[2]].horsgel()

def main():
    parser = argparse.ArgumentParser(description='Controls Heatzy devices throught the CLI')
    parser.add_argument('-u', '--username', help="Username on the Heatzy (Gizwits) platform")
    parser.add_argument('-p', '--password', help="Password of the user")
    parser.add_argument('-s', '--server', help="Broker IP or hostname")
    parser.add_argument('-i', '--port', help="Broker MQTT Port (default : 1883)", default=1883, type=int)
    parser.add_argument('-r', '--refresh', help="Refresh rate of the state in seconds (default : updates every 60 seconds)", default=60, type=float)
    parser.add_argument('-m', '--offmode', help="Sets off mode to this (default = 'ECO')", default='ECO')
    # TODO : Proposer l'édition du topic
    # parser.add_argument('-t', '--topic', help="Base topic for MQTT broker", default='')

    args = parser.parse_args()

    # TODO Vérification des arguments:

    if args.server and args.password and args.username:
        hh = heatzy.heatzy.HeatzyHandler(args.username, args.password)
        devicesDict = hh.getHeatzyDevices()

        # Création du client
        mqttClient = paho.mqtt.client.Client('heatzy_mqtt')
        mqttClient.connected_flag = False       # On attache les flags de connexion
        mqttClient.bad_connection_flag = False
        mqttClient.heatzy_devices = devicesDict # On attache les devices Heatzy
        mqttClient.off_mode = args.offmode

        mqttClient.on_connect = on_connect # Binding du callback de on_connect
        mqttClient.on_message = on_message # Binding du callback de on_connecth

        # Créer ensuite la connexion au broker
        mqttClient.connect(args.server, port=args.port, keepalive=60, bind_address='')
        # Début de la boucle
        mqttClient.loop_start()
        while not mqttClient.connected_flag and not mqttClient.bad_connection_flag:
            print('Connecting to '+args.server+' on port '+str(args.port)+'...')
            time.sleep(1)
        
        # Démarre le thread de notification...
        threading.Thread(target=update_state, args=(mqttClient,devicesDict, args.refresh)).start()

        # Boucle en attendant la suite
        mqttClient.loop_forever()

    else:
        parser.print_help()

if __name__ == "__main__":
    main()