import { PeerDataChannel } from "./peer-data-channel.js";
export class PeerConnection extends PeerDataChannel {
    constructor(dataChannel, user) {
        super(user.accessMode);
        this.dataChannel = dataChannel;
        this.user = user;
        this.open$ = this.dataChannel.readyState == "open"
            ? Promise.resolve()
            : new Promise(resolve => this.dataChannel.onopen = resolve);
        console.log('connected', user.user, user.accessMode, dataChannel.label);
        let type = null;
        this.dataChannel.addEventListener('close', () => this.emit('close'));
        this.dataChannel.addEventListener('message', event => {
            const data = new Uint8Array(event.data);
            if (type == null)
                type = data[0];
            else {
                this.emit(type, new Uint8Array(data));
                type = null;
            }
        });
    }
    async send(type, data) {
        await this.open$;
        this.dataChannel.send(Uint8Array.of(type));
        this.dataChannel.send(data);
    }
    disconnect() {
        this.dataChannel.close();
        super.disconnect();
    }
}
//# sourceMappingURL=peer-connection.js.map