import time
import urequests
import ugfx
import wifi
import machine #to get the reset cause
import badge #to set splashscreen and wait for eink display
import deepsleep #deepsleep in the main routine
import appglue #to return home
import dialogs #to query the user for the url

OWNNAME = "thuis"
URL = badge.nvs_get_str(OWNNAME,"url","http://192.168.99.2/badge")
SLEEPTIME = 60*60*24*1000 #a day
FONT = badge.nvs_get_str(OWNNAME,"font","DejaVuSans20")
FONTS = ugfx.fonts_list()

#default code for badge
def clear(color):
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    ugfx.clear(color)

def wait_wifi():
    clear(ugfx.BLACK)
    ugfx.string(50, 25, "STILL", "Roboto_BlackItalic24", ugfx.WHITE)
    ugfx.string(30, 50, "Connecting to wifi", "PermanentMarker22", ugfx.WHITE)
    le = ugfx.get_string_width("Connecting to wifi", "PermanentMarker22")
    ugfx.line(30, 72, 30 + 14 + le, 72, ugfx.WHITE)
    ugfx.string(140, 75, "Anyway", "Roboto_BlackItalic24", ugfx.WHITE)
    ugfx.flush()

    while not wifi.sta_if.isconnected():
        time.sleep(0.1)
        
def show(newtext):
    lineheight = int(FONT[-2:])
    lines = int(ugfx.height()/lineheight)
    firstN = newtext.split("\n")[:lines]
    clear(ugfx.WHITE)
    i=0 #line counter
    for line in firstN:
        ypos = 1 + i * lineheight; #ypos 0 is invalid somehow?
    	ugfx.string(1,ypos,line, FONT, ugfx.BLACK)
        i+=1
    ugfx.flush()
    
    
def mainroutine():
    wifi.init()
    wait_wifi()
    try:
        show("Requesting...")
        r = urequests.get(URL)
    except:
        show("Connection problems")
        if not wifi.sta_if.isconnected():
            wifi.init()
            wait_wifi()
    else:
        if r.status_code == 200:
            show(r.text);
            r.close()
        else:
            show("Error at fetching file");
            r.close();
            
        badge.nvs_set_str('boot','splash', OWNNAME) #set badge to reboot into this
        badge.eink_busy_wait() #wait for eink display to draw
        deepsleep.start_sleeping(SLEEPTIME) #let's go to sleep

def set_font(font):
    global FONT
    FONT = font
    badge.nvs_set_str(OWNNAME,"font",font)
    mainscreen()
    
def set_url():
    global URL
    url = dialogs.prompt_text("Enter URL", URL)
    URL = url
    badge.nvs_set_str(OWNNAME,"url",URL)
    
#allow to set font on call of mainscreen
def mainscreen():
    global URL
    global FONT
    show("""[A] Set URL
[B] Return to home
[Start] start display routine
[Select] Select font
Font: """+FONT+"\n"+URL)
    ugfx.input_init()
    ugfx.input_attach(ugfx.BTN_A,lambda pressed: set_url())
    ugfx.input_attach(ugfx.BTN_B,lambda pressed: appglue.start_app("launcher"))
    ugfx.input_attach(ugfx.BTN_START,lambda pressed: mainroutine())
    ugfx.input_attach(ugfx.BTN_SELECT,lambda pressed: set_font_menu())

def set_font_menu():
    global FONT
    global FONTS
    options = ugfx.List(0,0,int(ugfx.width()),ugfx.height())
    #options already handles up/down on it's own
    for font in FONTS:
        options.add_item(font)

    ugfx.input_init()
    ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush() if pushed else False)
    ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush() if pushed else False)
    ugfx.input_attach(ugfx.BTN_START,lambda pushed: set_font(options.selected_text()) if pushed else False)
    ugfx.input_attach(ugfx.BTN_A,lambda pushed: set_font(options.selected_text()) if pushed else False)
    ugfx.input_attach(ugfx.BTN_B,lambda pushed: mainscreen() if pushed else False)
    ugfx.flush()
       
ugfx.init()
badge.init()

displayloop = badge.nvs_get_str('boot','splash', "splash") == OWNNAME
#if the badge didn't boot from deepsleep, reset it to boot to splash
if( machine.reset_cause() == machine.DEEPSLEEP_RESET and displayloop ):
  	mainroutine()
else:
    badge.nvs_set_str('boot','splash','splash')
    mainscreen()