{% extends 'base/layout.html' %}
{% load static %}

{% block content %}
    {% include "netbox_proxbox/nodes_table/script.html" %}
    
    <script>
        const uvicornHost = "{{ configuration.netbox_proxbox.fastapi.uvicorn_host }}"
        const uvicornPort = "{{ configuration.netbox_proxbox.fastapi.uvicorn_port }}"

        const fastapiEndpoint = `https://${uvicornHost}:${uvicornPort}`
        const websocketEndpoint = `wss://${uvicornHost}:${uvicornPort}/ws/virtual-machine`

        // Instantiate WebSocket connection to FastAPI backend.
        let ws = new WebSocket(websocketEndpoint);

        // A flag to track the connection state
        let isConnected = false;


        // Event handler for when the WebSocket connection is established
        ws.onopen = function(event) {
            console.log('WebSocket is connected');
            isConnected = true;
        };

        ws.onmessage = function(event) {
            // Add WebSockets Messages came from FasstAPI backend on GUI
            console.log(event.data)

            let jsonMessage = undefined

            try {
                jsonMessage = JSON.parse(event.data)
            } catch (error) {
                // do nothing
                console.log("Could not parse JSON message.")
            }

            if (jsonMessage) {
                if (jsonMessage.object == "virtual_machine") {
                    populateVirtualMachinesTable(jsonMessage)
                } else if (jsonMessage.object == "device") {
                    console.log(jsonMessage)
                }
            }
        }

        ws.onerror = function(error) {
            console.log("WebSocket Error: " + error)
        }

        function syncNodes(event) {
            if (!isConnected) {
                console.log("WebSocket is not connected.")
                return
            } else {
                ws.send("Sync Nodes")
                event.preventDefault()
            }
        }
    </script>


    <div class="d-flex justify-content-center flex-nowrap" style="margin-bottom: 15px;">
        <h2>
            Proxmox Nodes (Devices)
        </h2>
    </div>

    <div style="margin-bottom: 15px;" class="d-flex justify-content-center noprint">
        <form class="m-2" action="" onsubmit="syncNodes(event)">
            {% if perms.netbox_proxbox.add_proxmoxvm %}
                <button id="full-update-button" class="btn btn-primary">Sync Nodes</button>
            {% endif %}
        </form>
    </div>

    {% include "netbox_proxbox/nodes_table/table.html" %}
{% endblock %}