<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الأجهزة</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            direction: rtl;
            background-color: #f4f4f9;
            margin: 0;
            padding: 0;
        }

        h1 {
            text-align: center;
            padding: 20px;
            background-color: #5e6d77;
            color: white;
        }

        #devicesTable {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
        }

        #devicesTable th, #devicesTable td {
            padding: 12px;
            text-align: center;
            border: 1px solid #ddd;
        }

        #devicesTable th {
            background-color: #4CAF50;
            color: white;
        }

        #devicesTable tbody tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .status {
            font-weight: bold;
        }

        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 4px;
        }

        button:hover {
            background-color: #45a049;
        }

        .container {
            width: 90%;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin: 20px 0;
        }
    </style>
</head>
<body>

    <div class="header">
        <h1>إدارة الأجهزة المتصلة</h1>
    </div>

    <div class="container">
        <table id="devicesTable">
            <thead>
                <tr>
                    <th>معرف الجهاز</th>
                    <th>الرقم التسلسلي</th>
                    <th>عنوان MAC</th>
                    <th>الحالة</th>
                    <th>إجراءات</th>
                </tr>
            </thead>
            <tbody>
                <!-- سيتم إضافة الأجهزة هنا عبر JavaScript -->
            </tbody>
        </table>
    </div>

    <script>
        var websocket;

        // دالة لإنشاء اتصال WebSocket بالجهاز
        function connectWebSocket(deviceId) {
            // إنشاء اتصال WebSocket
            websocket = new WebSocket(`ws://localhost:8080/ws/${deviceId}`);
            
            // عند فتح الاتصال، تحديث حالة الجهاز إلى "متصل"
            websocket.onopen = function(event) {
                console.log("تم الاتصال بالجهاز: " + deviceId);
                updateRowStatus(deviceId, "متصل");
            };
            
            // عند استقبال رسالة عبر WebSocket
            websocket.onmessage = function(event) {
                var message = JSON.parse(event.data);
                console.log("تم استلام رسالة من الجهاز: ", message);
                // تحديث حالة الجهاز عند تلقي heartbeat
                if (message.heartbeat) {
                    updateRowStatus(deviceId, "متصل");
                }
            };
            
            // عند إغلاق الاتصال، تحديث حالة الجهاز إلى "غير متصل"
            websocket.onclose = function(event) {
                console.log("تم قطع الاتصال بالجهاز: " + deviceId);
                updateRowStatus(deviceId, "غير متصل");
            };
            
            // في حالة حدوث خطأ
            websocket.onerror = function(error) {
                console.error("خطأ في الاتصال بالجهاز: " + deviceId, error);
                updateRowStatus(deviceId, "غير متصل");
            };
        }

        // دالة لتحديث حالة الجهاز في الجدول
        function updateRowStatus(deviceId, status) {
            var row = document.querySelector(`#device-${deviceId}`);
            if (row) {
                row.querySelector('.status').innerText = status;
            }
        }

        // تحميل الأجهزة عند فتح الصفحة
        async function loadDevices() {
            const response = await fetch("/api/devices");
            const devices = await response.json();
            devices.forEach(device => {
                const statusText = device.status;
                const row = document.createElement("tr");
                row.id = `device-${device.device_id}`;
                row.innerHTML = `
                    <td>${device.device_id}</td>
                    <td>${device.serial_number}</td>
                    <td>${device.mac_address}</td>
                    <td class="status">${statusText}</td>
                    <td><button onclick="connectWebSocket('${device.device_id}')">اتصال</button></td>
                `;
                document.querySelector("#devicesTable tbody").appendChild(row);
            });
        }

        // تحميل البيانات عند فتح الصفحة
        window.onload = loadDevices;
    </script>

</body>
</html>
