import badge, wifi, ugfx, urequests, time

# Global variables
noWifi = False
spaceOpen = False
spaceName = ''
exceptionCaught = False
wifiTries = 0
requestComplete = False

def setup():
    pass

def getSpaceInfo():
    global noWifi, spaceOpen, spaceName, exceptionCaught, requestComplete

    requestComplete = False
    try:
        exceptionCaught = False

        # You can set your own Spacestate API URL :D
        apiUrl = badge.nvs_get_str(
            "spaceapimon",
            "apiUrl",
            "https://frack.nl/spacestate/?api"
        );
        print("[SpaceAPIMon] Starting request")

        # get the API data
        apiData = urequests.get(apiUrl)

        # decode the JSON
        apiDecoded = apiData.json()

        apiData.close() # close conn

        # set the info in our global variables so the draw routine can read it
        print("[SpaceAPIMon] Setting info")
        spaceName = apiDecoded['space']
        spaceOpen = apiDecoded['state']['open']

        # We're done here. --Cave Johnson
        print("[SpaceAPIMon] Done")
    except:
        # Oops, that failed!
        print("[SpaceAPIMon] Caught exception")
        # Signal the exception to the draw routine
        exceptionCaught = True
    requestComplete = True
    return

def draw(y, sleep=2):
    global spaceOpen, spaceName, noWifi, exceptionCaught, requestComplete

    # determine if the service is enabled
    shouldRun = badge.nvs_get_u8("spaceapimon", "enabled", 0)

    # determine our update frequency
    refreshMs = int(badge.nvs_get_str("spaceapimon", "interval", '300000'))
    if (shouldRun == 0):
        # Service disabled!
        return [999999999, 0]

    print("[SpaceAPIMon] Drawing")
    # draw strings depending on state
    if (exceptionCaught):
        ugfx.string_box(
            0, y-22, 296, 22,
            'Error while checking space API',
            "Roboto_Regular18",
            ugfx.BLACK,
            ugfx.justifyLeft
        )
    elif (noWifi):
        ugfx.string_box(
            0, y-22, 296, 22,
            'Space state unknown (no wifi)',
            "Roboto_Regular18",
            ugfx.BLACK,
            ugfx.justifyLeft
        )
    elif spaceName == '': # This shouldn't happen, but happened once?
        ugfx.string_box(
            0, y-22, 296, 22,
            'Waiting for Space Info!',
            "Roboto_Regular18",
            ugfx.BLACK,
            ugfx.justifyLeft
        )
    else:
        ugfx.string_box(
            0, y-22, 296, 22,
            '%s is %s' % (spaceName, ('open' if spaceOpen else 'closed')),
            "Roboto_Regular18",
            ugfx.BLACK,
            ugfx.justifyLeft
        )

    # redraw every 1.5 seconds until we have data
    return [refreshMs if (requestComplete or noWifi) else 1500, 22]

def loop():
    global wifiTries, noWifi
    print("[SpaceAPIMon] In loop")
    # determine if we should run (service enabled?) and our refresh interval
    shouldRun = badge.nvs_get_u8("spaceapimon", "enabled", 0)
    refreshMs = int(badge.nvs_get_str("spaceapimon", "interval", '300000'))

    if (shouldRun == 0):
        # Service disabled!
        return 999999999

    # we handle (re)connecting to wifi ourselves due to some quirks
    maxWifiTries = badge.nvs_get_u8('spaceapimon', 'maxWifiTries', 20)
    if wifiTries == 0:
      wifi.init()

    # wait until wifi is up
    if not wifi.sta_if.isconnected():
        wifiTries+=1
        if (wifiTries > maxWifiTries):
            # give up, signal the draw routine there is no wifi
            print("[SpaceAPIMon] Giving up on wifi")
            noWifi = True
            wifiTries = 0
            return 999999999
        print("[SpaceAPIMon] No wifi yet")
        return 100 # wait 100ms

    # we got wifi!
    noWifi = False
    wifiTries = 0

    # Update our cached API response
    getSpaceInfo()

    # Go to sleep
    return refreshMs
