import network, socket, time, machine

cat=machine.Pin(15,machine.Pin.OUT)
red=machine.Pin(18,machine.Pin.OUT)
green=machine.Pin(19,machine.Pin.OUT)

ssid='SSID'
password='PSSWD'

def connect():
    wlan=network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid,password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        time.sleep(1)
    ip=wlan.ifconfig()[0]
    print(f'Connected on {ip}')
    return ip

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


def webpage(Gstate,Rstate,state):
    html=f"""
          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8" />
              <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          </head>
          <body>
          <form action="./lighton">
          <input type="submit" value="Cat on" />
          </form>
          <form action="./lightoff" />
          <input type="submit" value="Cat off" />
          </form>
          <form action="./redon">
          <input type="submit" value="Red on"/>
          </form>
          <form action="./redoff">
          <input type="submit" value="Red off"/>
          </form>
          <form action="./greenon">
          <input type="submit" value="Green on"/>
          </form>
          <form action="./greenoff">
          <input type="submit" value="Green off"/>
          </form>
          <p>Cat is {state}</p>
          <p>Red is {Rstate}</p>
          <p>Green is {Gstate}</p>
          </body>
          </html>
          """
    return html

def serve(connection):
    state='OFF'
    Rstate='OFF'
    Gstate='OFF'
    
    while True:
        client=connection.accept()[0]
        request=client.recv(1024)
        request=str(request)
        try:
            request=request.split()[1]
        except IndexError:
            pass
        if request=='/lighton?':
            cat.on()
            state='ON'
        elif request=='/lightoff?':
            cat.off()
            state='OFF'
        elif request=='/redon?':
            red.on()
            Rstate='ON'
        elif request=='/redoff?':
            red.off()
            Rstate='OFF'
        elif request=='/greenon?':
            green.on()
            Gstate='ON'
        elif request=='/greenoff?':
            green.off()
            Gstate='OFF'
        html=webpage(Gstate,Rstate,state)
        client.send(html)
        client.close()
    
try:
    ip=connect()
    connection=open_socket(ip)
    serve(connection)
except KeyboardInterrupt:
    machine.reset()
