import machine
# import gc
# import webrepl
# webrepl.start()
# gc.collect()

html = """<!DOCTYPE html>
<html>
    <head> <title>ESP8266</title> </head>
    <body> <h1>ESP8266 - Micropython</h1>
    LED Pin 2
        <a href="/led2/on"><button>LED ON</button></a>
        <a href="/led2/off"><button>LED OFF</button><br><br></a>

    LED Pin 16
        <a href="/led16/on"><button>LED ON</button></a>
        <a href="/led16/off"><button>LED OFF</button><br><br></a>

    Delay Sequence
        <a href="/led/delay"><button type="submit">Delay</button></a>
    </body>
</html>
"""

def SwitchON(pin):
    pin.low()

def SwitchOFF(pin):
    pin.high()

import socket
import time
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)
pin2 = machine.Pin(2, machine.Pin.OUT)
pin16 = machine.Pin(16, machine.Pin.OUT)

print('listening on', addr)

while True:
    conn, addr = s.accept()
    print('client connected from', addr)
    response = html
    request = conn.recv(1024)
    print(request)
    if '/led2/on' in str(request):
        SwitchON(pin2)
    elif '/led2/off' in str(request):
        SwitchOFF(pin2)
    elif '/led16/on' in str(request):
        SwitchON(pin16)
    elif '/led16/off' in str(request):
        SwitchOFF(pin16)
    elif '/led/delay' in str(request):
        seq = 10
        while seq:
            time.sleep(0.5)
            SwitchON(pin2)
            SwitchON(pin16)
            time.sleep(0.5)
            SwitchOFF(pin2)
            SwitchOFF(pin16)
            seq -= 1
    else:
        SwitchOFF(pin2)
        SwitchOFF(pin16)
    conn.send(response)
    conn.close()
