import network
import socket
import time
from machine import Pin

blinkled = Pin("LED", Pin.OUT)
leftinone = Pin(12, Pin.OUT)
leftintwo = Pin(13, Pin.OUT)
rightinone = Pin(14, Pin.OUT)
rightintwo = Pin(15, Pin.OUT)

def back():
    rightinone.value(0)
    rightintwo.value(1)
    leftinone.value(0)
    leftintwo.value(1)

def right():
    rightinone.value(1)
    rightintwo.value(0)
    leftinone.value(0)
    leftintwo.value(1)

def left():
    rightinone.value(0)
    rightintwo.value(1)
    leftinone.value(1)
    leftintwo.value(0)

def front():
    rightinone.value(1)
    rightintwo.value(0)
    leftinone.value(1)
    leftintwo.value(0)

def stop():
    rightinone.value(0)
    rightintwo.value(0)
    leftinone.value(0)
    leftintwo.value(0)

net = network.WLAN(network.WLAN.IF_STA)
if net.active():
    net.active(False)
    time.sleep(0.5)

blinkled.value(0)
net.active(True)
net.connect('your-network-ssid', 'your-network-pwd')

url = net.ifconfig()[0]
while not net.isconnected() or url == "0.0.0.0":
    print("loading")
    blinkled.value(1)
    time.sleep(0.1)
    blinkled.value(0)
    url = net.ifconfig()[0]

blinkled.value(0)
time.sleep(1)
print(url+":80")
for i in url.split(".")[-1]:
    k = int(i)
    for j in range(k):
        blinkled.value(1)
        time.sleep(0.5)
        blinkled.value(0)
        time.sleep(0.5)
    time.sleep(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 80))
s.listen(1) 
while True:
    conn, addr = s.accept()
    command = conn.recv(1024).decode().split("\n")[0]
    if command.startswith("GET /stop "):
        stop()
        print(command)
        print("stopping")
    elif command.startswith("GET /w "):
        front()
        print(command)
        print("going forward")
    elif command.startswith("GET /s "):
        back()
        print(command)
        print("going backwards")
    elif command.startswith("GET /a "):
        left()
        print(command)
        print("going left")
    elif command.startswith("GET /d "):
        right()
        print(command)
        print("going right")
    else:
        conn.send('HTTP/1.1 404 Not Found\nContent-Type: text/plain\n\nPage not found')
        conn.close()
        continue
    conn.send('HTTP/1.1 200 OK\n\nOK')
    conn.close()
