File app-main.js of Package PersistenceOS

/**
 * PersistenceOS Main Application Assembly
 * Brings together all modules into a cohesive Vue.js application
 * 
 * Depends on: core-utils.js, auth-module.js, dashboard-module.js, 
 *             vm-module.js, storage-module.js, network-module.js, snapshots-module.js
 */

// =============================================================================
// APPLICATION STATE ASSEMBLY
// =============================================================================

/**
 * Assemble application state from all modules
 * @returns {object}
 */
function assembleApplicationState() {
    const { createApp, ref, computed, onMounted, watch } = Vue;
    
    return createApp({
        setup() {
            // Core application state
            const activeSection = ref(PersistenceCore.getStorageItem(PersistenceCore.config.UI_CONSTANTS.ACTIVE_SECTION_KEY, 'dashboard'));
            const sidebarCollapsed = ref(PersistenceCore.getStorageItem(PersistenceCore.config.UI_CONSTANTS.SIDEBAR_COLLAPSED_KEY, false));
            const appReady = ref(false);
            
            // Module state references (reactive)
            const systemStats = ref(PersistenceDashboard.state.systemStats);
            const virtualMachines = ref(PersistenceVM.state.virtualMachines);
            const storagePools = ref(PersistenceStorage.state.storagePools);
            const networkInterfaces = ref(PersistenceNetwork.state.networkInterfaces);
            const systemSnapshots = ref(PersistenceSnapshots.state.systemSnapshots);
            
            // Computed properties
            const vmStats = computed(() => PersistenceVM.getVMStats());
            const storageStats = computed(() => PersistenceStorage.getStorageStats());
            const networkStats = computed(() => PersistenceNetwork.state.networkStats);
            const snapshotStats = computed(() => PersistenceSnapshots.getSnapshotStats());
            
            const filteredInterfaces = computed(() => PersistenceNetwork.getFilteredInterfaces());
            
            // Loading states from modules
            const vmLoading = ref(PersistenceVM.state.vmLoading);
            const vmActionLoading = ref(PersistenceVM.state.vmActionLoading);
            const networkLoading = ref(PersistenceNetwork.state.networkLoading);
            const isLoading = ref(PersistenceStorage.state.isLoading);
            
            // Network specific state
            const networkRoutes = ref(PersistenceNetwork.state.networkRoutes);
            const firewallStatus = ref(PersistenceNetwork.state.firewallStatus);
            const dnsConfig = ref(PersistenceNetwork.state.dnsConfig);
            const interfaceSearchTerm = ref(PersistenceNetwork.state.interfaceSearchTerm);
            
            // Additional network properties for comprehensive integration
            const networkConnections = ref(PersistenceNetwork.state.networkConnections);
            const networkSettings = ref(PersistenceNetwork.state.networkSettings);
            const selectedInterface = ref(PersistenceNetwork.state.selectedInterface);
            const connectionForm = ref(PersistenceNetwork.state.connectionForm);
            
            // System info
            const systemInfo = ref(PersistenceDashboard.state.systemInfo);
            
            // =============================================================================
            // CORE APPLICATION METHODS
            // =============================================================================
            
            const setActiveSection = (section) => {
                activeSection.value = section;
                window.location.hash = '#' + section;
                PersistenceCore.setStorageItem(PersistenceCore.config.UI_CONSTANTS.ACTIVE_SECTION_KEY, section);
            };
            
            const toggleSidebar = () => {
                sidebarCollapsed.value = !sidebarCollapsed.value;
                PersistenceCore.setStorageItem(PersistenceCore.config.UI_CONSTANTS.SIDEBAR_COLLAPSED_KEY, sidebarCollapsed.value);
            };
            
            const logout = () => {
                PersistenceAuth.logout();
            };
            
            // =============================================================================
            // MODULE METHOD INTEGRATION
            // =============================================================================
            
            // Dashboard methods
            const fetchSystemStats = PersistenceAuth.requireAuth(PersistenceDashboard.fetchSystemStats);
            const refreshDashboard = PersistenceAuth.requireAuth(PersistenceDashboard.refreshDashboard);
            
            // VM methods
            const refreshVMs = PersistenceAuth.requireAuth(PersistenceVM.refreshVMs);
            const performVMAction = PersistenceAuth.requireAuth(PersistenceVM.performVMAction);
            const createVM = PersistenceAuth.requireAuth(PersistenceVM.createVM, 'write');
            const deleteVM = PersistenceAuth.requireAuth(PersistenceVM.deleteVM, 'write');
            const openVMConsole = PersistenceAuth.requireAuth(PersistenceVM.openVMConsole);
            const showVMSettings = PersistenceAuth.requireAuth(PersistenceVM.showVMSettings);
            
            // Storage methods
            const refreshStorage = PersistenceAuth.requireAuth(PersistenceStorage.refreshStorage);
            const createPool = PersistenceAuth.requireAuth(PersistenceStorage.createPool, 'write');
            const importPool = PersistenceAuth.requireAuth(PersistenceStorage.importPool, 'write');
            const managePool = PersistenceAuth.requireAuth(PersistenceStorage.managePool);
            const snapshotPool = PersistenceAuth.requireAuth(PersistenceStorage.snapshotPool, 'write');
            
            // Network methods
            const refreshNetworkData = PersistenceAuth.requireAuth(PersistenceNetwork.refreshNetworkData);
            const configureInterface = PersistenceAuth.requireAuth(PersistenceNetwork.configureInterface, 'write');
            const showInterfaceDetails = PersistenceAuth.requireAuth(PersistenceNetwork.showInterfaceDetails);
            const toggleInterface = PersistenceAuth.requireAuth(PersistenceNetwork.toggleInterface, 'write');
            
            // Snapshot methods
            const refreshSnapshots = PersistenceAuth.requireAuth(PersistenceSnapshots.refreshSnapshots);
            const createSnapshot = PersistenceAuth.requireAuth(PersistenceSnapshots.createSnapshot, 'write');
            const scheduleSnapshot = PersistenceAuth.requireAuth(PersistenceSnapshots.scheduleSnapshot, 'write');
            const restoreSnapshot = PersistenceAuth.requireAuth(PersistenceSnapshots.restoreSnapshot, 'write');
            const deleteSnapshot = PersistenceAuth.requireAuth(PersistenceSnapshots.deleteSnapshot, 'write');
            const downloadSnapshot = PersistenceAuth.requireAuth(PersistenceSnapshots.downloadSnapshot);
            const showSnapshotCreationModal = PersistenceAuth.requireAuth(PersistenceSnapshots.showSnapshotCreationModal, 'write');
            const showSnapshotScheduleModal = PersistenceAuth.requireAuth(PersistenceSnapshots.showSnapshotScheduleModal, 'write');
            
            // Utility methods
            const getUsageColor = PersistenceCore.getUsageColor;
            const formatBytes = PersistenceCore.formatBytes;
            const showNotification = PersistenceCore.showNotification;
            
            // Placeholder methods for compatibility
            const refreshRoutes = () => refreshNetworkData();
            const refreshDNS = () => refreshNetworkData();
            const showAddInterfaceModal = () => PersistenceCore.showNotification('🚧 Add Interface - Feature in development', 'info');
            const showFirewallConfig = () => PersistenceCore.showNotification('🚧 Firewall Config - Feature in development', 'info');
            const loadNetworkInterfaces = () => refreshNetworkData();
            const loadNetworkConnections = () => refreshNetworkData();
            const loadNetworkSettings = () => refreshNetworkData();
            const saveNetworkSettings = () => PersistenceCore.showNotification('🚧 Save Network Settings - Feature in development', 'info');
            const createNetworkConnection = () => PersistenceCore.showNotification('🚧 Create Network Connection - Feature in development', 'info');
            const deleteNetworkConnection = () => PersistenceCore.showNotification('🚧 Delete Network Connection - Feature in development', 'info');
            const testNetworkConnectivity = () => PersistenceCore.showNotification('🚧 Test Network Connectivity - Feature in development', 'info');
            const getSnapshotStats = PersistenceSnapshots.getSnapshotStats;
            const populateStoragePools = () => refreshStorage();
            
            // =============================================================================
            // LIFECYCLE HOOKS
            // =============================================================================
            
            onMounted(async () => {
                console.log('🚀 PersistenceOS Vue.js application mounted');
                
                // Initialize authentication
                const isAuthenticated = PersistenceAuth.initializeAuth();
                
                if (isAuthenticated) {
                    // Load initial data
                    await Promise.all([
                        fetchSystemStats(),
                        refreshVMs(),
                        refreshStorage(),
                        refreshNetworkData(),
                        refreshSnapshots()
                    ]);
                }
                
                appReady.value = true;
                console.log('✅ Vue.js dashboard mounted successfully');
            });
            
            // Watch for authentication state changes
            watch(() => PersistenceAuth.state.isAuthenticated, (isAuthenticated) => {
                if (isAuthenticated) {
                    // Start all monitoring when authenticated
                    PersistenceDashboard.startDashboardRefresh();
                    PersistenceVM.startVMMonitoring();
                    PersistenceStorage.startStorageMonitoring();
                    PersistenceNetwork.startNetworkMonitoring();
                    PersistenceSnapshots.startSnapshotMonitoring();
                } else {
                    // Stop all monitoring when not authenticated
                    PersistenceDashboard.stopDashboardRefresh();
                    PersistenceVM.stopVMMonitoring();
                    PersistenceStorage.stopStorageMonitoring();
                    PersistenceNetwork.stopNetworkMonitoring();
                    PersistenceSnapshots.stopSnapshotMonitoring();
                }
            });
            
            // =============================================================================
            // RETURN STATEMENT - ALL REACTIVE DATA AND METHODS
            // =============================================================================
            
            return {
                // Core state
                activeSection, sidebarCollapsed, appReady,
                
                // Module state
                systemStats, virtualMachines, storagePools, networkInterfaces, systemSnapshots, systemInfo,
                
                // Computed properties
                vmStats, storageStats, networkStats, snapshotStats, filteredInterfaces,
                
                // Loading states
                vmLoading, vmActionLoading, networkLoading, isLoading,
                
                // Network state
                networkRoutes, firewallStatus, dnsConfig, interfaceSearchTerm,
                networkConnections, networkSettings, selectedInterface, connectionForm,
                
                // Core methods
                setActiveSection, toggleSidebar, logout,
                
                // Dashboard methods
                fetchSystemStats, refreshDashboard,
                
                // VM methods
                refreshVMs, performVMAction, createVM, deleteVM, openVMConsole, showVMSettings,
                
                // Storage methods
                refreshStorage, createPool, importPool, managePool, snapshotPool,
                
                // Network methods
                refreshNetworkData, refreshRoutes, refreshDNS, configureInterface, showInterfaceDetails,
                toggleInterface, showAddInterfaceModal, showFirewallConfig,
                loadNetworkInterfaces, loadNetworkConnections, loadNetworkSettings,
                saveNetworkSettings, createNetworkConnection, deleteNetworkConnection, testNetworkConnectivity,
                
                // Snapshot methods
                refreshSnapshots, createSnapshot, scheduleSnapshot, restoreSnapshot, deleteSnapshot,
                downloadSnapshot, getSnapshotStats, showSnapshotCreationModal, showSnapshotScheduleModal,
                populateStoragePools,
                
                // Utility methods
                getUsageColor, formatBytes, showNotification
            };
        }
    });
}

// =============================================================================
// APPLICATION INITIALIZATION
// =============================================================================

/**
 * Initialize the complete PersistenceOS application
 */
function initializePersistenceOSApp() {
    console.log('🚀 Initializing PersistenceOS modular application...');
    
    // Wait for all modules to be loaded
    const requiredModules = [
        'PersistenceCore',
        'PersistenceAuth', 
        'PersistenceDashboard',
        'PersistenceVM',
        'PersistenceStorage',
        'PersistenceNetwork',
        'PersistenceSnapshots'
    ];
    
    const checkModules = () => {
        const missingModules = requiredModules.filter(module => !window[module]);
        
        if (missingModules.length > 0) {
            console.log(`⏳ Waiting for modules: ${missingModules.join(', ')}`);
            setTimeout(checkModules, 100);
            return;
        }
        
        console.log('✅ All modules loaded successfully');
        
        // Create and mount the Vue application
        const app = assembleApplicationState();
        window.app = app.mount('#app');
        
        // Expose app to window for testing
        setTimeout(() => {
            console.log('🔧 Applying automatic window.app exposure fix...');
            
            // Ensure all methods are accessible from window.app
            const appInstance = window.app;
            if (appInstance) {
                // Add any missing methods to window.app
                Object.keys(appInstance).forEach(key => {
                    if (typeof appInstance[key] === 'function') {
                        window.app[key] = appInstance[key];
                    }
                });
                
                console.log('✅ Window.app exposure complete - all methods accessible');
                console.log('🎯 Available methods:', Object.keys(window.app).filter(k => typeof window.app[k] === 'function'));
            }
        }, 1000);
        
        console.log('🎉 PersistenceOS modular application initialized successfully!');
    };
    
    checkModules();
}

// =============================================================================
// AUTO-INITIALIZATION
// =============================================================================

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', initializePersistenceOSApp);

console.log('✅ PersistenceOS Main Application Assembly loaded');
openSUSE Build Service is sponsored by