{% 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 Controls
                </h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span>Status:</span>
                    <span id="player-status" class="badge bg-secondary">Unknown</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span>Current Video:</span>
                    <span id="current-video" class="text-muted">None</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span>Looping:</span>
                    <span id="loop-status" class="badge bg-secondary">Off</span>
                </div>
                
                <!-- Real-time Template Switcher -->
                <div class="mb-3">
                    <label class="form-label">Live Template Switch</label>
                    <select class="form-select" id="live-template-select" disabled>
                        <option value="">Select template...</option>
                    </select>
                    <div class="form-text">Change template while video is playing</div>
                </div>
                
                <!-- Player Controls -->
                <div class="btn-group w-100 mb-3" role="group">
                    <button class="btn btn-outline-success" id="play-loop-btn">
                        <i class="fas fa-repeat me-1"></i>Play Loop
                    </button>
                    <button class="btn btn-outline-danger" id="stop-btn">
                        <i class="fas fa-stop me-1"></i>Stop
                    </button>
                </div>
                
                <button class="btn btn-sm btn-outline-primary 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();
    loadLiveTemplates();
    
    // 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 loopStatus = document.getElementById('loop-status');
    const refreshStatusBtn = document.getElementById('refresh-status');
    
    // Enhanced player controls
    const liveTemplateSelect = document.getElementById('live-template-select');
    const playLoopBtn = document.getElementById('play-loop-btn');
    const stopBtn = document.getElementById('stop-btn');
    
    // Store uploaded videos
    let uploadedVideos = [];
    let isLooping = false;
    let currentPlayingVideo = null;
    
    // 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-play me-1"></i>Play Once
                </button>
                <button class="btn btn-sm btn-primary play-loop-video-btn me-2" data-filename="${filename}" data-template="${template}">
                    <i class="fas fa-repeat me-1"></i>Play Loop
                </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);
        });
    }
    
    // Play video loop function (from individual video buttons)
    function playVideoLoop(e) {
        const filename = e.target.closest('.play-loop-video-btn').dataset.filename;
        const template = e.target.closest('.play-loop-video-btn').dataset.template;
        
        startVideoLoop(filename, template);
    }
    
    // Enable player controls
    function enablePlayerControls() {
        playLoopBtn.disabled = false;
        stopBtn.disabled = false;
        liveTemplateSelect.disabled = false;
    }
    
    // Disable player controls
    function disablePlayerControls() {
        playLoopBtn.disabled = true;
        stopBtn.disabled = true;
        liveTemplateSelect.disabled = true;
        isLooping = false;
        currentPlayingVideo = null;
        updateLoopStatus(false);
    }
    
    // Start video loop function
    function startVideoLoop(filename, template) {
        fetch('/api/video/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'play_loop',
                filename: filename,
                template: template
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update player status
                playerStatus.className = 'badge bg-success';
                playerStatus.textContent = 'Playing Loop';
                currentVideo.textContent = filename.split('/').pop();
                isLooping = true;
                currentPlayingVideo = { filename, template };
                updateLoopStatus(true);
                
                // Enable live template switching
                liveTemplateSelect.disabled = false;
                stopBtn.disabled = false;
                
                showAlert('success', 'Loop playback started! Video is playing continuously in Qt Player.');
            } else {
                showAlert('danger', 'Failed to start loop playback: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            showAlert('danger', 'Error: ' + error.message);
        });
    }
    
    // Stop playback function
    function stopPlayback() {
        fetch('/api/video/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'stop_loop'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update player status
                playerStatus.className = 'badge bg-secondary';
                playerStatus.textContent = 'Stopped';
                currentVideo.textContent = 'None';
                isLooping = false;
                currentPlayingVideo = null;
                updateLoopStatus(false);
                
                showAlert('info', 'Playback stopped.');
            } else {
                showAlert('danger', 'Failed to stop playback: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            showAlert('danger', 'Error: ' + error.message);
        });
    }
    
    // Change template while playing
    function changeTemplate(template) {
        if (!template) return;
        
        fetch('/api/video/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'change_template',
                template: template
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (currentPlayingVideo) {
                    currentPlayingVideo.template = template;
                }
                showAlert('success', `Template changed to "${template}" during playback!`);
            } else {
                showAlert('danger', 'Failed to change template: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            showAlert('danger', 'Error: ' + error.message);
        });
    }
    
    // Update loop status display
    function updateLoopStatus(looping) {
        if (looping) {
            loopStatus.className = 'badge bg-success';
            loopStatus.textContent = 'On';
        } else {
            loopStatus.className = 'badge bg-secondary';
            loopStatus.textContent = 'Off';
        }
    }
    
    // Show alert function
    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show mt-3`;
        alertDiv.innerHTML = `
            <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'danger' ? 'fa-exclamation-circle' : 'fa-info-circle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // Find the player controls card body to append the alert
        const playerControlsCard = document.querySelector('#play-loop-btn').closest('.card-body');
        playerControlsCard.appendChild(alertDiv);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }
    
    // 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);
        });
    }
    
    // Load templates for live switching
    function loadLiveTemplates() {
        fetch('/api/templates')
            .then(response => response.json())
            .then(data => {
                const liveTemplateSelect = document.getElementById('live-template-select');
                liveTemplateSelect.innerHTML = '<option value="">Select template...</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;
                        liveTemplateSelect.appendChild(option);
                    });
                }
            })
            .catch(error => {
                console.error('Error loading live templates:', error);
            });
    }
    
    // Add event listeners for enhanced controls
    playLoopBtn.addEventListener('click', function() {
        if (uploadedVideos.length === 0) {
            // If no videos uploaded, start loop with a default test video
            showAlert('info', 'No videos uploaded. Starting loop with default test content...');
            startVideoLoop('test_default', 'fixtures'); // Use fixtures template as default
            return;
        }
        
        // Use the first uploaded video for loop playback
        const firstVideo = uploadedVideos[0];
        startVideoLoop(firstVideo.filename, firstVideo.template);
    });
    
    stopBtn.addEventListener('click', function() {
        stopPlayback();
        disablePlayerControls();
    });
    
    liveTemplateSelect.addEventListener('change', function(e) {
        if (e.target.value && isLooping) {
            changeTemplate(e.target.value);
        }
    });
    
    // Add event listeners for individual video loop buttons
    document.addEventListener('click', function(e) {
        if (e.target.closest('.play-loop-video-btn')) {
            playVideoLoop(e);
        }
    });
    
    // 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 %}