import appglue
import time
import ugfx
import urequests
import wifi
import easydraw
import gc
from os import system, sleep

restart = False
logo = None
state = {}

def on_start(pressed):
    if pressed:
        appglue.home()

def init_wifi():
    # Make sure WiFi is connected
    try:
        wifi.init()
        ugfx.clear(ugfx.WHITE);
        ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
        ugfx.flush()
        while not wifi.sta_if.isconnected():
            sleep(0.1)
    except:
        wifi.connect()
        easydraw.messageCentered("\nConnecting...", True, "/media/wifi.png")
        if not wifi.wait():
            easydraw.messageCentered("Could not connect!", True, "/media/alert.png")
            time.sleep(2)
            system.home()
        easydraw.messageCentered("\nConnected!", True, "/media/wifi.png")

def load_salzamt_state():
    try:
        response = urequests.get("https://git.sigflag.at/fuero/camp2019/raw/master/salzamt.json")
        gc.collect()
        return response.json()
    except:
        return None

def load_salzamt_logo(data):
    try:
        response = urequests.get(data['logo_small'])
        gc.collect()
        return response
    except:
        return None

def update_salzamt_state():
    global state
    state = load_salzamt_state()
    easydraw.messageCentered("\nSalzamt is")
    if state["open"]:
        easydraw.messageCentered("\nOPEN")
    else:
        easydraw.messageCentered("\nCLOSED")
    pass

def run():
    global restart
    global state

    ugfx.init()
    init_wifi()

    if not wifi.wait(30, True):
        exit()

    ugfx.orientation(0)
    ugfx.set_lut(ugfx.LUT_NORMAL)
    ugfx.input_attach(ugfx.BTN_START, on_start)

    ugfx.clear(ugfx.WHITE)
    ugfx.string_box(0,10,296,26, "Please be very patient...", "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.flush()
    ugfx.set_lut(ugfx.LUT_FULL)
    seconds_since_update = 999
    while not restart:
        if seconds_since_update >= 30:
            update_salzamt_state()
            seconds_since_update = 0
        time.sleep(1)
        seconds_since_update += 1

while True:
    run()