"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var EventsGateway_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventsGateway = void 0;
const websockets_1 = require("@nestjs/websockets");
const ws_1 = require("ws");
const common_1 = require("@nestjs/common");
let EventsGateway = EventsGateway_1 = class EventsGateway {
    constructor() {
        this.logger = new common_1.Logger(EventsGateway_1.name);
    }
    handleConnection(client) {
        this.logger.log('Client connected to WebSocket');
    }
    handleDisconnect(client) {
        this.logger.log('Client disconnected from WebSocket');
    }
    async onApplicationShutdown(signal) {
        this.logger.log(`Shutting down WebSocket gateway on signal: ${signal || 'N/A'}`);
        if (!this.server) {
            return;
        }
        for (const client of this.server.clients) {
            if (client.readyState === ws_1.WebSocket.OPEN) {
                client.terminate();
            }
        }
        await new Promise((resolve, reject) => {
            this.server.close((err) => {
                if (err && err.message !== 'The server is not running') {
                    this.logger.error('Error closing WebSocket server:', err);
                    return reject(err);
                }
                this.logger.log('WebSocket server closed or was not running.');
                resolve();
            });
        });
    }
    sendToAll(event, data) {
        const message = JSON.stringify({ event, data });
        this.logger.log(`Broadcasting WebSocket event '${event}'`);
        this.server.clients.forEach((client) => {
            if (client.readyState === ws_1.WebSocket.OPEN) {
                client.send(message);
            }
        });
    }
};
exports.EventsGateway = EventsGateway;
__decorate([
    (0, websockets_1.WebSocketServer)(),
    __metadata("design:type", ws_1.Server)
], EventsGateway.prototype, "server", void 0);
exports.EventsGateway = EventsGateway = EventsGateway_1 = __decorate([
    (0, websockets_1.WebSocketGateway)({
        cors: {
            origin: '*',
        },
    })
], EventsGateway);
//# sourceMappingURL=events.gateway.js.map