<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RDP - %s</title>
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="/rdpwasm/rdp.wasm.js"></script>
    <script src="/rdpwasm/clipboard.js"></script>
    <script src="/rdpwasm/out_stream.js"></script>
    <script src="/rdpwasm/rdp_graphics.js"></script>
    <script src="/rdpwasm/reversed_layouts.js"></script>
    <script src="/rdpwasm/scancodes.js"></script>
    <style>
        .navbar-brand {
            font-weight: bold;
        }
        .rdp-container {
            background-color: #1e1e1e;
            color: #f8f8f2;
            border-radius: 8px;
            height: calc(100vh - 200px);
            min-height: 400px;
            overflow: hidden;
            position: relative;
        }
        .rdp-container.full-size {
            overflow: auto;
            max-height: none;
            height: auto;
        }
        .rdp-container.full-size #canvas {
            min-width: fit-content;
            min-height: fit-content;
        }
        /* GNOME-like window decorations */
        .rdp-window {
            border: 1px solid #ccc;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .window-titlebar {
            background: linear-gradient(to bottom, #f0f0f0, #e0e0e0);
            border-bottom: 1px solid #ccc;
            padding: 4px 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 32px;
        }
        .window-title {
            font-weight: bold;
            color: #333;
            font-size: 14px;
        }
        .window-controls {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .window-btn {
            width: 24px;
            height: 24px;
            border: none;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
        }
        .window-btn:hover {
            transform: scale(1.1);
        }
        .close-btn {
            background: #ff605c;
            color: white;
        }
        .close-btn:hover {
            background: #ff403c;
        }
        .maximize-btn {
            background: #28ca42;
            color: white;
        }
        .maximize-btn:hover {
            background: #24b83a;
        }
        .minimize-btn {
            background: #ffbd44;
            color: white;
            display: none; /* Hidden by default, shown in fullscreen */
        }
        .minimize-btn:hover {
            background: #ffad2c;
        }
        .zoom-btn {
            background: #17a2b8;
            color: white;
        }
        .zoom-btn:hover {
            background: #138496;
        }
        .zoom-btn.active {
            background: #007bff;
        }
        .zoom-btn.active:hover {
            background: #0056b3;
        }
        .window-content {
            background: #1e1e1e;
            padding: 8px;
        }
        /* Fullscreen styles */
        .rdp-window.fullscreen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            border: none;
            border-radius: 0;
            z-index: 9999;
        }
        .rdp-window.fullscreen .rdp-container {
            height: calc(100vh - 40px) !important;
            min-height: calc(100vh - 40px) !important;
        }
        .rdp-window.fullscreen .minimize-btn {
            display: flex;
        }
        #canvas {
            width: 100%;
            height: 100%;
        }
        #canvasFocus {
            width: 0px;
            height: 0px;
            position: absolute;
            z-index: -10;
            padding: 0;
            margin: 0;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container">
<a class="navbar-brand" href="/">
<i class="fas fa-desktop"></i> WSSSHD control panel</a>
<div class="navbar-nav ms-auto">
<span class="navbar-text me-3">RDP Session - %s</span>
<a class="nav-link" href="/logout">Logout</a>
</div></div></nav>
<div id="notification-area" class="position-fixed top-0 end-0 p-3" style="z-index: 1050;"></div>
<div class="container mt-4">
<div class="row">
    <div class="col-12">
        <div class="rdp-window">
            <div class="window-titlebar">
                <div class="window-title">
                    <i class="fas fa-desktop"></i> RDP Session - %s
                </div>
                <div class="window-controls">
                    <button id="connectBtn" class="btn btn-success btn-sm me-1" style="height: 24px; font-size: 12px; padding: 0 8px;">
                        <i class="fas fa-play"></i> Connect
                    </button>
                    <button id="disconnectBtn" class="btn btn-danger btn-sm me-1" disabled style="height: 24px; font-size: 12px; padding: 0 8px;">
                        <i class="fas fa-stop"></i> Disconnect
                    </button>
                    <button class="window-btn zoom-btn" title="Toggle Zoom (Scale/Fit)" id="zoomBtn">
                        <i class="fas fa-search-plus"></i>
                    </button>
                    <button class="window-btn minimize-btn" title="Exit Fullscreen">_</button>
                    <button class="window-btn maximize-btn" title="Fullscreen"><span class="maximize-icon">□</span></button>
                    <button class="window-btn close-btn" title="Disconnect">×</button>
                </div>
            </div>
            <div class="window-content">
                <div id="rdp" class="rdp-container w-100">
                    <canvas id="canvas" width="1024" height="768"></canvas><input id="canvasFocus" type="text"/>
                    <div id="rdp_status" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #f8f8f2;">Click Connect to start RDP session</div>
                    <div id="rdp_loading" style="display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #f8f8f2;">
                        <div class="spinner-border text-primary mb-2" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <div>Connecting to RDP server...</div>
                        <button id="cancelConnectBtn" class="btn btn-outline-danger btn-sm mt-2" style="display: none;">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let rdpclient = null;
let socket = null;
let connected = false;

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

// Window control buttons
document.querySelector('.close-btn').addEventListener('click', disconnect);
document.querySelector('.maximize-btn').addEventListener('click', toggleFullscreen);
document.querySelector('.minimize-btn').addEventListener('click', toggleFullscreen);
document.getElementById('zoomBtn').addEventListener('click', toggleZoom);

// Input event handlers
let ecanvas = document.getElementById('canvas');
let ecanvasFocus = document.getElementById('canvasFocus');

function showNotification(message, type = 'info') {
    const notificationArea = document.getElementById('notification-area');
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    notificationArea.appendChild(notification);
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

function toggleFullscreen() {
    const rdpWindow = document.querySelector('.rdp-window');
    const maximizeBtn = document.querySelector('.maximize-btn');
    const maximizeIcon = maximizeBtn.querySelector('.maximize-icon');

    if (rdpWindow.classList.contains('fullscreen')) {
        // Exit fullscreen
        rdpWindow.classList.remove('fullscreen');
        maximizeIcon.textContent = '□';
        maximizeBtn.title = 'Fullscreen';
    } else {
        // Enter fullscreen
        rdpWindow.classList.add('fullscreen');
        maximizeIcon.textContent = '▭'; // Restore icon
        maximizeBtn.title = 'Exit Fullscreen';
    }
}

function toggleZoom() {
    if (!rdpclient || !connected) return;

    const zoomBtn = document.getElementById('zoomBtn');
    const zoomIcon = zoomBtn.querySelector('i');
    const rdpContainer = document.getElementById('rdp');

    if (zoomBtn.classList.contains('active')) {
        // Switch to scaled view (fit to window)
        zoomBtn.classList.remove('active');
        zoomBtn.title = 'Toggle Zoom (Scale/Fit)';
        zoomIcon.className = 'fas fa-search-plus';
        rdpContainer.classList.remove('full-size');

        // Enable scaling, disable clipping
        if (rdpclient.scaleViewport !== undefined) {
            rdpclient.scaleViewport = true;
        }

        showNotification('Switched to scaled view (fit to window)', 'info');
    } else {
        // Switch to full-size view with scrollbars
        zoomBtn.classList.add('active');
        zoomBtn.title = 'Toggle Zoom (Actual Size)';
        zoomIcon.className = 'fas fa-search-minus';
        rdpContainer.classList.add('full-size');

        // Disable scaling, enable clipping
        if (rdpclient.scaleViewport !== undefined) {
            rdpclient.scaleViewport = false;
        }

        showNotification('Switched to actual size view with scrollbars', 'info');
    }
}

function connect() {
    if (connected) return;

    // Hide the status text and show loading message
    document.getElementById('rdp_status').style.display = 'none';
    document.getElementById('rdp_loading').style.display = 'block';
    document.getElementById('cancelConnectBtn').style.display = 'inline-block';

    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = wsProtocol + '//' + window.location.host + '/rdp/%s/ws';

    try {
        socket = new WebSocket(wsUrl);
        socket.binaryType = 'arraybuffer';

        socket.onopen = () => {
            // Wait for WebAssembly module to be ready
            WallixModule.ready.then(() => {
                const canvas = document.getElementById('canvas');
                const gd = newRdpGraphics2D(canvas, WallixModule);
                const config = {
                    width: 1024,
                    height: 768,
                    username: '',
                    password: '',
                    domain: '',
                    bpp: 32,
                    verbosity: 0
                };
                rdpclient = new WallixModule.RdpClient(gd, config);
                rdpclient.writeFirstPacket();
                sendData();
                connected = true;
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                // Hide loading message
                document.getElementById('rdp_loading').style.display = 'none';
                showNotification('RDP session connected', 'success');
            }).catch((error) => {
                console.error('Failed to initialize WebAssembly module:', error);
                showNotification('Failed to initialize RDP client', 'danger');
                disconnect();
            });
        };

        socket.onmessage = (event) => {
            rdpclient.processInputData(event.data);
            sendData();
        };

        socket.onclose = () => {
            connected = false;
            document.getElementById('connectBtn').disabled = false;
            document.getElementById('disconnectBtn').disabled = true;
            // Reset UI to initial state
            document.getElementById('rdp_status').style.display = 'block';
            document.getElementById('rdp_loading').style.display = 'none';
            document.getElementById('cancelConnectBtn').style.display = 'none';
            showNotification('RDP session disconnected', 'info');
            rdpclient = null;
            socket = null;
        };

        socket.onerror = (e) => {
            console.error('RDP WebSocket error:', e);
            showNotification('RDP connection error', 'danger');
        };

    } catch (e) {
        console.error('Failed to create RDP client:', e);
        showNotification('Failed to connect RDP: ' + e.message, 'danger');
    }

    function sendData() {
        if (socket && socket.readyState === WebSocket.OPEN && rdpclient) {
            const data = rdpclient.getOutputData();
            if (data && data.length > 0) {
                socket.send(data);
            }
        }
    }
}

function disconnect() {
    if (socket) {
        socket.close();
        socket = null;
    }
    if (rdpclient) {
        rdpclient = null;
    }
    connected = false;
    document.getElementById('connectBtn').disabled = false;
    document.getElementById('disconnectBtn').disabled = true;
    // Reset UI to initial state
    document.getElementById('rdp_status').style.display = 'block';
    document.getElementById('rdp_loading').style.display = 'none';
    document.getElementById('cancelConnectBtn').style.display = 'none';
    setTimeout(() => {
        location.reload();
    }, 3000);
}

function cancelConnect() {
    if (socket) {
        socket.close();
        socket = null;
    }
    if (rdpclient) {
        rdpclient = null;
    }
    connected = false;
    document.getElementById('connectBtn').disabled = false;
    document.getElementById('disconnectBtn').disabled = true;
    // Reset UI to initial state
    document.getElementById('rdp_status').style.display = 'block';
    document.getElementById('rdp_loading').style.display = 'none';
    document.getElementById('cancelConnectBtn').style.display = 'none';
    showNotification('RDP connection cancelled', 'warning');
}
</script>
</body>
</html>