<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <script type="text/javascript" src="static/js/socket.io.js"></script>
        <title>LoRa Scanner</title>
        <link rel="icon" type="image/x-icon" href="assets/img/favicon.ico" />
        <!-- Font Awesome icons (free version)-->
        <script src="static/js/all.js" crossorigin="anonymous"></script>
        <!-- Google fonts-->

        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="static/css/styles.css" rel="stylesheet" />
        <!-- Include SweetAlert2 CSS -->
        <link rel="stylesheet" href="static/css/sweetalert2.css">

        <!-- Include SweetAlert2 JS -->
        <script src="static/js/sweetalert2.js"></script>
        <script src="static/js/jquery.min.js"></script>

    </head>
    <body id="page-top">
        <!-- Navigation-->
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav">
            <a class="navbar-brand js-scroll-trigger" href="#page-top">
                <span class="d-block d-lg-none">LoRa Scanner</span>
                <span class="d-none d-lg-block"><img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="static/assets/img/profile.jpg" alt="..." /></span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
            <div class="collapse navbar-collapse" id="navbarResponsive">
                <ul class="navbar-nav">
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="/">Home</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="/analysis">Analysis Mode</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#">Survey Mode</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="/tracking">Tracking Mode</a></li>
                </ul>
            </div>
        </nav>
        <!-- Page Content-->
        <div class="container-fluid p-0">
            <!-- About-->
            <section class="resume-section" id="about">
                <div class="resume-section-content">
                    <h1 class="mb-0" style="text-align: center;">
                        Survey Mode
                    </h1>
                    <br>
                    <div class="scrollable-table">
                        <table id="data-table">
                            <thead>
                                <tr>
                                    <th>Device Name</th>
                                    <th>Frequency</th>
                                    <th>Signal Strength</th>
                                    <th>Decoded Values</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Rows will be inserted here -->
                            </tbody>
                        </table><br><br>                            
                    </div>
                    <div style="text-align:center;">
                        <button class="transmit-button" onclick="manualUpdateTable()">Refresh Table</button>  
                        <button class="transmit-button" onclick="downloadPackets()">Download Packets</button>  
                    </div>
                    <script>
                         function downloadPackets() {
                            fetch('/downloadPackets')
                                .then(response => {
                                    if (response.ok) {
                                        return response.blob();
                                    }
                                    throw new Error('Network response was not ok.');
                                })
                                .then(blob => {
                                    const url = window.URL.createObjectURL(blob);
                                    const a = document.createElement('a');
                                    a.style.display = 'none';
                                    a.href = url;
                                    a.download = 'surveydata.csv';
                                    document.body.appendChild(a);
                                    a.click();
                                    window.URL.revokeObjectURL(url);
                                })
                                .catch(error => console.error('There was a problem with the fetch operation:', error));
                        }

                    </script>
                    <script>
                        let expandedRows = {};

                        function manualUpdateTable() {
                            // Display a loading alert
                            Swal.fire({
                                title: 'Table Updated!',
                                icon: 'success'
                            });

                            updateTableData();
                        }

                        function updateTableData() {
                            fetch('/get_table_data')
                                .then(response => response.json())
                                .then(data => {
                                    const tableBody = document.getElementById('data-table').getElementsByTagName('tbody')[0];
                                    tableBody.innerHTML = ''; // Clear existing table rows
                                    for (let key in data) {
                                        let mainRow = tableBody.insertRow();
                                        let cell1 = mainRow.insertCell();
                                        let cell2 = mainRow.insertCell();
                                        let cell3 = mainRow.insertCell();
                                        let cell4 = mainRow.insertCell();
                                        cell1.innerHTML = key;
                                        let lastIndex = data[key].length - 1; // Get the index of the last entry
                                        cell2.innerHTML = data[key][lastIndex][0]; // Frequency (from the last entry)
                                        let rssiValue = data[key][lastIndex][1];
                                        cell3.innerHTML = rssiValue === 0 ? 'unknown' : rssiValue; // Signal Strength (from the last entry)

                                        //cell2.innerHTML = data[key][0][0]; // Frequency (from the first entry)
                                        
                                        // Check for RSSI value and display 'unknown' if it is 0
                                        //let rssiValue = data[key][0][1];
                                        //cell3.innerHTML = rssiValue === 0 ? 'unknown' : rssiValue; // Signal Strength (from the first entry)
                    
                                        // Create a Bootstrap styled button
                                        let expandBtn = document.createElement('button');
                                        expandBtn.classList.add('btn', 'btn-secondary', 'btn-sm'); // Bootstrap button classes
                                        expandBtn.innerHTML = 'Show Values';
                                        expandBtn.onclick = function() {
                                            let deviceKey = key; // Capture the current device key
                                            let isExpanded = !expandedRows[deviceKey]; // Toggle the expanded state
                    
                                            // Show or hide the expandable rows
                                            let nextRow = mainRow.nextSibling;
                                            while (nextRow && nextRow.classList.contains('expandable-row')) {
                                                nextRow.style.display = isExpanded ? 'table-row' : 'none';
                                                nextRow = nextRow.nextSibling;
                                            }
                    
                                            // Update the button text and expandedRows object
                                            expandBtn.innerHTML = isExpanded ? 'Hide Values' : 'Show Values';
                                            expandedRows[deviceKey] = isExpanded;
                                        };
                                        cell4.appendChild(expandBtn);
                                        cell4.style.textAlign = 'center'; // Center align the button
                    
                                        // Add expandable rows for each decoded value
                                        data[key].forEach(entry => {
                                            let expandableRow = tableBody.insertRow();
                                            expandableRow.classList.add('expandable-row');
                                            expandableRow.style.display = 'none'; // Initially hidden
                                            let cell = expandableRow.insertCell();
                                            cell.colSpan = "4";
                                            cell.innerHTML = `Decoded Value: ${entry[2]}`;
                                        });
                    
                                        if (expandedRows[key]) {
                                            let nextRow = mainRow.nextSibling;
                                            while (nextRow && nextRow.classList.contains('expandable-row')) {
                                                nextRow.style.display = 'table-row';
                                                nextRow = nextRow.nextSibling;
                                            }
                                        }
                                    }
                                })
                                .catch(error => console.error('Error:', error));
                        }
                    
                        // Initial update of the table
                        updateTableData();
                    
                        // Periodically update the table every 30 seconds (30000 milliseconds)
                        setInterval(updateTableData, 30000);
                    </script>
                    
                    
            </section>
            <hr class="m-0" />
            
    </body>
</html>
