import ugfx, wifi, appglue
import time, urandom
from umqtt.simple import MQTTClient


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.string(10,10,"Connecting to MQTT...","Roboto_Regular12", 0)
ugfx.flush()


pizzaoven0 = "0"
pizzaoven1= "1"


def sub_cb(topic, msg):
    global pizzaoven0
    global pizzaoven1
    msg = msg.decode('utf-8')
  
    if topic.decode('utf-8') == 'pizza/temp0':
        pizzaoven0 = msg
    if topic.decode('utf-8') == 'pizza/temp1':
        pizzaoven1 = msg

    ugfx.clear(ugfx.WHITE)
    
    if float(pizzaoven0) < 100 or float(pizzaoven1) < 100:
        ugfx.string_box(0,10,296,26, "STILL", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
        ugfx.string_box(0,45,296,38, "prepping dough", "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter) 
        ugfx.string_box(0,94,296,26, "Anyway", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
    else:
        ugfx.string(0, 0,  "Still baking anyway", "PermanentMarker22", ugfx.BLACK)
        ugfx.string(0, 30, "Pizza oven 1: {} C".format(pizzaoven0), "Roboto_Black22", ugfx.BLACK)
        ugfx.string(0, 50, "Pizza oven 2: {} C".format(pizzaoven1), "Roboto_Black22", ugfx.BLACK)
        ugfx.string(0, 90, "Please volunteer!", "Roboto_Black22", ugfx.BLACK)

    ugfx.flush()

def main(server="mqtt.sha2017.org"):
    clientname = 'SHA2017Badge ' + str(urandom.getrandbits(30))
    c = MQTTClient(clientname, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"pizza/#")
    c.check_msg()
    while True:
        c.check_msg()
        time.sleep(1)
    c.disconnect()
    
def go_home(pushed):
    if pushed:
        appglue.home()


ugfx.input_attach(ugfx.BTN_B, go_home)
main()