{% extends "base.html" %}

{% block title %}Screen Cast - {{ super() }}{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cast me-2"></i>Screen Cast Management</h2>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-secondary" onclick="refreshStatus()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                    <button type="button" class="btn btn-outline-primary" onclick="discoverChromecasts()">
                        <i class="fas fa-search"></i> Discover Devices
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Status Panel -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Status</h5>
                </div>
                <div class="card-body">
                    <div class="row" id="statusPanel">
                        <div class="col-md-3">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h6 class="card-title">Capture</h6>
                                    <div id="captureStatus" class="badge badge-secondary">Stopped</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h6 class="card-title">Streaming</h6>
                                    <div id="streamingStatus" class="badge badge-secondary">Stopped</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h6 class="card-title">Chromecast</h6>
                                    <div id="chromecastStatus" class="badge badge-secondary">Disconnected</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-light">
                                <div class="card-body text-center">
                                    <h6 class="card-title">Stream Port</h6>
                                    <div id="streamPort">8000</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Control Panel -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-video me-2"></i>Screen Capture</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="resolution" class="form-label">Resolution</label>
                        <select class="form-select" id="resolution">
                            <option value="1280x720">1280x720 (HD)</option>
                            <option value="1920x1080">1920x1080 (Full HD)</option>
                            <option value="2560x1440">2560x1440 (QHD)</option>
                            <option value="3840x2160">3840x2160 (4K)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="framerate" class="form-label">Frame Rate</label>
                        <select class="form-select" id="framerate">
                            <option value="15">15 FPS</option>
                            <option value="24">24 FPS</option>
                            <option value="30">30 FPS</option>
                            <option value="60">60 FPS</option>
                        </select>
                    </div>
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="button" class="btn btn-success" id="startCaptureBtn" onclick="startCapture()">
                            <i class="fas fa-play"></i> Start Capture
                        </button>
                        <button type="button" class="btn btn-danger" id="stopCaptureBtn" onclick="stopCapture()" disabled>
                            <i class="fas fa-stop"></i> Stop Capture
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cast me-2"></i>Chromecast Streaming</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="chromecastDevice" class="form-label">Chromecast Device</label>
                        <select class="form-select" id="chromecastDevice">
                            <option value="">Select device...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">
                            <i class="fas fa-info-circle"></i> 
                            Stream URL: <span id="streamUrl">http://localhost:8000/stream.mp4</span>
                        </small>
                    </div>
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="button" class="btn btn-success" id="startStreamingBtn" onclick="startStreaming()">
                            <i class="fas fa-play"></i> Start Streaming
                        </button>
                        <button type="button" class="btn btn-danger" id="stopStreamingBtn" onclick="stopStreaming()" disabled>
                            <i class="fas fa-stop"></i> Stop Streaming
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Panel -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cog me-2"></i>Settings</h5>
                </div>
                <div class="card-body">
                    <form id="settingsForm">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="settingsStreamPort" class="form-label">Stream Port</label>
                                    <input type="number" class="form-control" id="settingsStreamPort" value="8000" min="1024" max="65535">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="settingsChromecastName" class="form-label">Default Chromecast Name</label>
                                    <input type="text" class="form-control" id="settingsChromecastName" placeholder="Living Room">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <div class="form-check mt-4">
                                        <input class="form-check-input" type="checkbox" id="autoStartCapture">
                                        <label class="form-check-label" for="autoStartCapture">
                                            Auto-start capture on startup
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Error/Success Messages -->
    <div id="messageContainer"></div>
</div>

<script>
// Screen Cast Management JavaScript
let statusUpdateInterval;

document.addEventListener('DOMContentLoaded', function() {
    refreshStatus();
    loadSettings();
    discoverChromecasts();
    
    // Auto-refresh status every 5 seconds
    statusUpdateInterval = setInterval(refreshStatus, 5000);
    
    // Settings form handler
    document.getElementById('settingsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveSettings();
    });
});

function refreshStatus() {
    fetch('/screen_cast/api/screen_cast/status')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateStatusDisplay(data.status);
            } else {
                showMessage('Error getting status: ' + data.error, 'danger');
            }
        })
        .catch(error => {
            showMessage('Connection error: ' + error.message, 'danger');
        });
}

function updateStatusDisplay(status) {
    // Update status badges
    document.getElementById('captureStatus').textContent = status.capture_active ? 'Active' : 'Stopped';
    document.getElementById('captureStatus').className = 'badge ' + (status.capture_active ? 'badge-success' : 'badge-secondary');
    
    document.getElementById('streamingStatus').textContent = status.streaming_active ? 'Active' : 'Stopped';
    document.getElementById('streamingStatus').className = 'badge ' + (status.streaming_active ? 'badge-success' : 'badge-secondary');
    
    document.getElementById('chromecastStatus').textContent = status.chromecast_connected ? 'Connected' : 'Disconnected';
    document.getElementById('chromecastStatus').className = 'badge ' + (status.chromecast_connected ? 'badge-success' : 'badge-secondary');
    
    document.getElementById('streamPort').textContent = status.stream_port;
    
    // Update button states
    document.getElementById('startCaptureBtn').disabled = status.capture_active;
    document.getElementById('stopCaptureBtn').disabled = !status.capture_active;
    document.getElementById('startStreamingBtn').disabled = status.streaming_active || !status.chromecast_connected;
    document.getElementById('stopStreamingBtn').disabled = !status.streaming_active;
    
    // Update stream URL with correct IP
    const streamHost = status.local_ip || 'localhost';
    document.getElementById('streamUrl').textContent = `http://${streamHost}:${status.stream_port}/stream.mp4`;
    
    // Show errors if any
    if (status.last_error) {
        showMessage('Error: ' + status.last_error, 'warning');
    }
}

function startCapture() {
    const resolution = document.getElementById('resolution').value;
    const framerate = parseInt(document.getElementById('framerate').value);
    
    fetch('/screen_cast/api/screen_cast/start_capture', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            resolution: resolution,
            framerate: framerate
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            refreshStatus();
        } else {
            showMessage('Error starting capture: ' + data.error, 'danger');
        }
    })
    .catch(error => {
        showMessage('Connection error: ' + error.message, 'danger');
    });
}

function stopCapture() {
    fetch('/screen_cast/api/screen_cast/stop_capture', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            refreshStatus();
        } else {
            showMessage('Error stopping capture: ' + data.error, 'danger');
        }
    })
    .catch(error => {
        showMessage('Connection error: ' + error.message, 'danger');
    });
}

function startStreaming() {
    fetch('/screen_cast/api/screen_cast/start_streaming', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            refreshStatus();
        } else {
            showMessage('Error starting streaming: ' + data.error, 'danger');
        }
    })
    .catch(error => {
        showMessage('Connection error: ' + error.message, 'danger');
    });
}

function stopStreaming() {
    fetch('/screen_cast/api/screen_cast/stop_streaming', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            refreshStatus();
        } else {
            showMessage('Error stopping streaming: ' + data.error, 'danger');
        }
    })
    .catch(error => {
        showMessage('Connection error: ' + error.message, 'danger');
    });
}

function discoverChromecasts() {
    fetch('/screen_cast/api/screen_cast/discover_chromecasts')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('chromecastDevice');
                select.innerHTML = '<option value="">Select device...</option>';
                
                data.chromecasts.forEach(device => {
                    const option = document.createElement('option');
                    option.value = device.name;
                    option.textContent = `${device.name} (${device.type})`;
                    select.appendChild(option);
                });
                
                showMessage(`Found ${data.chromecasts.length} Chromecast device(s)`, 'info');
            } else {
                showMessage('Error discovering devices: ' + data.error, 'warning');
            }
        })
        .catch(error => {
            showMessage('Connection error: ' + error.message, 'danger');
        });
}

function loadSettings() {
    fetch('/screen_cast/api/screen_cast/settings')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settings = data.settings;
                document.getElementById('settingsStreamPort').value = settings.stream_port;
                document.getElementById('settingsChromecastName').value = settings.chromecast_name || '';
                document.getElementById('autoStartCapture').checked = settings.auto_start_capture;
            }
        })
        .catch(error => {
            console.error('Error loading settings:', error);
        });
}

function saveSettings() {
    const settings = {
        stream_port: parseInt(document.getElementById('settingsStreamPort').value),
        chromecast_name: document.getElementById('settingsChromecastName').value,
        auto_start_capture: document.getElementById('autoStartCapture').checked
    };
    
    fetch('/screen_cast/api/screen_cast/settings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(settings)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
        } else {
            showMessage('Error saving settings: ' + data.error, 'danger');
        }
    })
    .catch(error => {
        showMessage('Connection error: ' + error.message, 'danger');
    });
}

function showMessage(message, type) {
    const container = document.getElementById('messageContainer');
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    container.appendChild(alert);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}

// Cleanup on page unload
window.addEventListener('beforeunload', function() {
    if (statusUpdateInterval) {
        clearInterval(statusUpdateInterval);
    }
});
</script>

{% endblock %}