"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Eden = void 0;
require("reflect-metadata");
const electron_1 = require("electron");
const path = __importStar(require("path"));
const ipc_1 = require("./ipc");
const appbus_1 = require("./appbus");
const SystemHandler_1 = require("./SystemHandler");
// Managers and Handlers
const package_manager_1 = require("./package-manager");
const process_manager_1 = require("./process-manager");
const view_manager_1 = require("./view-manager");
const filesystem_1 = require("./filesystem");
const file_open_1 = require("./file-open");
const notification_1 = require("./notification");
const db_1 = require("./db");
const settings_1 = require("./settings");
const tsyringe_1 = require("tsyringe");
class Eden {
    mainWindow = null;
    viewManager;
    ipcBridge;
    appsDirectory;
    userDirectory;
    config;
    // New components
    packageManager;
    processManager;
    fileOpenManager;
    autostartManager;
    constructor(config = {}) {
        this.config = config;
        electron_1.app.commandLine.appendSwitch("enable-features", "V8CodeCache");
        // Set apps directory to user data + /eden-apps or custom path
        this.appsDirectory =
            config.appsDirectory || path.join(electron_1.app.getPath("userData"), "eden-apps");
        // Set user directory to user data + /eden-user or custom path
        this.userDirectory =
            config.userDirectory || path.join(electron_1.app.getPath("userData"), "eden-user");
        // Set dist path for runtime assets (preloads, css, apps, etc.) - consumer's dist
        const distPath = path.join(process.cwd(), "dist");
        // 1. Fundamental registries and config
        tsyringe_1.container.registerInstance("EdenConfig", this.config);
        tsyringe_1.container.registerInstance("appsDirectory", this.appsDirectory);
        tsyringe_1.container.registerInstance("distPath", distPath);
        tsyringe_1.container.registerInstance("userDirectory", this.userDirectory);
        tsyringe_1.container.resolve(ipc_1.CommandRegistry);
        // 2. Main communication bridge
        tsyringe_1.container.resolve(process_manager_1.BackendManager);
        this.ipcBridge = tsyringe_1.container.resolve(ipc_1.IPCBridge);
        // 3. UI and Application layer
        this.viewManager = tsyringe_1.container.resolve(view_manager_1.ViewManager);
        // 4. Feature managers
        tsyringe_1.container.resolve(appbus_1.AppChannelManager);
        this.packageManager = tsyringe_1.container.resolve(package_manager_1.PackageManager);
        this.processManager = tsyringe_1.container.resolve(process_manager_1.ProcessManager);
        tsyringe_1.container.resolve(SystemHandler_1.SystemHandler);
        tsyringe_1.container.resolve(filesystem_1.FilesystemManager);
        this.fileOpenManager = tsyringe_1.container.resolve(file_open_1.FileOpenManager);
        this.autostartManager = tsyringe_1.container.resolve(process_manager_1.AutostartManager);
        tsyringe_1.container.resolve(notification_1.NotificationManager);
        tsyringe_1.container.resolve(db_1.DbManager);
        tsyringe_1.container.resolve(settings_1.SettingsManager);
        this.setupAppEventHandlers();
    }
    /**
     * Setup Electron app event handlers
     */
    setupAppEventHandlers() {
        electron_1.app.on("ready", () => this.onReady());
        electron_1.app.on("window-all-closed", () => this.onWindowAllClosed());
        electron_1.app.on("activate", () => this.onActivate());
        electron_1.app.on("before-quit", () => this.onBeforeQuit());
    }
    /**
     * Handle app ready event
     */
    async onReady() {
        console.log("Eden starting...");
        // Initialize package manager
        await this.packageManager.initialize();
        // Initialize file open manager (load user preferences)
        await this.fileOpenManager.initialize();
        // Create main window
        this.createMainWindow();
        console.log("Eden ready!");
    }
    /**
     * Create the main Eden window with foundation layer
     */
    createMainWindow() {
        const windowConfig = this.config.window || {};
        const distPath = path.join(process.cwd(), "dist");
        this.mainWindow = new electron_1.BrowserWindow({
            width: windowConfig.width || 1280,
            height: windowConfig.height || 800,
            title: windowConfig.title || "Eden",
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: true,
                sandbox: false,
                preload: path.join(distPath, "foundation/foundation-preload.js"),
            },
            backgroundColor: windowConfig.backgroundColor || "#1e1e1e",
            autoHideMenuBar: true,
            show: false, // Don't show until ready
        });
        // Set managers to use this window
        this.viewManager.setMainWindow(this.mainWindow);
        this.ipcBridge.setMainWindow(this.mainWindow);
        // Load the foundation layer (not eveshell!)
        const foundationPath = path.join(distPath, "foundation/foundation.html");
        this.mainWindow.loadFile(foundationPath);
        // Launch autostart apps after foundation loads
        this.mainWindow.webContents.once("did-finish-load", () => {
            this.autostartManager.launchAll();
        });
        // Show window when foundation and overlay are ready
        this.mainWindow.once("ready-to-show", () => {
            this.mainWindow?.show();
        });
        // Handle window close
        this.mainWindow.on("closed", () => {
            this.mainWindow = null;
        });
    }
    /**
     * Handle all windows closed
     */
    onWindowAllClosed() {
        electron_1.app.quit();
    }
    /**
     * Handle app activate (macOS)
     */
    onActivate() {
        // On macOS, recreate window when dock icon is clicked
        if (this.mainWindow === null) {
            this.createMainWindow();
        }
    }
    /**
     * Handle app quit
     */
    async onBeforeQuit() {
        console.log("Eden shutting down...");
        try {
            // Shutdown all apps and wait for them to stop
            await this.processManager.shutdown();
            // Brief delay to ensure all cleanup completes
            await new Promise((resolve) => setTimeout(resolve, 100));
            // Cleanup IPC bridge
            this.ipcBridge.destroy();
            console.log("Eden shutdown complete");
        }
        catch (error) {
            console.error("Error during shutdown:", error);
        }
    }
}
exports.Eden = Eden;
//# sourceMappingURL=Eden.js.map