import network
import socket
import machine
import time

# Setup RP2040 as an access point
ap = network.WLAN(network.AP_IF)
ap.config(essid="RP2040-AP-3", password="testing123")
ap.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "192.168.4.1"))
ap.active(True)

# Initialize onboard LED
led = machine.Pin("LED", machine.Pin.OUT, value=1)
motor_ctl_a = machine.Pin(16, machine.Pin.OUT, value=0)
motor_ctl_b = machine.Pin(17, machine.Pin.OUT, value=0)

# Create a socket and listen on port 80
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
s.bind(addr)
# only allowed to listen to 5 connections in AP mode
s.listen(5)

print("listening on", ap.ifconfig()[0])

# HTML to send to browsers
html = """
<!DOCTYPE html>
<html>
<body>
<h1>Toggle Motor</h1>
<button onclick="toggleLED()">Toggle LED</button>
<script>
function toggleLED() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/toggle", true);
  xhr.send();
}
</script>
</body>
</html>
"""


def serve():
    conn, addr = s.accept()
    print("client connected from", addr)
    request = conn.recv(1024)
    request_str = str(request)
    print("request:", request_str)

    if "POST /toggle" in request_str:
        led.toggle()
        motor_ctl_a.toggle()  # Toggle LED state
        conn.send("HTTP/1.1 200 OK\n\nLED Toggled")
    else:
        conn.send("HTTP/1.1 200 OK\n")
        conn.send("Content-Type: text/html\n")
        conn.send("Connection: close\n\n")
        conn.sendall(html)  # Send HTML page
    conn.close()


# Main loop: accept connections and respond
for i in range(10):
    print(f"Preparing to serve...{i}")
    time.sleep(1)

while True:
    serve()
