#import esp
import badge, ugfx, time, appglue, socket, network, gc

#HTML to send to browsers
html = """<!DOCTYPE html>
<html>
<head> <title>ESP8266 LED ON/OFF</title> </head>
<center><h2>A simple webserver for turning HUZZAH Feather LED's on and off with Micropython</h2></center>
<center><h3>(for noobs to both the ESP8266 and Micropython)</h3></center>
<form>
LED0: 
<button name="LED" value="ON0" type="submit">LED ON</button>
<button name="LED" value="OFF0" type="submit">LED OFF</button><br><br>
</form>
</html>
"""
    
def btn_home(pushed):
    if pushed:
		appglue.start_app('launcher')
        #appglue.home()
sta_if = False

def sta_init():
    global sta_if
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    ssid = badge.nvs_get_str('badge', 'wifi.ssid', 'SHA2017-insecure')
    password = badge.nvs_get_str('badge', 'wifi.password')
    if password:
        sta_if.connect(ssid, password)
    else:
        sta_if.connect(ssid)
	gc.collect()

badge.init()
badge.eink_init()

ugfx.init()
ugfx.input_init()
ugfx.input_attach(ugfx.BTN_START, btn_home)

# Make sure WiFi is connected
#sta_init()
time.sleep(1)
ugfx.clear(ugfx.WHITE)
ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
ugfx.flush()

# Wait for WiFi connection
i = 0 
#while not sta_if.isconnected():
#	i = i+1
#	time.sleep(0.1)
#	ugfx.clear(ugfx.WHITE)
#	ugfx.string(15,20,"Connecting failed..." + str(i),"Roboto_Regular12", 0)
#	ugfx.flush()
#	if(i>200):
#		break
#if (sta_if.isconnected() == True):
#if (sta_if.isconnected() == False):
#	ugfx.clear(ugfx.WHITE)
#	ugfx.string(10,10,"Conected...","Roboto_Regular12", 0)
#	ugfx.string(20,20, next(iter(sta_if.ifconfig())),"Roboto_Regular12",0)
#	ugfx.flush()
#else:
if True:
#	sta_if.disconnect()
#	sta_if.active(False)
	ap_if = network.WLAN(1)
	print(ap_if.config('essid'))
	ap_if.config(essid='SHA2017')
	ap_if.active(True)
	ugfx.clear(ugfx.WHITE)
	ugfx.string(10,10,"Opening AP...","Roboto_Regular12", 0)
	ugfx.string(20,20, next(iter(ap_if.ifconfig())),"Roboto_Regular12",0)
	ugfx.flush()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
    conn, addr = s.accept()
    print("Got a connection from %s" % str(addr))
    request = conn.recv(1024)
    print("Content = %s" % str(request))
    request = str(request)
    LEDON0 = request.find('/?LED=ON0')
    LEDOFF0 = request.find('/?LED=OFF0')
    print("Data: " + str(LEDON0))
    #print("Data2: " + str(LEDOFF0))
#    if LEDON0 == 6:
#        print('TURN LED0 ON')
#        LED0.low()
#    if LEDOFF0 == 6:
#        print('TURN LED0 OFF')
#        LED0.high()
    response = html
    conn.send(response)
    conn.close()