import { SignalingConnection } from "./signaling-connection.js";
import { bind } from '@cmmn/core';
import { Room } from "./room.js";
import { DataChannelProvider } from "./data-channel-provider.js";
export class YjsWebRTCProvider {
    constructor(signallingServers, rtcOptions = undefined) {
        this.rtcOptions = rtcOptions;
        this.rooms = new Map();
        this.peerInitiator = new DataChannelProvider({
            ...this.rtcOptions
        });
        this.signalingConnections = signallingServers.map(this.createSignallingConnection);
    }
    joinRoom(roomName, options) {
        const room = new Room(roomName, options, this.peerInitiator);
        this.rooms.set(roomName, room);
        const regInfo = room.getRegistrationInfo();
        this.signalingConnections.forEach(x => x.register(regInfo));
        return room;
    }
    leaveRoom(roomName) {
        this.rooms.get(roomName).disconnect();
    }
    async onSignal(msg) {
        if (msg.signal.type === "offer") {
            this.peerInitiator.withOffer(msg.from, msg.signal, (pc, room) => {
                this.rooms.get(room).addConnection(pc);
            });
        }
    }
    onAnnounce(msg) {
        this.rooms.get(msg.room).addUsers(msg.users);
    }
    /** @internal **/
    sendSignal(msg) {
        this.signalingConnections.forEach(s => s.sendSignal(msg));
    }
    createSignallingConnection(url) {
        const connection = new SignalingConnection(new WebSocket(url));
        connection.on('signal', this.onSignal);
        connection.on('announce', this.onAnnounce);
        return connection;
    }
    async dispose() {
        this.peerInitiator.dispose();
        for (let value of this.rooms.values()) {
            await value.disconnect();
        }
    }
}
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], YjsWebRTCProvider.prototype, "onSignal", null);
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], YjsWebRTCProvider.prototype, "onAnnounce", null);
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", SignalingConnection)
], YjsWebRTCProvider.prototype, "createSignallingConnection", null);
//# sourceMappingURL=yjs-webrtc.provider.js.map