# Requires latest git pull submodule sync magic to actually work!

import badge, easywifi, ugfx, gc, easydraw, woezel
easydraw.msg("Hi, my name is: " + badge.nvs_get_str("owner","name"))

easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("Meh unable to connect to network","FAILURE")
    easydraw.msg("Waiting 5 seconds to try again!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(5000)

easydraw.msg("Checking for updates")
try:
    woezel.install('wiki_infotag')
    easydraw.msg("Updated! Rebooting now!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(1)
except:
    easydraw.msg("No update available. Starting app!")
    easydraw.msg("Requesting "+ badge.nvs_get_str("wiki", "page", "Gallerij") + " page")
    import urequests as requests
    data = requests.get(badge.nvs_get_str("wiki", "url", "https://revspace.nl") + "/api.php?action=parse&format=json&prop=wikitext&disableeditsection&disabletoc&disablelimitreport&page=" + badge.nvs_get_str("wiki","page","Gallerij"))

    content=data.json()['parse']['wikitext']['*'].split("\n")[:]
    data.close()
    easydraw.msg("Data in, processing")
    gc.collect()

    indexteller=0
    offsetlijst=[]
    imagenaam =''
    projectnaam=''
    maker = ''
    omschrijving = ''
    datum = ''
    identiteit = 0

    # lets find all the Heading 1 topics, we use those to split info
    for x in range(0, len(content)-1):
        if len(content[x].split("=")) == 3: # 5 for heading 2 and 7 for heading 3
            offsetlijst.append(x)
        gc.collect()
    offsetlijst.append(len(content))

    # Now we find if our nickname matches one of the header 1 topics
    for x in range(0, len(offsetlijst)-1):
        if content[offsetlijst[x]].split("=")[1] == badge.nvs_get_str("owner","name"):
            identiteit = x
            easydraw.msg("Found info for me to display!")
        gc.collect()

    # Lets parse the information we selected
    for x in range(offsetlijst[identiteit]+1, offsetlijst[identiteit+1]):
        print(content[x])
        if len(content[x].split("[[File:")) == 2:
            imagenaam = content[x].split("[[File:")[1].split("]]")[0]
        if len(content[x].split("=")) == 7:
            projectnaam = content[x].split("=")[3]
        if len(content[x].split("Maker: ")) == 2:
            maker = content[x].split("Maker: ")[1]
        if len(content[x].split("Omschrijving: ")) == 2:
            omschrijving = content[x].split("Omschrijving: ")[1]
        if len(content[x].split("Datum: ")) == 2:
            datum = content[x].split("Datum: ")[1]
        gc.collect()

    if imagenaam != '':
        easydraw.msg("Downloading image...")
        gc.collect()
        data=requests.get(badge.nvs_get_str("wiki","url","https://revspace.nl")+"/Special:Filepath/"+imagenaam)
        gc.collect()
        png_data = data.content
        data.close()
        gc.collect()
        easydraw.msg("Ready to display!")
        ugfx.set_lut(ugfx.GREYSCALE)
        ugfx.clear(ugfx.WHITE)
        gc.collect()
        width,height,bitdepth,colortype=badge.eink_png_info(png_data)
        text = ugfx.Textbox(width,40, 296-width, 88)
        text.text(omschrijving)
        badge.eink_png(0, int((128-height)/2), png_data)
        ugfx.string_box(width,0,296-width,26, projectnaam, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
        ugfx.string_box(width, 26, 296-width, 14, datum + " " + maker, "pixelade13", ugfx.BLACK, ugfx.justifyCenter)
        ugfx.box(width,40, 296-width, 88, ugfx.WHITE) # ugly hack to remove ugly black box around textbox
        ugfx.line(width+4, 40, width+4, 128, ugfx.WHITE) # ugly hack to remove ugly cursor from textbox
    else:
        easydraw.msg("Ready to display!")
        ugfx.set_lut(ugfx.GREYSCALE)
        ugfx.clear(ugfx.WHITE)
        text = ugfx.Textbox(0,40, 296, 88)
        text.text(omschrijving)
        ugfx.string_box(0,0,296,26, projectnaam, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
        ugfx.string_box(0, 26, 296, 14, datum + " " + maker, "pixelade13", ugfx.BLACK, ugfx.justifyCenter)
        ugfx.box(0,40, 296, 88, ugfx.WHITE) # ugly hack to remove ugly black box around textbox
        ugfx.line(4, 40, 4, 128, ugfx.WHITE) # ugly hack to remove ugly cursor from textbox
    ugfx.flush()
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(524288)