import gc

try:
    import usocket as socket
except ImportError:
    import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 80))
s.listen(5)


def render_html(context: dict = {}):
    html = (
        """<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="data:,"><style>body { text-align: center; font-family: "Trebuchet MS", Arial;}
    table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }
    th { padding: 12px; background-color: #0043af; color: white; }
    tr { border: 1px solid #ddd; padding: 12px; }
    tr:hover { background-color: #bcbcbc; }
    td { border: none; padding: 12px; }
    .sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px;
    </style></head><body><h1>ESP32 Sensor Output</h1>
    <table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>
    <tr><td>Temp. Celsius</td><td><span class="sensor">"""
        + str(context.get("cel"))
        + """</span></td></tr>
    <tr><td>Temp. Fahrenheit</td><td><span class="sensor">"""
        + str(context.get("fahr"))
        + """F</span></td></tr>
    <tr><td>Light</td><td><span class="sensor">"""
        + str(context.get("light"))
        + """%</span></td></tr>
    <tr><td>Humidity</td><td><span class="sensor">"""
        + str(context.get("hum"))
        + """%</span></td></tr></body></html>"""
    )
    return html


def http_respond(html: str):
    try:
        if gc.mem_free() < 102000:
            gc.collect()
        conn, addr = s.accept()
        conn.settimeout(3.0)
        print("Got a connection from: {addr}".format(addr=addr))
        request = conn.recv(1024)
        conn.settimeout(None)
        request = str(request)
        print("Content = {}".format(request))
        conn.send("HTTP/1.1 200 OK\n")
        conn.send("Content-Type: text/html\n")
        conn.send("Connection: close\n\n")
        conn.sendall(html)
        conn.close()
    except OSError as err:
        conn.close()
        print("Connection closed")
