{% extends "base.html" %}

{% block title %}Terminal - {{ client_id }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h3 class="card-title mb-0">
                    <i class="fas fa-terminal"></i> SSH Terminal - {{ client_id }}
                </h3>
                <div>
                    <input type="text" id="sshUsername" class="form-control form-control-sm d-inline-block w-auto me-2" placeholder="Username" value="root">
                    <button id="connectBtn" class="btn btn-success btn-sm">
                        <i class="fas fa-play"></i> Connect
                    </button>
                    <button id="disconnectBtn" class="btn btn-danger btn-sm" disabled>
                        <i class="fas fa-stop"></i> Disconnect
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div id="terminal" class="terminal-container"></div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let term = null;
let connected = false;
let requestId = null;
let pollInterval = null;

document.getElementById('connectBtn').addEventListener('click', connect);
document.getElementById('disconnectBtn').addEventListener('click', disconnect);

function connect() {
    const username = document.getElementById('sshUsername').value;
    if (!username) {
        alert('Please enter a username');
        return;
    }

    // Initialize xterm
    if (!term) {
        term = new Terminal();
        term.open(document.getElementById('terminal'));
    }

    term.write('Connecting to ' + username + '@{{ client_id }}...\r\n');

    connected = true;
    document.getElementById('connectBtn').disabled = true;
    document.getElementById('disconnectBtn').disabled = false;
    document.getElementById('sshUsername').disabled = true;

    // Send connect request
    fetch('/terminal/{{ client_id }}/connect', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'username=' + encodeURIComponent(username)
    })
    .then(response => response.json())
    .then(data => {
        if (data.request_id) {
            requestId = data.request_id;
            if (data.command) {
                term.write('Launching: ' + data.command + '\r\n');
            }
            term.write('Connected successfully!\r\n$ ');
            // Start polling for data
            pollInterval = setInterval(pollData, 500);
        } else {
            term.write('Error: ' + data.error + '\r\n');
            disconnect();
        }
    })
    .catch(error => {
        term.write('Connection failed: ' + error + '\r\n');
        disconnect();
    });

    // Handle input
    term.onData(data => {
        if (!connected || !requestId) return;
        fetch('/terminal/{{ client_id }}/data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'request_id=' + encodeURIComponent(requestId) + '&data=' + encodeURIComponent(data)
        });
    });
}

function disconnect() {
    connected = false;
    document.getElementById('connectBtn').disabled = false;
    document.getElementById('disconnectBtn').disabled = true;
    document.getElementById('sshUsername').disabled = false;

    if (pollInterval) {
        clearInterval(pollInterval);
        pollInterval = null;
    }

    if (requestId) {
        fetch('/terminal/{{ client_id }}/disconnect', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'request_id=' + encodeURIComponent(requestId)
        });
        requestId = null;
    }

    if (term) {
        term.write('\r\nDisconnected.\r\n');
    }
}

function pollData() {
    if (!requestId) return;
    fetch('/terminal/{{ client_id }}/data?request_id=' + encodeURIComponent(requestId))
    .then(response => response.text())
    .then(data => {
        if (data) {
            term.write(data);
        }
    });
}

// Focus on terminal when connected
document.addEventListener('keydown', function(e) {
    if (connected && term) {
        term.focus();
    }
});
</script>
{% endblock %}