{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>Configuration</h1>
            <p>Manage application settings and preferences.</p>
            
            <!-- General Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>General Settings</h5>
                </div>
                <div class="card-body">
                    <form id="general-config-form">
                        <div class="mb-3">
                            <label for="app-name" class="form-label">Application Name</label>
                            <input type="text" class="form-control" id="app-name" value="{{ config.app_name or 'MbetterClient' }}">
                        </div>
                        <div class="mb-3">
                            <label for="log-level" class="form-label">Log Level</label>
                            <select class="form-select" id="log-level">
                                <option value="DEBUG" {% if config.log_level == 'DEBUG' %}selected{% endif %}>DEBUG</option>
                                <option value="INFO" {% if config.log_level == 'INFO' %}selected{% endif %}>INFO</option>
                                <option value="WARNING" {% if config.log_level == 'WARNING' %}selected{% endif %}>WARNING</option>
                                <option value="ERROR" {% if config.log_level == 'ERROR' %}selected{% endif %}>ERROR</option>
                            </select>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="enable-qt" {% if config.enable_qt %}checked{% endif %}>
                            <label class="form-check-label" for="enable-qt">
                                Enable Qt Video Player
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary">Save General Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Video Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Video Settings</h5>
                </div>
                <div class="card-body">
                    <form id="video-config-form">
                        <div class="mb-3">
                            <label for="video-width" class="form-label">Video Width</label>
                            <input type="number" class="form-control" id="video-width" value="{{ config.video_width or 1920 }}">
                        </div>
                        <div class="mb-3">
                            <label for="video-height" class="form-label">Video Height</label>
                            <input type="number" class="form-control" id="video-height" value="{{ config.video_height or 1080 }}">
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="fullscreen" {% if config.fullscreen %}checked{% endif %}>
                            <label class="form-check-label" for="fullscreen">
                                Fullscreen Mode
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Video Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- API Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>API Settings</h5>
                </div>
                <div class="card-body">
                    <form id="api-config-form">
                        <div class="mb-3">
                            <label for="fastapi-url" class="form-label">FastAPI Server URL</label>
                            <input type="url" class="form-control" id="fastapi-url"
                                   value="{{ config.fastapi_url or 'https://mbetter.nexlab.net/api/updates' }}"
                                   placeholder="https://mbetter.nexlab.net/api/updates">
                            <div class="form-text">Base URL for FastAPI server requests (include https:// or http://)</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-token" class="form-label">API Access Token</label>
                            <input type="password" class="form-control" id="api-token"
                                   value="{{ config.api_token or '' }}"
                                   placeholder="Enter your API access token">
                            <div class="form-text">Authentication token for FastAPI server access</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-interval" class="form-label">Request Interval (seconds)</label>
                            <input type="number" class="form-control" id="api-interval"
                                   value="{{ config.api_interval or 1800 }}" min="30" max="86400">
                            <div class="form-text">Time between automatic API requests (30 seconds to 24 hours)</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-timeout" class="form-label">Request Timeout (seconds)</label>
                            <input type="number" class="form-control" id="api-timeout"
                                   value="{{ config.api_timeout or 30 }}" min="5" max="300">
                            <div class="form-text">Timeout for API requests (5-300 seconds)</div>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="api-enabled"
                                   {% if config.api_enabled != false %}checked{% endif %}>
                            <label class="form-check-label" for="api-enabled">
                                Enable API Client
                            </label>
                            <div class="form-text">Enable/disable automatic API requests</div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save API Settings</button>
                        <button type="button" class="btn btn-outline-secondary ms-2" id="test-api-connection">
                            Test Connection
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Screen Cast Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Screen Cast Settings</h5>
                </div>
                <div class="card-body">
                    <form id="screen-cast-config-form">
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="screen-cast-enabled"
                                   {% if config.screen_cast_enabled != false %}checked{% endif %}>
                            <label class="form-check-label" for="screen-cast-enabled">
                                Enable Screen Cast & Chromecast Streaming
                            </label>
                            <div class="form-text">Enable screen capture and Chromecast streaming functionality</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="screen-cast-port" class="form-label">Stream Port</label>
                            <input type="number" class="form-control" id="screen-cast-port"
                                   value="{{ config.screen_cast_port or 8000 }}" min="1024" max="65535">
                            <div class="form-text">Port for the HTTP streaming server (1024-65535)</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="chromecast-name" class="form-label">Preferred Chromecast Device</label>
                            <input type="text" class="form-control" id="chromecast-name"
                                   value="{{ config.chromecast_name or '' }}"
                                   placeholder="Leave empty for auto-discovery">
                            <div class="form-text">Name of preferred Chromecast device (optional)</div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="screen-cast-resolution" class="form-label">Capture Resolution</label>
                                    <select class="form-select" id="screen-cast-resolution">
                                        <option value="1920x1080" {% if config.screen_cast_resolution == '1920x1080' %}selected{% endif %}>1920x1080 (Full HD)</option>
                                        <option value="1280x720" {% if config.screen_cast_resolution == '1280x720' or not config.screen_cast_resolution %}selected{% endif %}>1280x720 (HD)</option>
                                        <option value="854x480" {% if config.screen_cast_resolution == '854x480' %}selected{% endif %}>854x480 (SD)</option>
                                        <option value="640x360" {% if config.screen_cast_resolution == '640x360' %}selected{% endif %}>640x360 (Low)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="screen-cast-framerate" class="form-label">Frame Rate (FPS)</label>
                                    <select class="form-select" id="screen-cast-framerate">
                                        <option value="30" {% if config.screen_cast_framerate == 30 %}selected{% endif %}>30 FPS</option>
                                        <option value="24" {% if config.screen_cast_framerate == 24 %}selected{% endif %}>24 FPS</option>
                                        <option value="15" {% if config.screen_cast_framerate == 15 or not config.screen_cast_framerate %}selected{% endif %}>15 FPS</option>
                                        <option value="10" {% if config.screen_cast_framerate == 10 %}selected{% endif %}>10 FPS</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="screen-cast-auto-start-capture"
                                           {% if config.screen_cast_auto_start_capture %}checked{% endif %}>
                                    <label class="form-check-label" for="screen-cast-auto-start-capture">
                                        Auto-start Screen Capture
                                    </label>
                                    <div class="form-text">Automatically start capturing when application starts</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="screen-cast-auto-start-streaming"
                                           {% if config.screen_cast_auto_start_streaming %}checked{% endif %}>
                                    <label class="form-check-label" for="screen-cast-auto-start-streaming">
                                        Auto-start Chromecast Streaming
                                    </label>
                                    <div class="form-text">Automatically start streaming when capture begins</div>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Screen Cast Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Database Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Database Settings</h5>
                </div>
                <div class="card-body">
                    <form id="database-config-form">
                        <div class="mb-3">
                            <label for="db-path" class="form-label">Database Path</label>
                            <input type="text" class="form-control" id="db-path" value="{{ config.db_path or 'data/mbetterclient.db' }}">
                        </div>
                        <button type="submit" class="btn btn-primary">Save Database Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Global Betting Mode Settings (Admin Only) -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-cog"></i> Global Betting Mode Settings</h5>
                    <small class="text-muted">Admin Only - System-wide Configuration</small>
                </div>
                <div class="card-body">
                    <form id="betting-mode-config-form">
                        <div class="mb-3">
                            <label for="betting-mode" class="form-label">Global Betting Mode</label>
                            <select class="form-select" id="betting-mode">
                                <option value="all_bets_on_start">All Bets on Start - All matches become 'bet' status when START_GAME is triggered</option>
                                <option value="one_bet_at_a_time">One Bet at a Time - Only first match becomes 'bet', others remain 'scheduled'</option>
                            </select>
                            <div class="form-text">
                                <strong>Global System Setting:</strong> Determines how START_GAME messages affect match status across all fixtures.
                                <br><small class="text-muted">This affects all users and all game sessions.</small>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Global Betting Mode</button>
                    </form>
                    <div id="betting-mode-status" class="mt-3"></div>
                </div>
            </div>
            
            <!-- API Client Debug Section -->
            <div class="card">
                <div class="card-header">
                    <h5>API Client Debug</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <button type="button" class="btn btn-info" id="check-api-status">
                            Check API Client Status
                        </button>
                        <button type="button" class="btn btn-warning ms-2" id="trigger-api-request">
                            Trigger Manual Request
                        </button>
                    </div>
                    <div id="api-status-result" class="mt-3"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Save general configuration
    document.getElementById('general-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            app_name: document.getElementById('app-name').value,
            log_level: document.getElementById('log-level').value,
            enable_qt: document.getElementById('enable-qt').checked
        };
        
        saveConfig('general', config);
    });
    
    // Save video configuration
    document.getElementById('video-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            video_width: parseInt(document.getElementById('video-width').value),
            video_height: parseInt(document.getElementById('video-height').value),
            fullscreen: document.getElementById('fullscreen').checked
        };
        
        saveConfig('video', config);
    });
    
    // Save database configuration
    document.getElementById('database-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            db_path: document.getElementById('db-path').value
        };
        
        saveConfig('database', config);
    });
    
    // Save API configuration
    document.getElementById('api-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            fastapi_url: document.getElementById('fastapi-url').value,
            api_token: document.getElementById('api-token').value,
            api_interval: parseInt(document.getElementById('api-interval').value),
            api_timeout: parseInt(document.getElementById('api-timeout').value),
            api_enabled: document.getElementById('api-enabled').checked
        };
        
        saveConfig('api', config);
    });
    
    // Save screen cast configuration
    document.getElementById('screen-cast-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            enabled: document.getElementById('screen-cast-enabled').checked,
            stream_port: parseInt(document.getElementById('screen-cast-port').value),
            chromecast_name: document.getElementById('chromecast-name').value,
            resolution: document.getElementById('screen-cast-resolution').value,
            framerate: parseInt(document.getElementById('screen-cast-framerate').value),
            auto_start_capture: document.getElementById('screen-cast-auto-start-capture').checked,
            auto_start_streaming: document.getElementById('screen-cast-auto-start-streaming').checked
        };
        
        saveConfig('screen_cast', config);
    });
    
    // Test API connection
    document.getElementById('test-api-connection').addEventListener('click', function() {
        const url = document.getElementById('fastapi-url').value;
        const token = document.getElementById('api-token').value;
        
        if (!url) {
            alert('Please enter a FastAPI URL first');
            return;
        }
        
        this.disabled = true;
        this.textContent = 'Testing...';
        
        fetch('/api/config/test-connection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                token: token
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Connection successful! Response: ' + (data.message || 'OK'));
            } else {
                alert('Connection failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Connection test failed: ' + error.message);
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Test Connection';
        });
    });
    
    // Generic config save function
    function saveConfig(section, config) {
        fetch('/api/config/' + section, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(config)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(section.charAt(0).toUpperCase() + section.slice(1) + ' configuration saved successfully');
            } else {
                alert('Failed to save ' + section + ' configuration: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to save ' + section + ' configuration');
        });
    }
    
    // Check API client status
    document.getElementById('check-api-status').addEventListener('click', function() {
        this.disabled = true;
        this.textContent = 'Checking...';
        
        fetch('/api/api-client/status')
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('api-status-result');
            
            if (data.success) {
                const status = data.status;
                let html = '<div class="alert alert-info"><strong>API Client Status:</strong><br>';
                html += '<strong>Message Bus:</strong> ' + (status.message_bus_available ? 'Available' : 'Not Available') + '<br>';
                html += '<strong>Config Manager:</strong> ' + (status.config_manager_available ? 'Available' : 'Not Available') + '<br>';
                
                if (status.api_config) {
                    html += '<strong>API Configuration:</strong><br>';
                    html += '&nbsp;&nbsp;URL: ' + (status.api_config.fastapi_url || 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Token: ' + (status.api_config.api_token_set ? 'Set' : 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Interval: ' + status.api_config.api_interval + ' seconds<br>';
                    html += '&nbsp;&nbsp;Enabled: ' + status.api_config.api_enabled + '<br>';
                }
                
                if (status.fastapi_endpoint && Object.keys(status.fastapi_endpoint).length > 0) {
                    const ep = status.fastapi_endpoint;
                    html += '<strong>FastAPI Endpoint:</strong><br>';
                    html += '&nbsp;&nbsp;URL: ' + (ep.url || 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Enabled: ' + ep.enabled + '<br>';
                    html += '&nbsp;&nbsp;Interval: ' + ep.interval + ' seconds<br>';
                    html += '&nbsp;&nbsp;Auth Configured: ' + ep.auth_configured + '<br>';
                    html += '&nbsp;&nbsp;Total Requests: ' + ep.total_requests + '<br>';
                    html += '&nbsp;&nbsp;Consecutive Failures: ' + ep.consecutive_failures + '<br>';
                    html += '&nbsp;&nbsp;Last Request: ' + (ep.last_request || 'Never') + '<br>';
                    html += '&nbsp;&nbsp;Last Success: ' + (ep.last_success || 'Never') + '<br>';
                } else {
                    html += '<strong>FastAPI Endpoint:</strong> Not configured<br>';
                }
                
                html += '</div>';
                resultDiv.innerHTML = html;
            } else {
                resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            document.getElementById('api-status-result').innerHTML =
                '<div class="alert alert-danger">Error checking status: ' + error.message + '</div>';
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Check API Client Status';
        });
    });
    
    // Trigger manual API request
    document.getElementById('trigger-api-request').addEventListener('click', function() {
        this.disabled = true;
        this.textContent = 'Triggering...';
        
        fetch('/api/api-client/trigger', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({endpoint: 'fastapi_main'})
        })
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('api-status-result');
            
            if (data.success) {
                resultDiv.innerHTML = '<div class="alert alert-success">' + data.message + '</div>';
            } else {
                resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            document.getElementById('api-status-result').innerHTML =
                '<div class="alert alert-danger">Error triggering request: ' + error.message + '</div>';
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Trigger Manual Request';
        });
    });
    
    // Load current global betting mode on page load
    document.addEventListener('DOMContentLoaded', function() {
        loadBettingMode();
    });
    
    // Load global betting mode configuration
    function loadBettingMode() {
        fetch('/api/betting-mode')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('betting-mode').value = data.betting_mode || 'all_bets_on_start';
                
                if (data.is_default) {
                    document.getElementById('betting-mode-status').innerHTML =
                        '<div class="alert alert-info"><small><i class="fas fa-info-circle"></i> Using default global betting mode</small></div>';
                } else {
                    document.getElementById('betting-mode-status').innerHTML =
                        '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Global betting mode configured</small></div>';
                }
            } else {
                console.error('Failed to load betting mode:', data.error);
                document.getElementById('betting-mode-status').innerHTML =
                    '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Could not load current betting mode</small></div>';
            }
        })
        .catch(error => {
            console.error('Error loading betting mode:', error);
            document.getElementById('betting-mode-status').innerHTML =
                '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Error loading betting mode</small></div>';
        });
    }
    
    // Save global betting mode configuration
    document.getElementById('betting-mode-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const bettingMode = document.getElementById('betting-mode').value;
        const statusDiv = document.getElementById('betting-mode-status');
        
        // Clear previous status
        statusDiv.innerHTML = '';
        
        // Save global betting mode
        fetch('/api/betting-mode', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                betting_mode: bettingMode
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                statusDiv.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '<br><small>This setting affects all users and game sessions.</small></div>';
                
                // Auto-hide success message after 5 seconds
                setTimeout(() => {
                    statusDiv.innerHTML = '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Global betting mode configured</small></div>';
                }, 5000);
            } else {
                statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Failed to save global betting mode: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            console.error('Error saving betting mode:', error);
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Error saving global betting mode: ' + error.message + '</div>';
        });
    });
</script>
{% endblock %}