import ugfx, gc, wifi, badge, deepsleep, urandom, network
import urequests as requests
from time import *

ugfx.init()
ugfx.LUT_FULL
ugfx.input_init()

# 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():
    sleep(0.1)
    pass

ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()

def load_tickets(pushed):
    if(pushed):
        ugfx.string(10,10,"Downloading JSON","Roboto_Regular12", 0)
        ugfx.flush()
        gc.collect()
        try:
            data = requests.get("https://tickets.sha2017.org/status.json")
        except:
            ugfx.string(10,10,"Could not download JSON","Roboto_Regular12", 0)
            ugfx.flush()
            sleep(1)
            go_home(1)
            return
        try:
            global ticketsales
            ticketsales = data.json()
        except:
            data.close()
            ugfx.string(10,10,"Could not decode JSON","Roboto_Regular12", 0)
            ugfx.flush()
            sleep(1)
            go_home(1)
            return
        data.close()
    
    print("Rendering list...")
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
   
    lastorder = str(ticketsales['last_order'])
    lastorder,leftover = lastorder.split('.')
    lastdate,lasttime=lastorder.split(' ')

    ugfx.string(35,10,str(ticketsales['ordered'])+" tickets ordered","Roboto_BlackItalic24",ugfx.BLACK)
    ugfx.string(10,40,str(ticketsales['tickets_left'])+" remaining","PermanentMarker36",ugfx.BLACK)
    ugfx.string(45,85,"tickets.sha2017.org","Roboto_Black22",ugfx.BLACK)
    ugfx.string(180,116,lastdate+" "+lasttime,"Roboto_Regular12",ugfx.BLACK)
    ugfx.flush()

def main():
    load_tickets(1)
    
def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)
        
ugfx.input_attach(ugfx.BTN_A, load_tickets)
ugfx.input_attach(ugfx.BTN_B, go_home)
main()