File dashboard-module.js of Package PersistenceOS

/**
 * PersistenceOS Dashboard Module
 * Handles system statistics, overview components, and dashboard functionality
 * 
 * Depends on: core-utils.js, auth-module.js
 */

// =============================================================================
// DASHBOARD STATE
// =============================================================================

const dashboardState = {
    systemStats: {
        uptime: '10 days, 4 hours',
        version: 'PersistenceOS 6.1',
        hostname: 'localhost.localdomain',
        cpuUsage: 45,
        memoryUsage: 60,
        storageUsage: 30,
        memoryTotal: 0,
        memoryUsed: 0,
        storageTotal: 0,
        storageUsed: 0,
        source: 'fallback'
    },
    systemInfo: {
        version: 'PersistenceOS 6.1',
        kernel: '5.14.21-150400.24.76-default',
        hostname: 'localhost.localdomain',
        uptime: '10 days, 4 hours',
        cpu: 'Intel Xeon E5-2680 v4 @ 2.40GHz',
        memory: '16 GB'
    },
    isLoading: false,
    lastUpdate: null,
    refreshInterval: null
};

// =============================================================================
// SYSTEM STATISTICS FUNCTIONS
// =============================================================================

/**
 * Fetch system statistics from API
 * @returns {Promise<object>}
 */
async function fetchSystemStats() {
    console.log('🔄 Fetching real system stats from API...');
    
    dashboardState.isLoading = true;
    
    try {
        const data = await PersistenceCore.apiGet('/system/stats');
        console.log('✅ Real system stats loaded:', data);
        
        // Update system stats with real data
        dashboardState.systemStats = {
            hostname: data.hostname || 'localhost.localdomain',
            version: data.version || 'PersistenceOS 6.1.0',
            uptime: data.uptime || 'Unknown',
            cpuUsage: data.cpuUsage || 0,
            memoryUsage: data.memoryUsage || 0,
            storageUsage: data.storageUsage || 0,
            memoryTotal: data.memoryTotal || 0,
            memoryUsed: data.memoryUsed || 0,
            storageTotal: data.storageTotal || 0,
            storageUsed: data.storageUsed || 0,
            source: data.source || 'api'
        };
        
        console.log(`📊 System Stats: CPU=${data.cpuUsage}%, Memory=${data.memoryUsage}%, Storage=${data.storageUsage}%`);
        dashboardState.lastUpdate = new Date();
        
        return dashboardState.systemStats;
        
    } catch (error) {
        console.error('❌ Error fetching system stats:', error);
        
        // Use fallback values on error
        dashboardState.systemStats = {
            ...dashboardState.systemStats,
            uptime: 'Unknown',
            cpuUsage: 25,
            memoryUsage: 45,
            storageUsage: 35,
            source: 'error'
        };
        
        PersistenceCore.showNotification('Failed to load system stats', 'warning');
        return dashboardState.systemStats;
        
    } finally {
        dashboardState.isLoading = false;
    }
}

/**
 * Get system health status based on current metrics
 * @returns {object}
 */
function getSystemHealth() {
    const stats = dashboardState.systemStats;
    
    let status = 'healthy';
    let issues = [];
    
    // Check CPU usage
    if (stats.cpuUsage > 90) {
        status = 'critical';
        issues.push('High CPU usage');
    } else if (stats.cpuUsage > 70) {
        status = 'warning';
        issues.push('Elevated CPU usage');
    }
    
    // Check memory usage
    if (stats.memoryUsage > 95) {
        status = 'critical';
        issues.push('Critical memory usage');
    } else if (stats.memoryUsage > 80) {
        if (status !== 'critical') status = 'warning';
        issues.push('High memory usage');
    }
    
    // Check storage usage
    if (stats.storageUsage > 95) {
        status = 'critical';
        issues.push('Critical storage usage');
    } else if (stats.storageUsage > 85) {
        if (status !== 'critical') status = 'warning';
        issues.push('High storage usage');
    }
    
    return {
        status,
        issues,
        lastCheck: dashboardState.lastUpdate
    };
}

/**
 * Get formatted system uptime
 * @returns {string}
 */
function getFormattedUptime() {
    const uptime = dashboardState.systemStats.uptime;
    if (!uptime || uptime === 'Unknown') {
        return 'Unknown';
    }
    
    // If uptime is already formatted, return as-is
    if (typeof uptime === 'string' && uptime.includes('day')) {
        return uptime;
    }
    
    // If uptime is in seconds, format it
    if (typeof uptime === 'number') {
        const days = Math.floor(uptime / 86400);
        const hours = Math.floor((uptime % 86400) / 3600);
        const minutes = Math.floor((uptime % 3600) / 60);
        
        if (days > 0) {
            return `${days} days, ${hours} hours`;
        } else if (hours > 0) {
            return `${hours} hours, ${minutes} minutes`;
        } else {
            return `${minutes} minutes`;
        }
    }
    
    return uptime;
}

/**
 * Get system resource summary
 * @returns {object}
 */
function getResourceSummary() {
    const stats = dashboardState.systemStats;
    
    return {
        cpu: {
            usage: stats.cpuUsage,
            status: stats.cpuUsage > 80 ? 'high' : stats.cpuUsage > 50 ? 'medium' : 'low',
            color: PersistenceCore.getUsageColor(stats.cpuUsage)
        },
        memory: {
            usage: stats.memoryUsage,
            total: PersistenceCore.formatBytes(stats.memoryTotal),
            used: PersistenceCore.formatBytes(stats.memoryUsed),
            status: stats.memoryUsage > 80 ? 'high' : stats.memoryUsage > 50 ? 'medium' : 'low',
            color: PersistenceCore.getUsageColor(stats.memoryUsage)
        },
        storage: {
            usage: stats.storageUsage,
            total: PersistenceCore.formatBytes(stats.storageTotal),
            used: PersistenceCore.formatBytes(stats.storageUsed),
            status: stats.storageUsage > 85 ? 'high' : stats.storageUsage > 60 ? 'medium' : 'low',
            color: PersistenceCore.getUsageColor(stats.storageUsage)
        }
    };
}

// =============================================================================
// DASHBOARD REFRESH FUNCTIONS
// =============================================================================

/**
 * Start automatic dashboard refresh
 */
function startDashboardRefresh() {
    console.log('🔄 Starting dashboard auto-refresh...');
    
    // Clear existing interval
    if (dashboardState.refreshInterval) {
        clearInterval(dashboardState.refreshInterval);
    }
    
    // Set up new refresh interval
    dashboardState.refreshInterval = setInterval(async () => {
        if (!dashboardState.isLoading) {
            await fetchSystemStats();
            
            // Trigger custom event for Vue.js reactivity
            window.dispatchEvent(new CustomEvent('dashboard-stats-updated', {
                detail: dashboardState.systemStats
            }));
        }
    }, PersistenceCore.config.REFRESH_INTERVALS.SYSTEM_STATS);
    
    // Initial fetch
    fetchSystemStats();
}

/**
 * Stop automatic dashboard refresh
 */
function stopDashboardRefresh() {
    console.log('âšī¸ Stopping dashboard auto-refresh...');
    
    if (dashboardState.refreshInterval) {
        clearInterval(dashboardState.refreshInterval);
        dashboardState.refreshInterval = null;
    }
}

/**
 * Manually refresh dashboard data
 * @returns {Promise<void>}
 */
async function refreshDashboard() {
    console.log('🔄 Manual dashboard refresh triggered...');
    
    try {
        await fetchSystemStats();
        PersistenceCore.showNotification('Dashboard refreshed successfully', 'success');
        
        // Trigger custom event
        window.dispatchEvent(new CustomEvent('dashboard-refreshed', {
            detail: {
                timestamp: new Date(),
                stats: dashboardState.systemStats
            }
        }));
        
    } catch (error) {
        console.error('❌ Dashboard refresh failed:', error);
        PersistenceCore.showNotification('Failed to refresh dashboard', 'error');
    }
}

// =============================================================================
// DASHBOARD UTILITIES
// =============================================================================

/**
 * Get dashboard quick stats for overview cards
 * @returns {object}
 */
function getQuickStats() {
    const health = getSystemHealth();
    const resources = getResourceSummary();
    
    return {
        systemHealth: {
            status: health.status,
            message: health.issues.length > 0 ? health.issues.join(', ') : 'System running normally'
        },
        uptime: getFormattedUptime(),
        resources: resources,
        lastUpdate: dashboardState.lastUpdate ? PersistenceCore.formatTimestamp(dashboardState.lastUpdate) : 'Never'
    };
}

/**
 * Export system stats for external use
 * @returns {object}
 */
function exportSystemStats() {
    return {
        ...dashboardState.systemStats,
        exportTime: new Date().toISOString(),
        health: getSystemHealth(),
        resources: getResourceSummary()
    };
}

// =============================================================================
// INITIALIZATION
// =============================================================================

/**
 * Initialize dashboard module
 */
function initializeDashboard() {
    console.log('📊 Initializing dashboard module...');
    
    // Start auto-refresh if authenticated
    if (PersistenceAuth.state.isAuthenticated) {
        startDashboardRefresh();
    }
    
    // Listen for authentication changes
    window.addEventListener('auth-state-changed', (event) => {
        if (event.detail.isAuthenticated) {
            startDashboardRefresh();
        } else {
            stopDashboardRefresh();
        }
    });
}

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', initializeDashboard);

// =============================================================================
// EXPORT FOR MODULE SYSTEM
// =============================================================================

window.PersistenceDashboard = {
    state: dashboardState,
    fetchSystemStats,
    getSystemHealth,
    getFormattedUptime,
    getResourceSummary,
    startDashboardRefresh,
    stopDashboardRefresh,
    refreshDashboard,
    getQuickStats,
    exportSystemStats,
    initializeDashboard
};

console.log('✅ PersistenceOS Dashboard Module loaded');
openSUSE Build Service is sponsored by