"""
 ------------------------------------------------------------
  Code by lingib (C) 7 July 2023
  https://www.instructables.com/member/lingib/instructables/
  Licence: GPL3
 ------------------------------------------------------------
"""

# get libraries
import network
import socket
from machine import Pin

# configure on-board LED
led = Pin(2, Pin.OUT)
led.on()  # on() is actually "off" and vice-versa
button = 'STOP'
LED = 'OFF'

# access point security
ssid = 'ESP8266_AP'
password = '12345678'

# connect using AP (access point) mode
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=password)
ap.active(True)

# wait for wifi to go active
while not ap.active():
    pass
print('WiFi active')
print(ap.ifconfig())

# get ESP8266 address
status = ap.ifconfig()
esp8266_ip = status[0]
addr = (esp8266_ip, 80)

# start listening
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)

# main loop
while True:
    # accept client
    client, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    print('client' + str(client))
    print('addr' + str(addr))

    # process text string
    request = client.recv(1024)
    request = str(request)
    request_parts = request.split()
    http_method = request_parts[0]
    request_url = request_parts[1]
    print("http_method: " + http_method)
    print("request_url: " + request_url)
    print(" ")

    # action client button pushes
    if request_url.find('/forward') != -1:
        # turn LED on
        led.off()
        button = 'FORWARD'
        LED = 'ON'
    elif request_url.find('/left') != -1:
        # turn LED on
        led.off()
        button = 'LEFT'
        LED = 'ON'
    elif request_url.find('/stop') != -1:
        # turn LED off
        led.on()
        button = 'STOP'
        LED = 'OFF'
    elif request_url.find('/right') != -1:
        # turn LED on
        led.off()
        button = 'RIGHT'
        LED = 'ON'
    elif request_url.find('/reverse') != -1:
        # turn LED on
        led.off()
        button = 'REVERSE'
        LED = 'ON'
    else:
        pass

    # get HTML page
    file = open("five_buttons.html")
    html = file.read()
    file.close()

    # replace text in web page
    html = html.replace('button_label', button)
    html = html.replace('led_state', LED)

    # send modified webpage to client
    client.send('HTTP/1.1 200 OK\n')
    client.send('Content-Type: text/html\n')
    client.send('Connection: close\n\n')
    client.sendall(html)
    client.close()
