import network
import time


def connect() -> network.WLAN:
    """
    Connects to the WLAN as configured in wlan_cfg.py.
    Returns after the connection is established.
    """
    try:
        import wlan_cfg
    except Exception as e:
        print('[wlan_manager] Could not import wlan_cfg.py: {}'.format(str(e)))
        print('[wlan_manager] Defaulting to access point mode')
        wlan = network.WLAN(network.AP_IF)
        wlan.active(True)
        return wlan

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    if not wlan.isconnected():
        wlan.connect(wlan_cfg.SSID, wlan_cfg.PASSWORD)

        print('[wlan_manager] Connecting to WLAN "{}" '.format(wlan_cfg.SSID), end='')
        while not wlan.isconnected():
            print('.', end='')
            time.sleep(1)
        print('\n[wlan_manager] Connected!')
    else:
        print('[wlan_manager] Already connected to WLAN "{}"'.format(wlan.config('essid')))

    # Static IP configuration if IFCONFIG is not None
    if wlan_cfg.IFCONFIG:
        wlan.ifconfig(wlan_cfg.IFCONFIG)

    print('[wlan_manager] IP config: {}'.format(wlan.ifconfig()))
    return wlan
