/**
 * @fileoverview Main room management module that coordinates all room functionality.
 * This file handles:
 * - Room initialization and configuration
 * - Manager coordination (File, View, Upload, Search, Modal)
 * - Navigation and path management
 * - Event handling and user interactions
 * - Permission management
 */

console.log('[RoomManager] Script loaded');

// Main room.js file - Coordinates all room functionality
import { FileManager } from './fileManager.js';
import { ViewManager } from './viewManager.js';
import { UploadManager } from './uploadManager.js';
import { SearchManager } from './searchManager.js';
import { ModalManager } from './modalManager.js';

console.log('[RoomManager] All modules imported successfully');

/**
 * @class RoomManager
 * @classdesc Main class that coordinates all room functionality and manages the various
 * sub-managers (File, View, Upload, Search, Modal).
 */
class RoomManager {
    /**
     * Creates a new RoomManager instance.
     * @param {Object} config - Configuration object for the room
     * @param {string} config.roomId - The ID of the room
     * @param {boolean} config.canDelete - Whether the user can delete files
     * @param {boolean} config.canShare - Whether the user can share files
     * @param {boolean} config.canUpload - Whether the user can upload files
     * @param {boolean} config.canDownload - Whether the user can download files
     * @param {boolean} config.canRename - Whether the user can rename files
     * @param {boolean} config.canMove - Whether the user can move files
     */
    constructor(config) {
        console.log('[RoomManager] Initializing with config:', config);
        this.roomId = config.roomId;
        this.canDelete = config.canDelete;
        this.canShare = config.canShare;
        this.canUpload = config.canUpload;
        this.canDownload = config.canDownload;
        this.canRename = config.canRename;
        this.canMove = config.canMove;
        
        console.log('[RoomManager] Creating manager instances...');
        // Initialize managers
        this.fileManager = new FileManager(this);
        this.viewManager = new ViewManager(this);
        this.uploadManager = new UploadManager(this);
        this.searchManager = new SearchManager(this);
        this.modalManager = new ModalManager(this);
        
        console.log('[RoomManager] All managers initialized');
        // Initialize the room
        this.initialize();
    }
    
    /**
     * Initializes the room functionality.
     * Sets up the view, fetches files, initializes search, and sets up event listeners.
     * @async
     */
    async initialize() {
        console.log('[RoomManager] Starting initialization...');
        // Get current path from URL
        this.currentPath = this.getPathFromUrl();
        console.log('[RoomManager] Current path:', this.currentPath);
        
        try {
            console.log('[RoomManager] Initializing view...');
            // Initialize view and fetch files
            await this.viewManager.initializeView();
            console.log('[RoomManager] View initialized');
            
            console.log('[RoomManager] Fetching files...');
            await this.fileManager.fetchFiles();
            console.log('[RoomManager] Files fetched');
            
            // Render breadcrumb after files are fetched
            this.viewManager.renderBreadcrumb();
            
            console.log('[RoomManager] Initializing search...');
            // Initialize search
            this.searchManager.initialize();
            console.log('[RoomManager] Search initialized');
            
            console.log('[RoomManager] Setting up event listeners...');
            // Initialize event listeners
            this.initializeEventListeners();
            console.log('[RoomManager] Event listeners initialized');
            
            console.log('[RoomManager] Initialization complete');
        } catch (error) {
            console.error('[RoomManager] Error during initialization:', error);
        }
    }
    
    /**
     * Navigates to a subfolder within the current path.
     * @param {string} folderName - The name of the folder to navigate to
     */
    navigateToFolder(folderName) {
        console.log('[RoomManager] Navigating to folder:', folderName);
        const newPath = this.currentPath ? `${this.currentPath}/${folderName}` : folderName;
        this.navigateTo(newPath);
    }

    /**
     * Navigates to the parent folder of the current path.
     */
    navigateToParent() {
        console.log('[RoomManager] Navigating to parent folder');
        if (!this.currentPath) return;
        
        const parts = this.currentPath.split('/');
        parts.pop(); // Remove the last part
        const newPath = parts.join('/');
        this.navigateTo(newPath);
    }

    /**
     * Navigates to a specific path and updates the URL.
     * @param {string} path - The path to navigate to
     */
    navigateTo(path) {
        console.log('[RoomManager] Navigating to path:', path);
        this.currentPath = path;
        // Update the URL with the current path
        const url = new URL(window.location);
        if (this.currentPath) {
            url.searchParams.set('path', this.currentPath);
        } else {
            url.searchParams.delete('path');
        }
        window.history.replaceState({}, '', url);
        this.fileManager.fetchFiles().then(() => {
            // Render breadcrumb after files are fetched
            this.viewManager.renderBreadcrumb();
        });
    }

    /**
     * Gets the current path from the URL parameters.
     * @returns {string} The current path from the URL
     */
    getPathFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('path') || '';
    }
    
    /**
     * Initializes event listeners for user interactions.
     * Sets up handlers for select all, download selected, delete selected,
     * and click outside to clear selection.
     */
    initializeEventListeners() {
        console.log('[RoomManager] Setting up event listeners');
        
        // Add event listener for select all checkbox
        const selectAllCheckbox = document.querySelector('.select-all-checkbox');
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', (event) => {
                const checkboxes = document.querySelectorAll('.select-item-checkbox');
                checkboxes.forEach((cb, index) => {
                    cb.checked = event.target.checked;
                    if (event.target.checked) {
                        this.fileManager.selectedItems.add(index);
                    } else {
                        this.fileManager.selectedItems.delete(index);
                    }
                });
                this.viewManager.updateMultiSelectUI();
            });
        }

        // Add event listener for download selected button
        const downloadSelectedBtn = document.getElementById('downloadSelectedBtn');
        if (downloadSelectedBtn && this.canDownload) {
            downloadSelectedBtn.addEventListener('click', () => {
                this.fileManager.downloadSelected();
            });
        }

        // Add event listener for delete selected button
        const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
        if (deleteSelectedBtn && this.canDelete) {
            deleteSelectedBtn.addEventListener('click', () => {
                this.modalManager.showBatchDeleteModal();
            });
        }

        // Add event listener for clicking outside to clear selection
        document.addEventListener('click', (event) => {
            if (!event.target.closest('.file-card') && !event.target.closest('.file-row') && !event.target.closest('.file-action-btn')) {
                this.fileManager.clearSelection();
            }
        });
    }
}

/**
 * Initializes the room manager when the DOM is loaded.
 * Creates a new RoomManager instance with configuration from meta tags.
 */
document.addEventListener('DOMContentLoaded', () => {
    const config = {
        roomId: document.querySelector('meta[name="room-id"]').getAttribute('content'),
        canDelete: document.querySelector('meta[name="can-delete"]').getAttribute('content') === 'true',
        canShare: document.querySelector('meta[name="can-share"]').getAttribute('content') === 'true',
        canUpload: document.querySelector('meta[name="can-upload"]').getAttribute('content') === 'true',
        canDownload: document.querySelector('meta[name="can-download"]').getAttribute('content') === 'true',
        canRename: document.querySelector('meta[name="can-rename"]').getAttribute('content') === 'true',
        canMove: document.querySelector('meta[name="can-move"]').getAttribute('content') === 'true'
    };
    
    // Create and expose the room manager instance
    window.roomManager = new RoomManager(config);
}); 