# based on wifi_setup module
import dialogs, ugfx, network, badge, deepsleep

# after_callback takes (name_of_ssid, sta_if)
def chooseSSID(prompt, after_callback, sta_if=None):
    ugfx.init()
    ugfx.input_init()

    ugfx.clear(ugfx.WHITE)
    ugfx.string(100,50,'Scanning...','Roboto_Regular18',ugfx.BLACK)
    ugfx.flush()

    if sta_if is None:
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)
    scanResults = sta_if.scan()

    ssidSet = set([ AP[0] for AP in scanResults ])

    ugfx.clear(ugfx.WHITE)
    ugfx.string(10,20,'Found %d' % len(ssidSet),'Roboto_Regular18',ugfx.BLACK)
    ugfx.string(10,40,'Networks','Roboto_Regular18',ugfx.BLACK)
    ugfx.string(10,60,'A=PICK','Roboto_Regular18',ugfx.BLACK)
    ugfx.string(10,80,'B=RESCAN','Roboto_Regular18',ugfx.BLACK)
    options = ugfx.List(ugfx.width()-int(ugfx.width()/1.5),0,int(ugfx.width()/1.5),ugfx.height())

    for ssid in ssidSet:
        options.add_item(ssid)

    ugfx.input_attach(ugfx.BTN_A, lambda pushed: _connectClick(options, pushed, after_callback, sta_if))
    ugfx.input_attach(ugfx.BTN_B, lambda pushed: chooseSSID(prompt, after_callback, sta_if))
    ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush() if pushed else 0)
    ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush() if pushed else 0)
    ugfx.flush()

def _connectClick(options, pushed, after_callback, sta_if):
    if pushed:
        selected = options.selected_text()
        ugfx.input_attach(ugfx.BTN_A, None)
        ugfx.input_attach(ugfx.BTN_B, None)
        ugfx.clear(ugfx.WHITE)
        ugfx.string(100,50,'Starting monitor!','Roboto_Regular18',ugfx.BLACK)
        ugfx.flush()
        after_callback(selected, sta_if)
