"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerManager = void 0;
const events_1 = require("events");
const server_1 = require("../server/server");
class ServerManager extends events_1.EventEmitter {
    server;
    configManager;
    status = { isRunning: false };
    constructor(configManager) {
        super();
        this.configManager = configManager;
    }
    async start() {
        if (this.status.isRunning) {
            throw new Error('Server is already running');
        }
        try {
            const config = this.configManager.getConfig();
            const app = await (0, server_1.createServer)();
            this.server = app.listen({
                port: config.server.port,
                hostname: config.server.host
            });
            this.status = {
                isRunning: true,
                port: config.server.port,
                host: config.server.host,
                startTime: new Date()
            };
            this.emit('started', this.status);
        }
        catch (error) {
            this.status = {
                isRunning: false,
                error: error instanceof Error ? error.message : 'Unknown error'
            };
            this.emit('error', error);
            throw error;
        }
    }
    async stop() {
        if (!this.server || !this.status.isRunning) {
            return;
        }
        return new Promise((resolve, reject) => {
            this.server.close((error) => {
                if (error) {
                    this.status.error = error.message;
                    this.emit('error', error);
                    reject(error);
                }
                else {
                    this.status = { isRunning: false };
                    this.server = undefined;
                    this.emit('stopped');
                    resolve();
                }
            });
        });
    }
    async restart() {
        if (this.status.isRunning) {
            await this.stop();
        }
        await this.start();
    }
    getStatus() {
        return { ...this.status };
    }
    isRunning() {
        return this.status.isRunning;
    }
    getUrl() {
        if (!this.status.isRunning || !this.status.host || !this.status.port) {
            return undefined;
        }
        return `http://${this.status.host}:${this.status.port}`;
    }
    getPort() {
        return this.status.port;
    }
    getLogs() {
        // TODO: Implement log collection
        return [];
    }
    clearLogs() {
        // TODO: Implement log clearing
    }
}
exports.ServerManager = ServerManager;
//# sourceMappingURL=serverManager.js.map