import machine, wifi, urequests, sndmixer, gc
import easydraw, ugfx

ugfx.clear(ugfx.WHITE)
ugfx.flush()
easydraw.messageCentered('Initialising stream', True)

wifi.connect()
wifi.wait()

gc.collect()
url = 'https://relay0.r-a-d.io/main.mp3'
stream = urequests.get(url)
gc.collect()
sndmixer.begin(1)
player = sndmixer.mp3_stream(stream.raw)
sndmixer.volume(player, machine.nvs_getint('system', 'volume') or 5)

PreviousNowPlaying = 1

ugfx.clear(ugfx.WHITE)
ugfx.flush()
easydraw.messageCentered('Now Playing r-a-d.io', True)

## These API calls seem to timeout whilst playing audio, so are currently disabled.

# import time

# while 1:
# 	gc.collect()
# 
# 	#Get R/a/dio data from API
# 	parsed = urequests.get('http://r-a-d.io/api').json()  # No HTTPS here because there isn't enough DRAM for 2 uSSL sockets
# 
# 	#parse DJ and Song name
# 	DJname = parsed["main"]["dj"]["djname"]
# 	NowPlaying = parsed["main"]["np"]
# 
# 	gc.collect()
# 
# 	if PreviousNowPlaying != NowPlaying:
# 
# 		#Clear Display
# 		ugfx.clear(ugfx.WHITE)
# 		ugfx.flush()
# 
# 		logo = '/lib/Radio/RadioLogo.png'
# 
# 		easydraw.messageCentered('DJ: %s\n\n%s' % (DJname, NowPlaying), True)
# 
# 		ugfx.flush()
# 
# 	time.sleep(10)
# 	PreviousNowPlaying = NowPlaying