import ugfx
import urequests
import wifi
import time

def setup():
    pass

def loop():
    return 60000

def draw(y):
    start(y)
    printRain(y)
    return [60000, 36]

def printRain(y):
    ugfx.string(0, y, "Still raining anyway %i" %y, "Roboto_Regular12", ugfx.BLACK)

def start(y):
    data = get_data()
#    printRain(12)
    draw_chart(data,y-36,20,4)
#    printRain(60)
    ugfx.string(0,y-12,"Buienradar","Roboto_Regular12", 0)

def wait_wifi():
    while not wifi.sta_if.isconnected():
        time.sleep(0.1)

def get_data():
    wifi.init()
    wait_wifi()

    try:
        response = urequests.get("https://br-gpsgadget-new.azurewebsites.net/data/raintext/?lat=52.28&lon=5.53")

    except:
        ugfx.string(80,10,"Could not download weather data","Roboto_Regular12", 0)
        return
    else:
        if response.status_code == 200:
            result = response.text
    response.close()

    try:
        data = []
        for v in result.split("\n"):
            data.append(v.split('|'))
    except:
        ugfx.string(80,10,"Could not convert data","Roboto_Regular12", 0)
    return data


def draw_chart(data,dy,height,barsize): #[],10,20,4
    n = 0
    for v in data:
        spacer = 1
        mm = int(v[0])
        time = v[1]
        if time == "19:55":
            mm = 40
        barsize=4
        x=n*(barsize+spacer)+spacer
        barheight=int(height/255*mm)
        y=dy-barheight
        cx=barsize
        cy=barheight+1
        ugfx.area(x,y,cx,cy, ugfx.BLACK)
#        printRain(36)
        n+=1
#        print(mm,time,n,x,y,cx,cy)