#!/usr/bin/env python3

import argparse
import re
import time
import signal
import logging
import sys
import schedule
import paho.mqtt.client as mqtt


class Zimmer:
    name = None
    automatic = None
    temperaturSet = None
    statusActual = None



zimmer = [Zimmer, Zimmer]
zimmerName =["alexander", "wohnzimmer"]


for i in range(len(zimmer)):
    zimmer[i].name = zimmerName[i]
    zimmer[i].automatic = 0
    zimmer[i].temperaturSet = 0.0
    zimmer[i].statusActual = 0


def on_connect(client, userdata, flags, rc):
    log.debug("Connected with result code " + str(rc))

    for i in zimmer:

        client.subscribe("zimmer/" + i.name + "/heizung/homeassistant/automatic")
        client.subscribe("zimmer/" + i.name + "/heizung/homeassistant/temperatur")
        client.subscribe("zimmer/" + i.name + "/heizung/homeassistant/status")
        client.subscribe("zimmer/" + i.name + "/heizung/temperatur")
        client.subscribe("zimmer/" + i.name + "/heizung/status")
#        client.subscribe("zimmer/" + i.name + "/sensoren/tuer/status")
#        client.subscribe("zimmer/" + i.name + "/sensoren/fenster/status")
#        client.subscribe("zimmer/" + i.name + "/sensoren/temperatur")

    sendReadings()



def on_publish(client, userdata, mid):
    log.debug("mid: "+str(mid))



def on_message(client, userdata, message):
    msg = message.payload.decode("utf-8")
    log.debug('received message: %s from %s', format(msg), format(message.topic))

    if message.topic.split("/", -1)[2] == "heizung":
        if message.topic.split("/", -1)[3] == "homeassistant":
            if message.topic.split("/", -1)[4] == "automatic":
                for i in zimmer:
                    if message.topic.split("/", -1)[1] == i.name:
                        i.automatic = bool(msg)
            if message.topic.split("/", -1)[4] == "temperatur":
                for i in zimmer:
                    if message.topic.split("/", -1)[1] == i.name:
                        i.temperaturSet = round(float(msg),1)
        if message.topic.split("/", -1)[3] == "status":
                for i in zimmer:
                    if message.topic.split("/", -1)[1] == i.name:
                        i.statusActual = bool(msg)


    sendReadings()

def sendReadings():
    
    for i in zimmer:

        if i.automatic:
            client.publish("zimmer/" + i.name + "/heizung/temperatur", i.temperaturSet, qos=1, retain=True)
            client.publish("zimmer/" + i.name + "/heizung/homeassistant/status", i.statusActual, qos=1, retain=True)

    log.debug('sent readings')


def terminate(signum, frame):
    log.warn('SIGTERM received. Shutting down!')
    log.info('stopping mqtt client')
    client.loop_stop()
    log.info('disconnecting mqtt client')
    client.disconnect()
    log.info('heizberry stopped all functions; exit')
    sys.exit(0)



def getArgs():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="increase output verbosity")
    return parser.parse_args()



if __name__ == '__main__':
    signal.signal(signal.SIGINT, terminate)
    args = getArgs()
    logging.basicConfig(filename='/var/log/heizberry/heizberry_control.log', level=logging.WARN, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    log = logging.getLogger('heizberry')
    if args.verbose:
        log.setLevel(logging.DEBUG)
        log.info('Loglevel set to DEBUG')
    else:
        log.setLevel(logging.WARN)

    log.debug('start mqtt client')
    client = mqtt.Client("localThermostatControl")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("192.168.1.24", 1883, 60)
    log.debug('connected mqtt client')

    client.loop_start()

    log.debug('schedule periodic readings')
    schedule.every(60).seconds.do(sendReadings)

    time.sleep(10)