const DAEMON_URL = 'http://127.0.0.1:12345';

document.addEventListener('DOMContentLoaded', () => {
    fetchInstances();
    document.getElementById('refresh-btn').addEventListener('click', fetchInstances);
});


async function fetchInstances() {
    const tableBody = document.getElementById('instances-table-body');
    
    try {
        const response = await fetch(`${DAEMON_URL}/instances/list`);
        if (!response.ok) throw new Error(`Server returned code: ${response.status}`);
        
        const instances = await response.json();
        renderTable(instances);
    } catch (error) {
        console.error('Failed fetching telemetry data:', error);
        tableBody.innerHTML = `<tr><td colspan="5" style="color: #ff5555;">Offline: Could not connect to vs-manager daemon.</td></tr>`;
    }
}


function renderTable(instances) {
    const tableBody = document.getElementById('instances-table-body');
    
    if (!instances || instances.length === 0) {
        tableBody.innerHTML = `<tr><td colspan="5">No server configurations registered.</td></tr>`;
        return;
    }

    tableBody.innerHTML = ''; 

    instances.forEach(inst => {
        const row = document.createElement('tr');
        const isRunning = inst.status === 'RUNNING';
        
        row.innerHTML = `
            <td><strong>${inst.name}</strong></td>
            <td>${inst.version}</td>
            <td>${inst.port}</td>
            <td class="${isRunning ? 'status-running' : 'status-stopped'}">${inst.status}</td>
            <td>
                <button class="action-btn" data-name="${inst.name}" data-action="${isRunning ? 'stop' : 'start'}">
                    ${isRunning ? 'Stop' : 'Start'}
                </button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });


    document.querySelectorAll('.action-btn').forEach(btn => {
        btn.addEventListener('click', handleAction);
    });
}


async function handleAction(e) {
    const button = e.target;
    const name = button.getAttribute('data-name');
    const action = button.getAttribute('data-action'); 
    
    button.disabled = true;
    button.innerText = 'Processing...';

    try {
        const response = await fetch(`${DAEMON_URL}/instances/${action}?name=${encodeURIComponent(name)}`, {
            method: 'POST'
        });

        if (!response.ok) {
            const errText = await response.text();
            alert(`Action Failed: ${errText}`);
        }
    } catch (error) {
        alert(`Network transmission failure: ${error.message}`);
    } finally {
        await fetchInstances();
    }
}