import easyrtc
import ugfx
import gc, urequests as requests
#from time import sleep

def show_space_status(pushed,y):
    if(pushed):
 #       ugfx.string(10,10,"Downloading JSON","Roboto_Regular12", 0)
        ugfx.flush()
        gc.collect()
        try:
            data = requests.get("https://status.kreativitaet-trifft-technik.de/api/spaceInfo")
        except:
#            ugfx.string(10,10,"Could not download JSON","Roboto_Regular12", 0)
            ugfx.flush()
            return
        try:
            global output
            output = data.json()
        except:
            data.close()
#            ugfx.string(10,10,"Cannot understand shit","Roboto_Regular12", 0)
            ugfx.flush()
            return
        data.close()    
        
#    print("Rendering list...")
    open_text=''
    if str(output['state']['open']) != "False":
      open_text='We are open!'
    else :
      open_text = 'We are closed'
    
#    ugfx.clear(ugfx.WHITE)
#    ugfx.flush()
#    ugfx.string_box(0,2,296,36, "Space Status Mainframe ", "DejaVuSans20", ugfx.BLACK, ugfx.justifyCenter)
#    ugfx.string_box(0,50,296,38, str(output['state']['open'])+ "", "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
#    ugfx.string_box(0,50,296,36,  open_text, "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
#    ugfx.string_box(0,104,296,26, "Press A to reload, B to return homescreen", "Roboto_BlackItalic20", ugfx.BLACK, ugfx.justifyCenter)
#    ugfx.flush()    
    ugfx.string(0, y-24, "Space status %s anyway" % open_text, "Roboto_Regular12", ugfx.BLACK)




def setup():
    pass
  
def loop():
    return 60000

def draw(y):
#    show_space_status(1,y)

#       ugfx.string(10,10,"Downloading JSON","Roboto_Regular12", 0)
    ugfx.flush()
    gc.collect()
    try:
        data = requests.get("https://status.kreativitaet-trifft-technik.de/api/spaceInfo")
    except:
#            ugfx.string(10,10,"Could not download JSON","Roboto_Regular12", 0)
        ugfx.flush()
        return
    try:
        global output
        output = data.json()
    except:
        data.close()
#            ugfx.string(10,10,"Cannot understand shit","Roboto_Regular12", 0)
        ugfx.flush()
        return
    data.close()    
        
#    print("Rendering list...")
    open_text=''
    if str(output['state']['open']) != "False":
      open_text='We are open!'
    else :
      open_text = 'We are closed'
    
    t = easyrtc.string()
    t = t
    ugfx.string(0, y-12, "Space time %s anyway" % t, "Roboto_Regular12", ugfx.BLACK)
   # ugfx.string(0, y-12, "Space status %s anyway" % open_text, "Roboto_Regular12", ugfx.BLACK)

	#ugfx.flush()
    return [60000, 14]