import wifi, audio, time, system, appconfig, keypad, machine, display, touchpads, sndmixer

vol = machine.nvs_getint('system', 'volume')
if vol == None:
    vol = 255;

settings = appconfig.get("radio", {
 "0" : {"url" : "https://icecast-bnr-cdp.triple-it.nl/bnr_mp3_128_03?.mp3", "color" : "#FFD200"},
 "1" : {"url" : "http://icecast-qmusicnl-cdp.triple-it.nl/Qmusic_nl_live_96.mp3", "color" : "#ED3624"},
 "2" : {"url" : "http://21253.live.streamtheworld.com/RADIO538.mp3", "color" : "#82B902"},
 "3" : {"url" : "http://stream.100p.nl/100pctnl.mp3", "color" : "#EF7D00"},
 "4" : {"url" : "http://media1.onswestbrabant.nl:8000/OWBLiveMP3#.mp3", "color" : "#70A32E"},
 "5" : {"url" : "https://ice.cr5.streamzilla.xlcdn.com:8000/sz=efteling=hdstream?.mp3", "color" : "#B71234"},
 "6" : {"url" : "", "color" : ""},
 "7" : {"url" : "", "color" : ""},
 "8" : {"url" : "", "color" : ""},
 "9" : {"url" : "", "color" : ""},
 "10" : {"url" : "", "color" : ""},
 "11" : {"url" : "", "color" : ""},
 "12" : {"url" : "", "color" : ""},
 "13" : {"url" : "", "color" : ""},
 "14" : {"url" : "", "color" : ""},
 "15" : {"url" : "", "color" : ""},
 "16" : {"url" : "", "color" : ""}
})

for z in range(0,16):
    if settings[str(z)]["url"] != "":
        x, y = z % 4, int(z / 4)
        color = int(settings[str(z)]["color"].replace("#","0x"),16)
        display.drawPixel(x, y, color)    
display.flush();

if not wifi.status():
    audio.play('/cache/system/wifi_connecting.mp3')
    wifi.connect()
    wifi.wait()
    if not wifi.status():
        audio.play('/cache/system/wifi_failed.mp3')
        time.sleep(6)
        system.launcher()

stationId = machine.nvs_getint("radio", "stationId")    
if stationId == None:
	stationId = 0
if settings[str(stationId)]["url"] == "":
    stationId = 0
print("Start: ", settings[str(stationId)]["url"])
audio.play(settings[str(stationId)]["url"], vol)

def on_key(key_index, is_pressed):
    if is_pressed and settings[str(key_index)]["url"] != "":
        machine.nvs_setint("radio", "stationId", key_index)
        system.start('better_radio')
        
keypad.add_handler(on_key)


# volume control
is_down = False;
def vol_up(is_pressed):
    global vol
    if is_pressed:
        vol += 32
        if vol > 255:
            vol = 255
        setvolume(vol)

def vol_down(is_pressed):
    global vol
    if is_pressed:
        vol -= 32
        if vol < 0:
            vol = 0
        setvolume(vol)
        
def setvolume(volume):
    print(volume)
    for index in audio.handles.keys():
        sndmixer.volume(index, volume)


touchpads.on(touchpads.RIGHT, vol_up)
touchpads.on(touchpads.LEFT, vol_down)