import network, socket, time
from secrets import secrets

ssid=secrets['ssid']
password = secrets['pw']

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 get_html(html_name):
    with open(html_name, 'r') as file:
        html=file.read()
    return html

def serve(connection):
        
    while True:
        client=connection.accept()[0]
        request=client.recv(1024)
        request=str(request)
        try:
            response=get_html('index.html')
            request=request.split()[1]
        except IndexError:
            pass
        
        client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        client.send(response)
        client.close()
    
try:
    ip=connect()
    connection=open_socket(ip)
    serve(connection)
except KeyboardInterrupt:
    pass