import ugfx, wifi, appglue, badge, ubinascii, uos
import time, json
import urequests as requests
from umqtt.simple import MQTTClient

apiurl = "http://hotglue.tech:5000/api/get/current"

ugfx.init()
ugfx.LUT_FULL
ugfx.input_init()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
# Make sure WiFi is connected
wifi.init()

ugfx.clear(ugfx.WHITE);
ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
ugfx.flush()

# Wait for WiFi connection
while not wifi.sta_if.isconnected():
    time.sleep(0.1)
    pass


ugfx.clear(ugfx.WHITE);
ugfx.flush()

clientname = 'SHA2017Badge' + str(ubinascii.hexlify(uos.urandom(5)))
host = "mqtt.devlol.org"
topic = "elephant/fart/relay/0"

c = MQTTClient(clientname,host)
c.connect()

beer = "-"


def main():
    print ("updating")
    ugfx.string(0,0,".","Roboto_Regular12", 0)
    ugfx.flush()
    try:
        response = requests.get(apiurl).json()
        beer = str(int(response['total']))
    except:
        beer = "?"
    ugfx.clear(ugfx.WHITE);
    ugfx.string(0, 20,  "Koeniglich Bayrisches ", "PermanentMarker22", ugfx.BLACK)
    ugfx.string(0, 40,  "Amtsvillage", "PermanentMarker22", ugfx.BLACK)
    ugfx.string(0, 70, "Bier gezapft: {}l".format(beer), "Roboto_Black22", ugfx.BLACK)
    ugfx.flush()
    time.sleep(5)

def btn_a(pressed):
        if pressed:
            print ("huuuup")
            c.publish(topic, "1")

def go_home(pushed):
    if pushed:
        appglue.home()


ugfx.input_attach(ugfx.BTN_B, go_home)
ugfx.input_attach(ugfx.BTN_A,lambda pressed: btn_a(pressed))
ugfx.clear(ugfx.WHITE);
ugfx.flush()
while True:
    main()
