#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

import logging
from waveshare_epd import epd2in13d
import time
from PIL import Image,ImageDraw,ImageFont
import traceback
from paho.mqtt import client as mqtt_client
import paho.mqtt.client as paho

logging.basicConfig(level=logging.INFO)

Connected = False   #global variable for the state of the connection

broker = "192.168.99.224"
port = 1883
topic_wHouseConsumption = "openWB/global/WHouseConsumption"
topic_pvProduction = "openWB/pv/W"
topic_energyImportExport = "openWB/evu/W"
topic_houseBatterySoC = "openWB/housebattery/%Soc"
topic_houseBatteryLoadUnload = "openWB/housebattery/W"

username = "mqtt-user"
pw = "phio6yiR9ohs1veeghu4WaeGhaiRi8he4EiWasheev4faeku8tohdiuthah7zahP"
client_id = "solarmonitor"

try:
    epd = epd2in13d.EPD()
    logging.debug("init and Clear")
    epd.init()
    epd.Clear()
    #time.sleep(1)

except IOError as e:
    logging.info(e)
    
except KeyboardInterrupt:    
    logging.info("ctrl + c:")
    epd.Clear()
    epd2in13d.epdconfig.module_exit()
    exit()

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        logging.info("Connected to MQTT Broker!")

        global Connected                #Use global variable
        Connected = True                #Signal connection 
    else:
        logging.debug("Failed to connect, return code %d\n", rc)

def on_message(client, userdata, msg):
    global value_pvProduction
    global value_wHouseConsumption
    global value_energyImportExport
    global value_houseBatterySoC
    global value_houseBatteryLoadUnload

    if msg.topic == "openWB/pv/W":
        value_pvProduction = int(msg.payload.decode())
        value_pvProduction = -value_pvProduction
    elif msg.topic == "openWB/global/WHouseConsumption":
        value_wHouseConsumption = int(msg.payload.decode())
    elif msg.topic == "openWB/evu/W":
        value_energyImportExport = int(msg.payload.decode())
    elif msg.topic == "openWB/housebattery/%Soc":
        value_houseBatterySoC = int(msg.payload.decode())
    elif msg.topic == "openWB/housebattery/W":  
        value_houseBatteryLoadUnload = int(msg.payload.decode())

client = mqtt_client.Client(client_id, protocol=paho.MQTTv31)
client.username_pw_set(username, password=pw)
client.on_connect = on_connect

value_pvProduction = 0
value_wHouseConsumption = 0
value_energyImportExport = 0
value_houseBatterySoC = 0
value_houseBatteryLoadUnload = 0

client.on_message = on_message

client.connect(broker, port=port)

client.loop_start()        #start the loop
  
while Connected != True:    #Wait for connection
    time.sleep(1)

client.subscribe(topic_wHouseConsumption)
client.subscribe(topic_pvProduction)
client.subscribe(topic_energyImportExport)
client.subscribe(topic_houseBatterySoC)
client.subscribe(topic_houseBatteryLoadUnload)

try:
    while True:
        logging.debug("Drawing")
        font10 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12)
        
        HBlackimage = Image.new('1', (epd.height, epd.width), 255)  # 298*126
        #HRedimage = Image.new('1', (epd.height, epd.width), 255)  # 298*126  ryimage: red or yellow image  
        drawblack = ImageDraw.Draw(HBlackimage)
        #drawred = ImageDraw.Draw(HRedimage)
        drawblack.text((5, 0), 'PV Produktion', font = font10, fill = 0)
        #if value_pvProduction < value_wHouseConsumption:
            #drawred.text((5, 15), 'Hausverbrauch', font = font10, fill = 0)
        #else:
        drawblack.text((5, 15), 'Hausverbrauch', font = font10, fill = 0)
        if value_energyImportExport > 0:
            drawblack.text((5, 30), 'Strom Import', font = font10, fill = 0)
        else:
           drawblack.text((5, 30), 'Strom Export', font = font10, fill = 0) 

        drawblack.text((5, 45), 'Batterie', font = font10, fill = 0)
        if value_houseBatteryLoadUnload > 0:
            drawblack.text((5, 60), 'Batterie Laden', font = font10, fill = 0)
        else:
            drawblack.text((5, 60), 'Batterie Entladen', font = font10, fill = 0)

        logging.info("-----")
        logging.info("PvProd: "+str(value_pvProduction))
        logging.info("HouseU: "+str(value_wHouseConsumption))
        logging.info("EneI/E: "+str(value_energyImportExport))
        logging.info("BatSoC: "+str(value_houseBatterySoC))
        logging.info("BatI/O: "+str(value_houseBatteryLoadUnload))
        drawblack.rectangle((150, 0, 220, 50), fill = 255)
        drawblack.text((150, 0), str(value_pvProduction) + " W", font = font10, fill = 0)
        drawblack.rectangle((150, 15, 220, 50), fill = 255)
        #if value_pvProduction < value_wHouseConsumption:
            #drawred.text((150, 15), str(value_wHouseConsumption) + " W", font = font10, fill = 0)
        #else:
        drawblack.text((150, 15), str(value_wHouseConsumption) + " W", font = font10, fill = 0)
        drawblack.rectangle((150, 30, 220, 50), fill = 0)
        #if value_energyImportExport > 0:
            #drawred.text((150, 30), str(value_energyImportExport) + " W", font = font10, fill = 0)
        #else:    
        drawblack.text((150, 30), str(value_energyImportExport) + " W", font = font10, fill = 0)
        drawblack.rectangle((150, 45, 220, 50), fill = 255)
        drawblack.text((150, 45), str(value_houseBatterySoC) + " %", font = font10, fill = 0)
        drawblack.rectangle((150, 60, 220, 50), fill = 255)
        #if value_houseBatteryLoadUnload > 0:
        drawblack.text((150, 60), str(value_houseBatteryLoadUnload) + " W", font = font10, fill = 0)
        #else:
            #drawred.text((150, 60), str(value_houseBatteryLoadUnload) + " W", font = font10, fill = 0)
        
        epd.DisplayPartial(epd.getbuffer(HBlackimage))
        time.sleep(10)
  
except KeyboardInterrupt:
    logging.info("exiting")
    client.disconnect()
    client.loop_stop()
