<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WiFi Configuration</title>
    <link rel="icon" type="image/x-icon" href="/static/images/favicon.ico">
    <link rel="stylesheet" href="/static/css/styles.css">
    <link rel="stylesheet" href="/static/fontawesome/css/all.min.css">
    <style>
        h1 {
            margin-top: 30px;
            font-size: 36px;
            color: #333;
        }
        .button-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }
        .btn {
            padding: 10px 20px;
            font-size: 1.2em;
            cursor: pointer;
            background-color: blue;
            color: white;
            width: 150px;
            border-radius: 5px;
            border: none;
            text-decoration: none;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .small-btn {
            width: 100px;
            padding: 5px 10px;
            font-size: 0.8em;
            background-color: darkslateblue;
        }
        .small-btn-container {
            margin-left: auto;
        }
        .scan-container {
            margin-top: 20px;
        }
        .scan-container .btn {
            background-color: #28a745;
        }
        .scan-container .btn:hover {
            background-color: #218838;
        }
        .connect-container {
            margin-top: 20px;
        }
        .connect-container .btn {
            padding: 5px 15px;
            border-radius: 5px;
            background-color: #ffc107;
        }
        .connect-container .btn:hover {
            background-color: #e0a800;
        }
        .network-list {
            margin-top: 20px;
            width: 100%;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: white;
            box-sizing: border-box;
        }
        .network-list table {
            width: 100%;
            border-collapse: collapse;
            table-layout: auto;
            box-sizing: border-box;
        }
        .network-list th, .network-list td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            white-space: nowrap;
            box-sizing: border-box;
        }
        .network-list th {
            background-color: #f2f2f2;
        }
        .network-list tr.selected {
            background-color: #d1e7dd;
        }
        .status {
            margin-top: 20px;
            font-size: 18px;
            color: #555;
        }
        .home-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 10px 20px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .home-btn:hover {
            background-color: #5a6268;
        }
        .placeholder-img {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        .placeholder-img img {
            top: 20px;
            width: 70px;
            height: 70px;
        }
        .header-img {
            margin-top: 20px;  /* Adjust the margin as needed */
            margin-bottom: 30px;
            width: auto;
            height: 80px;  /* Adjust the height as needed */
            position: absolute;
            left: 30px;
            top: 60px;
        }
    </style>
</head>
<body>
    <div id="navbar"></div>
    <script>
        fetch('/static/html/nav.html')
            .then(response => response.text())
            .then(data => {
                document.getElementById('navbar').innerHTML = data;
            });
    </script>

    <div class="content-wrapper">
        <div class="content">
            <h1>WiFi Internet Access</h1>
            <img src="/static/images/internet_icon.png" alt="internet" class="header-img">
            <label id="label-status">Status:</label>
            <div class="button-container">
                <button class="btn" id="scanButton" onclick="scanWifi()">Scan</button>
                <div class="small-btn-container">
                    <button class="btn small-btn" id="forgetButton" onclick="checkForgetNetworks()">Forget all</button>
                    <button class="btn small-btn" id="testButton" onclick="checkInternetAccess()">Test Internet</button>
                </div>
            </div>
            <div class="scan-container">
                <div id="scanStatus" class="status"></div>
            </div>
            <div class="network-list">
                <table id="networksTable">
                    <thead>
                        <tr>
                            <th>SSID</th>
                            <th>Freq</th>
                            <th>Signal</th>
                            <th>Bssid</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- List of networks will be appended here -->
                    </tbody>
                </table>
            </div>
            <div class="connect-container">
                <button class="btn" id="connectToNetworkButton"onclick="connectToNetwork()">Connect</button>
            </div>
            <div class="status" id="connectionStatus"></div>
        </div>
    </div>
    
    <script>
        window.onload = function() { OnPageLoad(); };

        function scanWifi() {
            console.log("Starting WiFi scan...");
            document.getElementById('connectionStatus').innerText = ""
            document.getElementById('scanStatus').innerText = "Scanning for networks...";
            fetch('/wifi_scan')
                .then(response => response.json())
                .then(data => {
                    console.log("Scan complete. Data received:", data);
                    document.getElementById('scanStatus').innerText = "Scan complete.";
                    let tableBody = document.getElementById('networksTable').getElementsByTagName('tbody')[0];
                    tableBody.innerHTML = '';
                    data.networks.forEach(network => {
                        let row = tableBody.insertRow();
                        let cell1 = row.insertCell(0);
                        let cell2 = row.insertCell(1);
                        let cell3 = row.insertCell(2);
                        let cell4 = row.insertCell(3);
                        cell1.textContent = network.ssid || '';
                        cell2.textContent = network.Freq || '';
                        cell3.textContent = network.signal || '';
                        cell4.textContent = network.bssid || '';
                        row.addEventListener('click', function() {
                            const rows = document.querySelectorAll('#networksTable tbody tr');
                            rows.forEach(r => r.classList.remove('selected'));
                            row.classList.add('selected');
                        });
                    });
                })
                .catch(error => {
                    console.error("Error during scan:", error);
                    document.getElementById('scanStatus').innerText = "Error during scan.";
                });
        }

        function connectToNetwork() {
            console.log("Attempting to connect to network...");
            const table = document.getElementById('networksTable');
            const selectedRow = table.querySelector('tbody tr.selected');
            if (!selectedRow) {
                document.getElementById('connectionStatus').innerText = "Please select a network to connect to.";
                return;
            }
            const ssid = selectedRow.cells[0].textContent;
            const bssid = selectedRow.cells[3].textContent;
            const password = prompt("Enter the WiFi password for " + ssid + ":");
            if (!password) {
                document.getElementById('connectionStatus').innerText = "Connection cancelled.";
                return;
            }
            document.getElementById('connectionStatus').innerText = "Please wait...";
            document.getElementById('connectToNetworkButton').disabled = true;
            document.getElementById('scanButton').disabled = true;
            document.getElementById('testButton').disabled = true;
            document.getElementById('forgetButton').disabled = true;
            fetch('/wifi_connect', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ ssid: ssid, bssid: bssid, password: password })
            })
                .then(response => response.json())
                .then(data => {
                    console.log("Connection attempt result:", data);
                    document.getElementById('connectionStatus').innerText = data.message;
                    checkWifiStatus();
                })
                .catch(error => {
                    console.error("Error during connection attempt:", error);
                    document.getElementById('connectionStatus').innerText = "Error during connection attempt.";
                })
                .finally(() => {
                    // Re-enable buttons after the connection attempt
                    document.getElementById('connectToNetworkButton').disabled = false;
                    document.getElementById('scanButton').disabled = false;
                    document.getElementById('testButton').disabled = false;
                    document.getElementById('forgetButton').disabled = false;
                });
        }

        function checkInternetAccess() {
            fetch('/wifi_test')
                .then(response => response.json())
                .then(data => {
                    const statusMessage = data.success ? "Internet Access Ok" : "No Internet Access";
                    alert(statusMessage); // Display message in a popup
                })
                .catch(error => {
                    console.error("Error checking internet access:", error);
                    alert("Error checking internet access."); // Display error in a popup
                });
        }
    
        function checkForgetNetworks() {
            fetch('/wifi_forget')
                .then(response => response.json())
                .then(data => {
                    const statusMessage = data.success ? "All networks forgotten" : "Nothing happened";
                    alert(statusMessage); // Display message in a popup
                })
                .catch(error => {
                    console.error("Error forgetting networks:", error);
                    alert("Error forgetting networks."); // Display error in a popup
                });
        }

        function checkWifiStatus() {
            fetch('/wifi_status')
                .then(response => response.json())
                .then(data => {
                    console.log("Data received:", data);
                    document.getElementById('label-status').innerText = "Status: " + data.msg;
                })
                .catch(error => {
                    console.error("Error getting wifi status:", error);
                    document.getElementById('label-status').innerText = "Status: ...";
                });
        }

        function OnPageLoad(){
            checkWifiStatus();
        }
        
    </script>
</body>
</html>
