import badge
import ugfx
import virtualtimers
import wifi

buienradar = __import__('lib/buienalarm/buienradar')

MSG_HEIGHT = 14
REFRESH_RATE = 5 * 60 * 1000 # 5 minutes

def refresh():
    global downpour
    try:
        downpour = buienradar.get_downpour()
        to_store = repr(downpour)
        badge.nvs_set_str('buienalarm', 'rain_cache.0', to_store[:255])
        badge.nvs_set_str('buienalarm', 'rain_cache.1', to_store[255:510])
        badge.nvs_set_str('buienalarm', 'rain_cache.2', to_store[510:])
    except:
        to_eval  = badge.nvs_get_str('buienalarm', 'rain_cache.0', '')
        to_eval += badge.nvs_get_str('buienalarm', 'rain_cache.1', '')
        to_eval += badge.nvs_get_str('buienalarm', 'rain_cache.2', '')
        if len(to_eval) > 0:
            downpour = eval(to_eval)
        else:
            downpour = []

def setup():
    refresh()

def loop():
    refresh()
    return REFRESH_RATE

def buzz():
    badge.vibrator_activate(0b1100110011)
    return 0

def draw(y):
    global downpour
    if len(downpour) == 0:
        ugfx.string_box(0, y - MSG_HEIGHT, 296, MSG_HEIGHT,
                        'Failed to retrieve rain forecast', 'Roboto_Regular12',
                        ugfx.BLACK, ugfx.justifyLeft)
        return REFRESH_RATE, 0

    if any(d[1] for d in downpour):
        start_idx, start = next((i, d[0]) for i, d in enumerate(downpour) if d[1] > 0)
        try:
            end_idx = next(i for i, d in enumerate(downpour[start_idx:]) if d[1] == 0)
        except StopIteration:
            end_idx = -1
        duration = '%d minutes' % (5 * (end_idx - start_idx)) if end_idx > 0 else 'a while'

        ugfx.string_box(0, y - MSG_HEIGHT, 296, MSG_HEIGHT,
                        'Rain starting at %s, lasting %s' % (start, duration), 'Roboto_Regular12',
                        ugfx.BLACK, ugfx.justifyLeft)

        # Alert the user when there's rain coming in the next 30 minutes
        if start_idx <= 6:
            # 200 ms per bit
            virtualtimers.new(1, buzz)
    else:
        ugfx.string_box(0, y - MSG_HEIGHT, 296, MSG_HEIGHT,
                        'No rain expected', 'Roboto_Regular12',
                        ugfx.BLACK, ugfx.justifyLeft)
    return REFRESH_RATE, MSG_HEIGHT
