import network
import time

# AP_IF: int = 1  # type: int
# STAT_CONNECTING: int = 1  # type: int
# STAT_GOT_IP: int = 3  # type: int
# STAT_IDLE: int = 0  # type: int
# STAT_CONNECT_FAIL: int = -1  # type: int
# STAT_NO_AP_FOUND: int = -2  # type: int
# STAT_WRONG_PASSWORD: int = -3  # type: int
# STA_IF: int = 0  # type: int


def initialize(SSID, PASS):
    print("Attempting to connect to: " + SSID)

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PASS)

    print(wlan.scan())

    # Wait for connect or fail
    max_wait = 6
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print("waiting for connection...")
        time.sleep(1)

    # Handle connection error
    if wlan.status() != 3:
        print("Error Number is: " + str(wlan.status()))
        # raise RuntimeError("Error connecting! Status: {status}")
        # raise RuntimeError("network connection failed")
    else:
        print("connected")
        status = wlan.ifconfig()
        print("ip = " + status[0])

    if wlan.isconnected():
        print("Connected to " + SSID)
    else:
        print("Error: Unable to connect to " + SSID)

    return wlan


def web_page():
    return """
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Home Lock</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }

        h1 {
            color: #333;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }

        #status {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <h1>Smart Home Lock</h1>
    <button id="lockButton" onclick="toggleLock()">Toggle Lock</button>
    <div id="status"></div>

    <script>
        function toggleLock() {

            var statusElement = document.getElementById("status");
            var lockButton = document.getElementById("lockButton");

            // Simulate a server response (success)
            var success = true;

            if (success) {
                if (lockButton.innerText === "Lock") {
                    lockButton.innerText = "Unlock";
                    statusElement.innerText = "Lock is now unlocked.";
                } else {
                    lockButton.innerText = "Lock";
                    statusElement.innerText = "Lock is now locked.";
                }
            } else {
                statusElement.innerText = "Failed to toggle lock.";
            }
        }
    </script>
</body>

</html>
"""
