from machine import Pin, PWM, I2C, Timer
import time
import wifi, settings
import usocket as socket
import select

# Initialize GPIO
led = Pin("LED", Pin.OUT)
b1 = Pin(15, Pin.IN, Pin.PULL_UP)
LED_R = Pin(3, Pin.OUT)
LED_W = Pin(2, Pin.OUT)


def initializing():
    for x in range(10):
        LED_W.toggle()
        time.sleep_ms(settings.FLASH_TIME)
    LED_W.off()
    # Initialize WiFi
    wlan = wifi.initialize(settings.SSID, settings.PASS)
    if wlan.isconnected():
        for x in range(6):
            LED_W.toggle()
            time.sleep_ms(settings.FLASH_TIME)
    else:
        for x in range(6):
            LED_R.toggle()
            time.sleep_ms(settings.FLASH_TIME)
    LED_R.off()
    LED_W.off()
    return wlan


def open_socket(ip):
    address = (ip, 80)
    connection = socket.socket()
    connection.bind(address)
    connection.listen(1)
    poll = select.poll()
    poll.register(connection, select.POLLIN)
    return connection, poll


def serve(connection, poll):
    events = poll.poll(100)
    if events:
        state = "off"
        print(str(connection))
        client = connection.accept()[0]
        request = client.recv(1024)
        request = str(request)
        print(request)
        try:
            request = request.split()[
                1
            ]  # second member of the array, split at each split
        except IndexError:
            pass
        if request == "/lock?":
            LED_W.off()
            LED_R.on()
            state = "ON"
        elif request == "/unlock?":
            state = "OFF"
            LED_W.on()
            LED_R.off()
        html = webpage(state)
        client.send(html)
        print(request)
        client.close()


def webpage(state):
    # Template HTML
    html = f"""
            <!DOCTYPE html>
            <html>
            <form action="./lock">
            <input type="submit" value="Lock" />
            </form>
            <form action="./unlock">
            <input type="submit" value="unlock" />
            </form>
            <p>Lock State is {state}</p>
            </body>
            </html>
            """
    return str(html)


# Set Up
print("test test test")
wlan = initializing()
ip = wlan.ifconfig()[0]
print(f"Connected on {ip}")
connection, poll = open_socket(ip)
print(str(connection))

while True:
    serve(connection, poll)
    if b1.value() != 1:
        LED_W.on()
