import audio, ugfx, badge, virtualtimers, easywifi, time

url = 'https://lainon.life/radio/{}.mp3'
stations = ('everything', 'cafe', 'cyberia', 'swing')
ugfx.set_lut(ugfx.LUT_NORMAL)
ugfx.orientation(90)
w_tot, h_tot = ugfx.width(), ugfx.height()
station = None

def ugfx_draw():
    global station
    ugfx.clear(ugfx.WHITE)
    ugfx.string_box(0, int(h_tot * .75), w_tot, int(h_tot * .2),
            "Volume: {}".format(audio.volume()),
            "Roboto_Black9", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0, int(h_tot * .4), w_tot, int(h_tot * .2),
            "Everything\n{}\n|".format("O" if station == 0 else "T"),
            "Roboto_Black9", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0, h_tot // 2, w_tot // 2, int(h_tot * .2),
            "Cyberia {}-".format("O" if station == 2 else "<"),
            "Roboto_Black9", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(w_tot // 2, h_tot // 2, w_tot // 2, int(h_tot * .2),
            "-{} Cafe".format("O" if station == 1 else ">"),
            "Roboto_Black9", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.string_box(0, int(h_tot * .6), w_tot, int(h_tot * .2),
            "|\n{}\nSwing".format("O" if station == 3 else "V"),
            "Roboto_Black9", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.flush()

def turn_off(pressed):
    global station
    if audio.is_playing():
        audio.stop()
        station = None
    while audio.is_playing():
        time.sleep(0.05)

def switch_station(index):
    def switch_closure(pressed):
        global station
        if pressed:
            final_url = url.format(stations[index])
            print("URL: ", final_url)
            if audio.is_playing():
                turn_off(True)
            audio.play_mp3_stream(final_url)
            station = index
        ugfx_draw()

    return switch_closure

def btn_volume_down(pressed):
    if pressed:
        audio.volume(audio.volume()-1)
    ugfx_draw()

def btn_volume_up(pressed):
    if pressed:
        audio.volume(audio.volume()+1)
    ugfx_draw()

def go_home(pushed):
    if pushed:
        badge.leds_send_data(bytes([0] * 24))
        badge.leds_disable()
        ugfx.set_lut(ugfx.LUT_FULL)
        ugfx.clear(ugfx.BLACK)
        ugfx.flush()
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()
        import machine
        machine.deepsleep(1)

ugfx.input_attach(ugfx.JOY_UP, switch_station(0))
ugfx.input_attach(ugfx.JOY_DOWN, switch_station(3))
ugfx.input_attach(ugfx.JOY_LEFT, switch_station(2))
ugfx.input_attach(ugfx.JOY_RIGHT, switch_station(1))
ugfx.input_attach(ugfx.BTN_B, btn_volume_down)
ugfx.input_attach(ugfx.BTN_A, btn_volume_up)
ugfx.input_attach(ugfx.BTN_SELECT, turn_off)
ugfx.input_attach(ugfx.BTN_START, go_home)

def wifiTask():
    if not easywifi.status():
        easywifi.enable()
    return 5000

wifiTask()
ugfx_draw()

virtualtimers.activate(25)
virtualtimers.new(0, wifiTask)
