import easywifi
import math
import urequests
import ugfx

graph = __import__('lib/buienalarm/graph')

SHA_LAT = 52.28
SHA_LON =  5.53

TS_WIDTH = 32
TS_HEIGHT = 14

BUIENRADAR_URL = 'https://gps.buienradar.nl/getrr.php?lat=%.2f&lon=%.2f' % (SHA_LAT, SHA_LON)

def _raw_to_mm(raw):
    raw = int(raw)
    if raw == 0: return 0.0
    return 10 ** ((raw - 109) / 32)

def get_downpour():
    """Returns a table for the downpour over the next 2 hours.

    Return value is a list of pairs of the form ('hh:mm', millimeters)
    """
    if not easywifi.status(): raise RuntimeError('WiFi is not connected')

    resp = urequests.get(BUIENRADAR_URL)
    data = []
    for line in resp.text.splitlines():
        rain, time = line.split('|')
        data.append((time, _raw_to_mm(rain)))

    return data

def draw_rain_graph(x, y, width, height, scale=1.0, colour=ugfx.BLACK):
    """Draws a rain graph at the specified coordinates.

    Uses 14 pixels for the time, and then draws a graph across the full length
    of the specified area, capping values at (height / scale) - 14 millimeters
    """
    try:
        downpour = []
        retry = 0
        while len(downpour) == 0 and retry < 10:
            downpour = get_downpour()
            retry += 1

        if len(downpour) == 0:
            raise RuntimeError('Buienradar returned no data')
    except Exception as e:
        ugfx.string_box(x, y, width, height,
                        str(e), "Roboto_Regular12",
                        colour, ugfx.justifyCenter)
        return

    # How many timestmaps can we fit?
    num_items = len(downpour)
    period = math.ceil(num_items * 1.5 * TS_WIDTH / (width - TS_WIDTH))

    sample_width = int(width / (num_items - 1))
    
    text_y = y + height - TS_HEIGHT + 1
    for i, item in enumerate(downpour):
        time, _ = item
        if i % period == 0:
            text_x = x + i * sample_width - ugfx.get_string_width(time, 'Roboto_Regular12') // 2
            
            # Corner case: screen edge
            if text_x < 0:
                text_x = 0
            elif text_x + TS_WIDTH > x + width:
                text_x = x + width - TS_WIDTH

            ugfx.string(text_x, text_y, time, "Roboto_Regular12", colour)

    ugfx.string(x + width - TS_WIDTH, text_y, downpour[-1][0], "Roboto_Regular12", colour)

    samples = [d[1] for d in downpour]
    if any(samples):
        graph.draw_graph(x, y, width, height - TS_HEIGHT, samples, scale, ugfx.BLACK)
    else:
        ugfx.string_box(x, y, width, height - TS_HEIGHT,
                        'No rain expected', 'Roboto_Regular12',
                        ugfx.BLACK, ugfx.justifyCenter)