import ugfx, gc, wifi, badge, 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_Price(pushed):
    if(pushed):
        ugfx.string(10,10,"Downloading JSON","Roboto_Regular12", 0)
        ugfx.flush()
        gc.collect()
        try:
            data = requests.get("https://api.kraken.com/0/public/Ticker?pair=ETHEUR")
        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=''
    price=float(output['result']['XETHZEUR']['c'][0])
    opening=float(output['result']['XETHZEUR']['o'])
    
    if price > opening:
      buystr='UP'
    else :
      buystr = 'DOWN'
    
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    ugfx.string_box(0,10,296,26, "ETH Price", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0,35,296,38, str(output['result']['XETHZEUR']['b'][0])+ " EUR", "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0,74,296,26, "Trend: "+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_Price(1)

def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)

ugfx.input_attach(ugfx.BTN_A, get_Price)
ugfx.input_attach(ugfx.BTN_B, go_home)
main()