import { EventEmitter } from "../shared/observable.js";
import { bind } from "@cmmn/core";
export class ClientConnection extends EventEmitter {
    constructor(socket, userInfo) {
        super();
        this.socket = socket;
        this.userInfo = userInfo;
        this.decoder = new TextDecoder();
        this.listenPingPong();
        this.socket.on('message', this.onMessage);
        this.socket.on('close', () => this.emit('close'));
    }
    listenPingPong() {
        let pongReceived = true;
        const pingInterval = setInterval(() => {
            if (!pongReceived) {
                this.socket.close();
                clearInterval(pingInterval);
            }
            else {
                pongReceived = false;
                try {
                    this.socket.ping();
                }
                catch (e) {
                    this.socket.close();
                }
            }
        }, pingTimeout);
        this.socket.on('pong', () => {
            pongReceived = true;
        });
    }
    send(message) {
        // const buffer = new Buffer(JSON.stringify(message), 'utf8');
        this.socket.send(JSON.stringify(message));
    }
    onMessage(data) {
        const stringData = typeof data === "string" ? data : this.decoder.decode(data);
        const message = JSON.parse(stringData);
        if (message.type !== 'signal')
            return;
        this.emit('signal', {
            ...message,
            from: this.userInfo
        });
    }
    close() {
        super.dispose();
        this.socket.close();
    }
}
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], ClientConnection.prototype, "onMessage", null);
const pingTimeout = 30000;
//# sourceMappingURL=client-connection.js.map