import { bind } from "@cmmn/core";
import { EventEmitter } from "../shared/observable.js";
export class SignalingConnection extends EventEmitter {
    constructor(socket) {
        super();
        this.socket = socket;
        this.connected$ = new Promise(resolve => this.socket.onopen = resolve);
        this.encoder = new TextEncoder();
        this.decoder = new TextDecoder();
        this.socket.onmessage = this.onMessage;
        this.socket.onclose = console.log;
        this.socket.onerror = console.log;
    }
    async connect() {
        return await this.connected$;
    }
    async disconnect() {
    }
    send(data) {
        if (this.socket.readyState == WebSocket.CLOSED ||
            this.socket.readyState == WebSocket.CLOSING) {
            console.log('closing or closed state');
            return;
        }
        // const buffer = this.encoder.encode(JSON.stringify(data));
        this.socket.send(JSON.stringify(data));
    }
    onMessage(event) {
        const stringData = typeof event.data === "string" ? event.data : this.decoder.decode(event.data);
        const message = JSON.parse(stringData);
        switch (message.type) {
            case "signal":
                this.emit('signal', {
                    from: {
                        user: message.from.user,
                        accessMode: message.from.accessMode,
                        signaling: this
                    },
                    signal: message.signal,
                });
                break;
            case "announce":
                this.emit('announce', {
                    room: message.room,
                    users: message.users.map(x => ({
                        ...x,
                        signaling: this
                    }))
                });
                break;
        }
    }
    ;
    async register(info) {
        await this.connected$;
        this.send({
            type: 'register',
            info
        });
    }
    sendSignal(msg) {
        this.send(msg);
    }
}
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [MessageEvent]),
    __metadata("design:returntype", void 0)
], SignalingConnection.prototype, "onMessage", null);
//# sourceMappingURL=signaling-connection.js.map