import ugfx, badge
import utime
import ujson

ugfx.init()
ugfx.input_init()

def home(pressed):
	if pressed:
		import appglue
		appglue.home()

ugfx.input_attach(ugfx.BTN_B, home)
ugfx.input_attach(ugfx.BTN_START, home)

def display_daysuntil(prefix, days, name):
	ugfx.clear(ugfx.BLACK)
	ugfx.flush()
	ugfx.clear(ugfx.WHITE)
	ugfx.string_box(0,10,296,26, prefix, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
	ugfx.string_box(0,40,296,38, "%i Days" % days, "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
	ugfx.string_box(0,90,296,26, "until %s" % name, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
	ugfx.flush()

def read_jsonfile(filename):
	try:
		with open(filename,'r') as fh:
			return(ujson.loads(fh.read()))
	except:
		return false

def load_event(e):
	if e['time'] < utime.time():
		return False
	prefix = "still"
	if('prefix' in e):
		prefix = e['prefix']
	elif ((e['time'] - 2592000) < utime.time()):
		prefix = "only"
	display_daysuntil(prefix, (e['time']-utime.time()) / 86400, e['name'])
	return True

def run():
	events = read_jsonfile("/lib/daysuntil/events.json")
	if (events):
		while True:
			for e in events:
				load_event(e) and utime.sleep(10)
				if (badge.battery_volt_sense() < 4000):
					import appglue
					appglue.home()
					return

run()



