"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShutdownListener = exports.onServerShutdownRequested = void 0;
const tslib_1 = require("tslib");
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const event_1 = require("@deepkit/event");
const framework_1 = require("@deepkit/framework");
const logger_1 = require("@deepkit/logger");
exports.onServerShutdownRequested = new event_1.EventToken('server.shutdown-requested');
class ShutdownListener {
    constructor(eventDispatcher, logger) {
        this.eventDispatcher = eventDispatcher;
        this.logger = logger;
    }
    reconfigureShutdown() {
        const sigtermListeners = process.listeners('SIGTERM');
        const sigintListeners = process.listeners('SIGINT');
        process.removeAllListeners('SIGTERM');
        process.removeAllListeners('SIGINT');
        process.on('SIGTERM', __assignType(signal => {
            this.handleShutdown()
                .then(() => {
                for (const listener of sigtermListeners) {
                    listener(signal);
                }
            })
                .catch(__assignType(err => {
                this.logger.error('Error during shutdown', err);
                process.exit(1);
            }, ['err', '', 'P"2!"/"']));
        }, ['signal', '', 'P"2!"/"']));
        process.on('SIGINT', __assignType(signal => {
            this.handleShutdown()
                .then(() => {
                for (const listener of sigintListeners) {
                    listener(signal);
                }
            })
                .catch(__assignType(err => {
                this.logger.error('Error during shutdown', err);
                process.exit(1);
            }, ['err', '', 'P"2!"/"']));
        }, ['signal', '', 'P"2!"/"']));
    }
    async handleShutdown() {
        if (!this.shutdownPromise) {
            this.shutdownPromise = this.eventDispatcher.dispatch(exports.onServerShutdownRequested);
        }
        return this.shutdownPromise;
    }
}
exports.ShutdownListener = ShutdownListener;
ShutdownListener.__type = ['shutdownPromise', () => event_1.EventDispatcher, 'eventDispatcher', () => logger_1.Logger, 'logger', 'constructor', 'reconfigureShutdown', 'handleShutdown', 'ShutdownListener', 'P$`-J3!;PP7"2#;P7$2%;"0&P$0\'P$`0(5w)'];
tslib_1.__decorate([
    event_1.eventDispatcher.listen(framework_1.onServerBootstrapDone),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", void 0)
], ShutdownListener.prototype, "reconfigureShutdown", null);
//# sourceMappingURL=shutdown.js.map