import ugfx, gc, wifi, badge, deepsleep, urandom, network,random
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.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
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.WHITE)
ugfx.flush()

def get_btcPrice(pushed):
    if(pushed):
        ugfx.string(10,10,"Downloading JSON","Roboto_Regular12", 0)
        ugfx.flush()
        gc.collect()
        try:
            data = requests.get("https://blockchain.info/es/ticker?")
        except:
            ugfx.string(10,10,"Could not download JSON","Roboto_Regular12", 0)
            ugfx.flush()
            sleep(1)
            go_home(1)
            return
        try:
            global output
            output = data.json()
        except:
            data.close()
            ugfx.string(10,10,"Cannot understand shit","Roboto_Regular12", 0)
            ugfx.flush()
            sleep(1)
            go_home(1)
            return
        data.close()    
    print("Rendering list...")
    buystr=''
    if bool(random.getrandbits(1)):
      buystr='SELL'
    else :
      buystr = 'BUY'
    
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    ugfx.string_box(0,10,296,26, "BTC Price(last 15m avg)", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0,35,296,38, str(output['EUR']['15m'])+ " EUR", "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0,74,296,26, "Random advice: "+buystr, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0,104,296,26, "Press A to reload, B to return homescreen", "Roboto_BlackItalic20", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.flush()    

def main():
    get_btcPrice(1)

def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)

ugfx.input_attach(ugfx.BTN_A, get_btcPrice)
ugfx.input_attach(ugfx.BTN_B, go_home)
main()