#ILI9488 uses 24bit mode
COLOUR_BLACK  = const(0x000000)
COLOUR_WHITE  = const(0xFFFFFF)
COLOUR_RED    = const(0xFF0000)
COLOUR_GREEN  = const(0x00FF00)
COLOUR_BLUE   = const(0x0000FF)
COLOUR_YELLOW = const(0xFFFF00)
COLOUR_CYAN   = const(0x00FFFF)
COLOUR_MAGENTA= const(0xFF00FF)
COLOUR_GREY   = const(0x808080)

import utime
import time
from ILI9488LIB import ILI9488LIB
from ILI9488LIB import LCD_BUTTON
import LSNBFONT
import uselect
import sys
import network
import ntptime
import urequests

display = ILI9488LIB()       #use defaults
display.init()               #init
display.setRotation(2)

red=LCD_BUTTON(10,280,100,35,"RED")
green=LCD_BUTTON(130,280,100,35,"GREEN")
blue=LCD_BUTTON(250,280,100,35,"BLUE")
erase=LCD_BUTTON(370,280,100,35,"ERASE")
c=COLOUR_WHITE
scanBuf=""
scanProcessed=1
scanReady=0
menuState=0
oldSeconds=0
tzOffset=0

def drawDemo():
    display.clear(COLOUR_BLACK)
    display.drawstr((display.width-display.strwidth("Testing",LSNBFONT))//2,20,"Testing",LSNBFONT,COLOUR_WHITE,COLOUR_BLUE)
    display.fcircle(100,100,20,COLOUR_YELLOW)
    display.fcircle(100,100,15,COLOUR_RED)
    display.circle(100,100,45,COLOUR_CYAN)
    display.box(280,80,320,120,COLOUR_YELLOW)
    display.box(285,85,315,115,COLOUR_RED)
    display.hbox(255,55,345,145,COLOUR_CYAN)
    display.button(red)
    display.button(green)
    display.button(blue)
    display.button(erase)

#serial port scanning
portscan=uselect.poll()
portscan.register(sys.stdin, uselect.POLLIN)

#WiFi setup
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

wStat=wlan.status()
oldwStat=-1

def scanInput():
    global scanProcessed
    global scanReady
    global scanBuf
    if(scanProcessed==1):
        scanProcessed=0
        scanReady=0
        scanBuf=""
    c=(sys.stdin.read(1) if portscan.poll(0) else "")
    if(c!=""):
        #print (ord(c))
        if((ord(c)==13 or ord(c)==10)):
            if (len(scanBuf)>0):
                scanReady=1
                scanProcessed=0
        else:
            scanBuf=scanBuf+c

def showMenu():
    print("Menu:")
    print("1: Scan for networks")
    print("2: Set SSID name")
    print("3: Set SSID password")
    print("4: Connect")
    print("5: Disconnect")
    print("6: Get IPAPI data")

drawDemo()
lastx=-1
lasty=-1
ssidname="SSID"
ssidpass="PASS"
showMenu()
machine.RTC().datetime((2022,1,1,0,0,0,0,0))

while 1:
    x=display.touchx()
    y=display.touchy()
    if (x>=0 and y>=0 and lastx>=0 and lasty >=0):
        display.line(x,y,lastx,lasty,c)
    lastx=x
    lasty=y
    display.check(red)
    if(red.lastchange != 0):
        display.button(red)
        c=COLOUR_RED
    display.check(green)
    if(green.lastchange != 0):
        display.button(green)
        c=COLOUR_GREEN
    display.check(blue)
    if(blue.lastchange != 0):
        display.button(blue)
        c=COLOUR_BLUE
    display.check(erase)
    if(erase.lastchange != 0):
        display.button(erase)
    if(erase.lastchange == -1):
        drawDemo()
    scanInput()
    if(scanReady==1):
        #print("Line received")	#debugging output
        #print(scanBuf)
        if(menuState==0):
            if(scanBuf[0:1]=='1'):
                print("Scanning.")
                nets = wlan.scan()
                for net in nets:
                    print(str(net[3])+"   "+net[0].decode("utf-8")) #RSSI and SSID
                print("Scan complete.")
                showMenu()
            if(scanBuf[0:1]=='2'):
                print("Enter SSID:")
                menuState=2
            if(scanBuf[0:1]=='3'):
                print("Enter password:")
                menuState=3
            if(scanBuf[0:1]=='4'):
                print("Connecting to "+ssidname)
                wlan.connect(ssidname,ssidpass)
                showMenu()
                menuState=0
            if(scanBuf[0:1]=='5'):
                print("Disconnecting.")
                wlan.disconnect()
                wlan.active(False)	#reset WiFi too
                wlan.active(True)
                showMenu()
                menuState=0
            if(scanBuf[0:1]=='6'):
                print("Getting IPAPI data.")
                try:
                    req=urequests.get("http://ip-api.com/line?fields=city,offset")
                    print(req.status_code)
                    if(req.status_code == 200):
                        cont=req.content.decode("utf-8")
                        print(len(cont))
                        if (len(cont.splitlines()) > 1):
                            display.drawstr(10,250,cont.splitlines()[0]+"        ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                            ntptime.settime()
                            tzOffset=int((cont.splitlines()[1]))	#second line is offset
                    req.close()
                except Exception :
                    print("Could not fetch HTTP and sync NTP time.")
                    pass
                showMenu()
                menuState=0
        elif(menuState==2):
            ssidname=scanBuf
            menuState=0
            print("SSID set to "+ssidname)
            showMenu()
        elif(menuState==3):
            ssidpass=scanBuf
            menuState=0
            print("Password set to "+ssidpass)
            showMenu()
        scanProcessed=1
    #display state
    now=time.localtime(time.time()+tzOffset)
    seconds=now[5]    
    if(seconds != oldSeconds):	#update at most once per second
        wStat=wlan.status()
        if(wStat != oldwStat):        
            if(wStat==network.STAT_IDLE):
                display.drawstr(10,160,"WiFi idle                ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            elif(wStat==network.STAT_CONNECTING):
                display.drawstr(10,160,"Connecting               ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            elif(wStat==network.STAT_WRONG_PASSWORD):
                display.drawstr(10,160,"Wrong password           ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            elif(wStat==network.STAT_NO_AP_FOUND):
                display.drawstr(10,160,"No Access point          ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            elif(wStat==network.STAT_CONNECT_FAIL):
                display.drawstr(10,160,"Connect fail             ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            elif(wStat==network.STAT_GOT_IP):
                display.drawstr(10,160,"Connected, IP OK         ",LSNBFONT,COLOUR_GREEN,COLOUR_BLACK)
                display.drawstr(10,190,"IP:"+wlan.ifconfig()[0]+"                   ",LSNBFONT,COLOUR_GREEN,COLOUR_BLACK)
            else:
                display.drawstr(10,160,"Status unknown         ",LSNBFONT,COLOUR_GREEN,COLOUR_BLACK)
                display.drawstr(10,190,"IP:0:0:0:0                   ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
            oldwStat=wStat
        timeString='{:02d}/{:02d}/{:04d} {:02d}:{:02d}:{:02d}'.format(now[2], now[1], now[0],now[3], now[4], now[5])
        display.drawstr(10,220,timeString+"            ",LSNBFONT,COLOUR_YELLOW,COLOUR_BLACK)
        seconds=now[5]    
        oldSeconds=seconds            