{% 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="news_template">News Template</option>
                            <option value="sports_template">Sports Template</option>
                            <option value="simple_template">Simple Template</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>After upload, click "Play" to view the video</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>
        </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>

<!-- Video Player Modal -->
<div class="modal fade" id="videoPlayerModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Video Player</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="video-player-container" style="position: relative; width: 100%; height: 0; padding-bottom: 56.25%;">
                    <video id="video-player" controls style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
                        Your browser does not support the video tag.
                    </video>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 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');
    const videoPlayer = document.getElementById('video-player');
    
    // Store uploaded videos
    let uploadedVideos = [];
    
    // 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-play me-1"></i>Play
                </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) {
                // Show player modal
                new bootstrap.Modal(document.getElementById('videoPlayerModal')).show();
                
                // Update player status
                playerStatus.className = 'badge bg-success';
                playerStatus.textContent = 'Playing';
                currentVideo.textContent = filename.split('/').pop();
            } else {
                alert('Failed to play video: ' + (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 %}