import network
import socket
import time
from machine import Pin

# Conexión Wifi Simulada
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
    print('.', end='')
    time.sleep(0.1)
    print(" Connected!")
print(sta_if.ifconfig())



# Setup LED pins
red = Pin(15, Pin.OUT)
green = Pin(2, Pin.OUT)
blue = Pin(4, Pin.OUT)

# Turn off all at start
red.off()
green.off()
blue.off()

ssid = "Wokwi-GUEST"
password = ""


# HTML template
def web_page():
    html = """<!DOCTYPE html>
    <html>
    <head><title>ESP32 RGB LED</title></head>
    <body>
    <h1>ESP32 RGB LED Control</h1>
    <p><a href="/red"><button>RED</button></a></p>
    <p><a href="/green"><button>GREEN</button></a></p>
    <p><a href="/blue"><button>BLUE</button></a></p>
    <p><a href="/off"><button>OFF</button></a></p>
    </body></html>"""
    return html

# Start server
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)

print('Web server running on http://', network.WLAN(network.STA_IF).ifconfig()[0])

while True:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)

    if '/red' in request:
        red.on(); green.off(); blue.off()
    elif '/green' in request:
        red.off(); green.on(); blue.off()
    elif '/blue' in request:
        red.off(); green.off(); blue.on()
    elif '/off' in request:
        red.off(); green.off(); blue.off()

    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    conn.close()