{% 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>
            
            <!-- Database Settings -->
            <div class="card">
                <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>
            
            <!-- 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);
    });
    
    // 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';
        });
    });
</script>
{% endblock %}