import ugfx, wifi, badge, random
import urequests as requests
from time import sleep

ugfx.init()
ugfx.set_lut(ugfx.GREYSCALE)
ugfx.input_init()

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()

while not wifi.sta_if.isconnected():
	sleep(0.1)

ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.string(10, 10, "Loading first image...", "Roboto_Regular12", 0)

def go_home(pushed):
	if (pushed):
		import machine
		machine.deepsleep(1)

def fetchImage():
	imageMin = 1
	imageMax = 143
	imageID = random.randint(imageMin, imageMax)
	try:
		data = requests.get("https://poly.nomial.co.uk/rms/eink/" + str(imageID) + ".eink")
	except:
		return 0
	
	# waiting on this PR: https://github.com/SHA2017-badge/micropython-esp32/pull/156
	badge.eink_raw_frame(data, ugfx.GREYSCALE)
	return 1

ugfx.input_attach(ugfx.BTN_B, go_home)

while 1:
	if fetchImage():
		sleep(10)
	else:
		sleep(2)