/**
 * AniWorld - Logging Config Module
 *
 * Handles logging configuration, log file management, and log viewing.
 *
 * Dependencies: constants.js, api-client.js, ui-utils.js
 */

var AniWorld = window.AniWorld || {};

AniWorld.LoggingConfig = (function() {
    'use strict';

    const API = AniWorld.Constants.API;

    /**
     * Load logging configuration
     */
    async function load() {
        try {
            const response = await AniWorld.ApiClient.get(API.LOGGING_CONFIG);
            if (!response) return;

            const data = await response.json();

            if (data.success) {
                const config = data.config;

                // Set form values
                document.getElementById('log-level').value = config.log_level || 'INFO';
                document.getElementById('enable-console-logging').checked = config.enable_console_logging !== false;
                document.getElementById('enable-console-progress').checked = config.enable_console_progress === true;
                document.getElementById('enable-fail2ban-logging').checked = config.enable_fail2ban_logging !== false;

                // Load log files
                await loadLogFiles();
            }
        } catch (error) {
            console.error('Error loading logging config:', error);
            AniWorld.UI.showToast('Failed to load logging configuration', 'error');
        }
    }

    /**
     * Load log files list
     */
    async function loadLogFiles() {
        try {
            const response = await AniWorld.ApiClient.get(API.LOGGING_FILES);
            if (!response) return;

            const data = await response.json();

            if (data.success) {
                const container = document.getElementById('log-files-list');
                container.innerHTML = '';

                if (data.files.length === 0) {
                    container.innerHTML = '<div class="log-file-item"><span>No log files found</span></div>';
                    return;
                }

                data.files.forEach(function(file) {
                    const item = document.createElement('div');
                    item.className = 'log-file-item';

                    const info = document.createElement('div');
                    info.className = 'log-file-info';

                    const name = document.createElement('div');
                    name.className = 'log-file-name';
                    name.textContent = file.name;

                    const details = document.createElement('div');
                    details.className = 'log-file-details';
                    details.textContent = 'Size: ' + file.size_mb + ' MB • Modified: ' + new Date(file.modified).toLocaleDateString();

                    info.appendChild(name);
                    info.appendChild(details);

                    const actions = document.createElement('div');
                    actions.className = 'log-file-actions';

                    const downloadBtn = document.createElement('button');
                    downloadBtn.className = 'btn btn-xs btn-secondary';
                    downloadBtn.innerHTML = '<i class="fas fa-download"></i>';
                    downloadBtn.title = 'Download';
                    downloadBtn.onclick = function() { downloadLogFile(file.name); };

                    const viewBtn = document.createElement('button');
                    viewBtn.className = 'btn btn-xs btn-secondary';
                    viewBtn.innerHTML = '<i class="fas fa-eye"></i>';
                    viewBtn.title = 'View Last 100 Lines';
                    viewBtn.onclick = function() { viewLogFile(file.name); };

                    actions.appendChild(downloadBtn);
                    actions.appendChild(viewBtn);

                    item.appendChild(info);
                    item.appendChild(actions);

                    container.appendChild(item);
                });
            }
        } catch (error) {
            console.error('Error loading log files:', error);
            AniWorld.UI.showToast('Failed to load log files', 'error');
        }
    }

    /**
     * Save logging configuration
     */
    async function save() {
        try {
            // Get current config
            const configResponse = await AniWorld.ApiClient.get(AniWorld.Constants.API.CONFIG);
            if (!configResponse) return;
            const config = await configResponse.json();

            // Update logging settings
            config.logging = {
                level: document.getElementById('log-level').value.toUpperCase(),
                file: document.getElementById('log-file').value.trim() || null,
                max_bytes: document.getElementById('log-max-bytes').value ? parseInt(document.getElementById('log-max-bytes').value) : null,
                backup_count: parseInt(document.getElementById('log-backup-count').value) || 3
            };

            // Save updated config
            const response = await AniWorld.ApiClient.put(AniWorld.Constants.API.CONFIG, config);
            if (!response) return;

            AniWorld.UI.showToast('Logging configuration saved successfully', 'success');
            await load();
        } catch (error) {
            console.error('Error saving logging config:', error);
            AniWorld.UI.showToast('Failed to save logging configuration', 'error');
        }
    }

    /**
     * Test logging functionality
     */
    async function testLogging() {
        try {
            const response = await AniWorld.ApiClient.post(API.LOGGING_TEST, {});

            if (!response) return;
            const data = await response.json();

            if (data.success) {
                AniWorld.UI.showToast('Test messages logged successfully', 'success');
                setTimeout(loadLogFiles, 1000);
            } else {
                AniWorld.UI.showToast('Failed to test logging: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error testing logging:', error);
            AniWorld.UI.showToast('Failed to test logging', 'error');
        }
    }

    /**
     * Cleanup old log files
     */
    async function cleanupLogs() {
        const days = prompt('Delete log files older than how many days?', '30');
        if (!days || isNaN(days) || days < 1) {
            AniWorld.UI.showToast('Invalid number of days', 'error');
            return;
        }

        try {
            const response = await AniWorld.ApiClient.request(API.LOGGING_CLEANUP, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ days: parseInt(days) })
            });

            if (!response) return;
            const data = await response.json();

            if (data.success) {
                AniWorld.UI.showToast(data.message, 'success');
                await loadLogFiles();
            } else {
                AniWorld.UI.showToast('Failed to cleanup logs: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error cleaning up logs:', error);
            AniWorld.UI.showToast('Failed to cleanup logs', 'error');
        }
    }

    /**
     * Download a log file
     */
    function downloadLogFile(filename) {
        const link = document.createElement('a');
        link.href = '/api/logging/files/' + encodeURIComponent(filename) + '/download';
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    /**
     * View a log file's last lines
     */
    async function viewLogFile(filename) {
        try {
            const response = await AniWorld.ApiClient.get('/api/logging/files/' + encodeURIComponent(filename) + '/tail?lines=100');
            if (!response) return;

            const data = await response.json();

            if (data.success) {
                // Create modal to show log content
                const modal = document.createElement('div');
                modal.className = 'modal';
                modal.style.display = 'block';

                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.style.maxWidth = '80%';
                modalContent.style.maxHeight = '80%';

                const header = document.createElement('div');
                header.innerHTML = '<h3>Log File: ' + filename + '</h3><p>Showing last ' + data.showing_lines + ' of ' + data.total_lines + ' lines</p>';

                const content = document.createElement('pre');
                content.style.maxHeight = '60vh';
                content.style.overflow = 'auto';
                content.style.backgroundColor = '#f5f5f5';
                content.style.padding = '10px';
                content.style.fontSize = '12px';
                content.textContent = data.lines.join('\n');

                const closeBtn = document.createElement('button');
                closeBtn.textContent = 'Close';
                closeBtn.className = 'btn btn-secondary';
                closeBtn.onclick = function() { document.body.removeChild(modal); };

                modalContent.appendChild(header);
                modalContent.appendChild(content);
                modalContent.appendChild(closeBtn);
                modal.appendChild(modalContent);
                document.body.appendChild(modal);

                // Close on background click
                modal.onclick = function(e) {
                    if (e.target === modal) {
                        document.body.removeChild(modal);
                    }
                };
            } else {
                AniWorld.UI.showToast('Failed to view log file: ' + data.error, 'error');
            }
        } catch (error) {
            console.error('Error viewing log file:', error);
            AniWorld.UI.showToast('Failed to view log file', 'error');
        }
    }

    // Public API
    return {
        load: load,
        loadLogFiles: loadLogFiles,
        save: save,
        testLogging: testLogging,
        cleanupLogs: cleanupLogs,
        downloadLogFile: downloadLogFile,
        viewLogFile: viewLogFile
    };
})();
