{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-file-video me-2"></i>Video Upload Test
        </h1>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-upload me-2"></i>Upload Video
                </h5>
            </div>
            <div class="card-body">
                <form id="upload-form" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="video-file" class="form-label">Select Video File</label>
                        <input class="form-control" type="file" id="video-file" accept="video/*">
                        <div class="form-text">Supported formats: MP4, AVI, MOV, MKV</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Template</label>
                        <select class="form-select" id="video-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary" id="upload-btn">
                        <i class="fas fa-upload me-1"></i>Upload Video
                    </button>
                </form>
                
                <div class="mt-4" id="upload-progress-container" style="display: none;">
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" id="upload-progress" style="width: 0%;">0%</div>
                    </div>
                    <div class="mt-2 text-center" id="upload-status">Uploading...</div>
                </div>
            </div>
        </div>
        
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-list me-2"></i>Uploaded Videos
                </h5>
            </div>
            <div class="card-body">
                <div id="uploaded-videos-list">
                    <p class="text-muted text-center">No videos uploaded yet</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-info-circle me-2"></i>Instructions
                </h5>
            </div>
            <div class="card-body">
                <ol>
                    <li>Select a video file to upload</li>
                    <li>Choose an overlay template</li>
                    <li>Click "Upload Video" to start upload</li>
                    <li><strong>After upload, click "Play in Qt Player" to view the video in the Qt player window</strong></li>
                    <li>Use "Delete" to remove uploaded videos</li>
                </ol>
                <div class="alert alert-info">
                    <i class="fas fa-lightbulb me-2"></i>
                    Videos are stored temporarily and will be deleted when the application restarts.
                </div>
                <div class="alert alert-warning">
                    <i class="fas fa-desktop me-2"></i>
                    <strong>Note:</strong> Videos play in the Qt player window, not in the web browser. Make sure the Qt player window is visible.
                </div>
            </div>
        </div>
        
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-video me-2"></i>Player Status
                </h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <span>Status:</span>
                    <span id="player-status" class="badge bg-secondary">Unknown</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <span>Current Video:</span>
                    <span id="current-video" class="text-muted">None</span>
                </div>
                <button class="btn btn-sm btn-outline-primary mt-3 w-100" id="refresh-status">
                    <i class="fas fa-sync me-1"></i>Refresh Status
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load available templates on page load
    loadAvailableTemplates();
    
    // Elements
    const uploadForm = document.getElementById('upload-form');
    const videoFileInput = document.getElementById('video-file');
    const videoTemplateSelect = document.getElementById('video-template');
    const uploadBtn = document.getElementById('upload-btn');
    const uploadProgressContainer = document.getElementById('upload-progress-container');
    const uploadProgress = document.getElementById('upload-progress');
    const uploadStatus = document.getElementById('upload-status');
    const uploadedVideosList = document.getElementById('uploaded-videos-list');
    const playerStatus = document.getElementById('player-status');
    const currentVideo = document.getElementById('current-video');
    const refreshStatusBtn = document.getElementById('refresh-status');
    
    // Store uploaded videos
    let uploadedVideos = [];
    
    // Load available templates function
    function loadAvailableTemplates() {
        fetch('/api/templates')
            .then(response => response.json())
            .then(data => {
                const templateSelect = document.getElementById('video-template');
                templateSelect.innerHTML = ''; // Clear loading option
                
                if (data.templates && Array.isArray(data.templates)) {
                    data.templates.forEach(template => {
                        const option = document.createElement('option');
                        option.value = template.name;
                        option.textContent = template.display_name || template.name;
                        templateSelect.appendChild(option);
                    });
                    
                    // Select default template if available
                    const defaultOption = templateSelect.querySelector('option[value="default"]');
                    if (defaultOption) {
                        defaultOption.selected = true;
                    }
                } else {
                    // Fallback if no templates found
                    const option = document.createElement('option');
                    option.value = 'default';
                    option.textContent = 'Default';
                    templateSelect.appendChild(option);
                }
            })
            .catch(error => {
                console.error('Error loading templates:', error);
                // Fallback template option
                const templateSelect = document.getElementById('video-template');
                templateSelect.innerHTML = '<option value="default">Default</option>';
            });
    }
    
    // Handle form submission
    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const file = videoFileInput.files[0];
        if (!file) {
            alert('Please select a video file');
            return;
        }
        
        // Check file size (limit to 100MB for demo)
        if (file.size > 100 * 1024 * 1024) {
            alert('File size exceeds 100MB limit');
            return;
        }
        
        uploadVideo(file);
    });
    
    // Upload video function
    function uploadVideo(file) {
        // Show progress
        uploadProgressContainer.style.display = 'block';
        uploadProgress.style.width = '0%';
        uploadProgress.textContent = '0%';
        uploadStatus.textContent = 'Uploading...';
        uploadBtn.disabled = true;
        
        // Create FormData
        const formData = new FormData();
        formData.append('video', file);
        formData.append('template', videoTemplateSelect.value);
        
        // Create XMLHttpRequest for progress tracking
        const xhr = new XMLHttpRequest();
        
        // Progress tracking
        xhr.upload.addEventListener('progress', function(e) {
            if (e.lengthComputable) {
                const percentComplete = Math.round((e.loaded / e.total) * 100);
                uploadProgress.style.width = percentComplete + '%';
                uploadProgress.textContent = percentComplete + '%';
            }
        });
        
        // Handle response
        xhr.addEventListener('load', function() {
            uploadBtn.disabled = false;
            
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        uploadStatus.textContent = 'Upload complete!';
                        uploadStatus.className = 'mt-2 text-center text-success';
                        
                        // Add to uploaded videos list
                        addUploadedVideo(response.filename, file.name, videoTemplateSelect.value);
                        
                        // Reset form after delay
                        setTimeout(() => {
                            uploadProgressContainer.style.display = 'none';
                            uploadForm.reset();
                        }, 2000);
                    } else {
                        uploadStatus.textContent = 'Upload failed: ' + (response.error || 'Unknown error');
                        uploadStatus.className = 'mt-2 text-center text-danger';
                    }
                } catch (e) {
                    uploadStatus.textContent = 'Upload failed: Invalid response';
                    uploadStatus.className = 'mt-2 text-center text-danger';
                }
            } else {
                uploadStatus.textContent = 'Upload failed: Server error';
                uploadStatus.className = 'mt-2 text-center text-danger';
            }
        });
        
        // Handle errors
        xhr.addEventListener('error', function() {
            uploadBtn.disabled = false;
            uploadStatus.textContent = 'Upload failed: Network error';
            uploadStatus.className = 'mt-2 text-center text-danger';
            uploadProgressContainer.style.display = 'none';
        });
        
        // Send request
        xhr.open('POST', '/api/video/upload');
        xhr.send(formData);
    }
    
    // Add uploaded video to list
    function addUploadedVideo(filename, displayName, template) {
        const videoId = 'video-' + Date.now();
        const videoItem = document.createElement('div');
        videoItem.className = 'd-flex justify-content-between align-items-center mb-3 p-3 border rounded';
        videoItem.id = videoId;
        videoItem.innerHTML = `
            <div>
                <div class="fw-bold">${displayName}</div>
                <small class="text-muted">Template: ${template}</small>
            </div>
            <div>
                <button class="btn btn-sm btn-success play-btn me-2" data-filename="${filename}" data-template="${template}">
                    <i class="fas fa-desktop me-1"></i>Play in Qt Player
                </button>
                <button class="btn btn-sm btn-danger delete-btn" data-id="${videoId}" data-filename="${filename}">
                    <i class="fas fa-trash me-1"></i>Delete
                </button>
            </div>
        `;
        
        // Add to beginning of list
        if (uploadedVideosList.querySelector('.text-muted')) {
            uploadedVideosList.innerHTML = '';
        }
        uploadedVideosList.prepend(videoItem);
        
        // Add event listeners
        videoItem.querySelector('.play-btn').addEventListener('click', playVideo);
        videoItem.querySelector('.delete-btn').addEventListener('click', deleteVideo);
        
        // Store in array
        uploadedVideos.push({
            id: videoId,
            filename: filename,
            displayName: displayName,
            template: template
        });
    }
    
    // Play video function
    function playVideo(e) {
        const filename = e.target.closest('.play-btn').dataset.filename;
        const template = e.target.closest('.play-btn').dataset.template;
        
        // Send play command to Qt player
        fetch('/api/video/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'play',
                file_path: filename,
                template: template
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update player status
                playerStatus.className = 'badge bg-success';
                playerStatus.textContent = 'Playing';
                currentVideo.textContent = filename.split('/').pop();
                
                // Show success message
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-success alert-dismissible fade show mt-3';
                alertDiv.innerHTML = `
                    <i class="fas fa-check-circle me-2"></i>
                    Video sent to Qt Player window! Check the Qt player window to view the video.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                e.target.closest('.card-body').appendChild(alertDiv);
                
                // Auto-dismiss after 5 seconds
                setTimeout(() => {
                    if (alertDiv.parentNode) {
                        alertDiv.remove();
                    }
                }, 5000);
            } else {
                alert('Failed to send video to Qt Player: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    }
    
    // Delete video function
    function deleteVideo(e) {
        const videoId = e.target.closest('.delete-btn').dataset.id;
        const filename = e.target.closest('.delete-btn').dataset.filename;
        
        if (!confirm('Are you sure you want to delete this video?')) {
            return;
        }
        
        // Send delete request
        fetch('/api/video/delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                filename: filename
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Remove from list
                const videoItem = document.getElementById(videoId);
                if (videoItem) {
                    videoItem.remove();
                }
                
                // Remove from array
                uploadedVideos = uploadedVideos.filter(video => video.id !== videoId);
                
                // Show message if no videos left
                if (uploadedVideos.length === 0) {
                    uploadedVideosList.innerHTML = '<p class="text-muted text-center">No videos uploaded yet</p>';
                }
                
                alert('Video deleted successfully');
            } else {
                alert('Failed to delete video: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    }
    
    // Refresh player status
    refreshStatusBtn.addEventListener('click', function() {
        fetch('/api/video/status')
        .then(response => response.json())
        .then(data => {
            if (data.player_status) {
                playerStatus.textContent = data.player_status.charAt(0).toUpperCase() + data.player_status.slice(1);
                playerStatus.className = 'badge ' + 
                    (data.player_status === 'playing' ? 'bg-success' : 
                     data.player_status === 'paused' ? 'bg-warning' : 'bg-secondary');
                
                if (data.current_file) {
                    currentVideo.textContent = data.current_file.split('/').pop();
                } else {
                    currentVideo.textContent = 'None';
                }
            }
        })
        .catch(error => {
            console.error('Failed to get player status:', error);
        });
    });
    
    // Initialize player status
    refreshStatusBtn.click();
});
</script>
{% endblock %}