#!/usr/local/opt/python/bin/python3.7
import heatzy
import argparse
import sys
import time

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('-d', '--device', help="Name of the Heatzy device you wish to control")
    parser.add_argument('-l', '--list', help="List all devices", action="store_true", default=0)
    parser.add_argument('-m', '--setmode', help="Sets the mode of the device")
    parser.add_argument('-b', '--binary', help="Binary mode : returns OFF for all modes except CONFORT", action="store_true", default=0)

    args = parser.parse_args()

    # On liste les devices
    if args.list and args.username and args.password:
        hh = heatzy.HeatzyHandler(args.username, args.password)
        deviceList = hh.getHeatzyDevices()

        for device_name in deviceList:
            print(device_name+deviceList[device_name].__str__())

    # On recherche un device
    elif args.device and args.username and args.password:
        hh = heatzy.HeatzyHandler(args.username, args.password)
        deviceList = hh.getHeatzyDevices()

        if args.device in deviceList:
            # Si définition du mode : on exécute
            if args.setmode:
                if args.setmode in heatzy.HeatzyHandler.MODES_AVAILABLE:
                    deviceList[args.device].setMode(args.setmode)
                    time.sleep(2)   # On attend 2 secondes (si on requête directement pas de mise à jour)
                else:
                    print('Mode not found', file=sys.stderr)
            # Mode binaire (Home Assistant)
            if args.binary:
                if deviceList[args.device].status() == 'CONFORT':
                    print('ON')
                else:
                    print('OFF')
            else:
                print(deviceList[args.device].__str__())
        else:
            print('Device "'+args.device+'" not found', file=sys.stderr)

    else:
        parser.print_help()

if __name__ == "__main__":
    main()