import { Injectable } from "@cmmn/core";
import { ClientConnection } from "./client-connection.js";
import { ServerRoom } from "./server-room.js";
import { TokenParser } from "./token-parser.js";
let YjsWebrtcController = class YjsWebrtcController {
    constructor(parser) {
        this.parser = parser;
        this.rooms = new Map();
        this.subscribedTopics = new Set();
    }
    async handleConnection(socket) {
        socket.on('message', async (msg) => {
            var _a;
            try {
                const registerMessage = await this.GetRegistrationMessage(msg);
                if (!registerMessage)
                    return;
                const userInfo = {
                    user: registerMessage.token.User,
                    accessMode: registerMessage.token.AccessMode
                };
                console.log(userInfo.user);
                const room = this.rooms.getOrAdd(registerMessage.room, name => new ServerRoom(name));
                const connection = new ClientConnection(socket, userInfo);
                room.addClient(connection);
                this.subscribedTopics.add(room);
            }
            catch (e) {
                return e ? ((_a = e.message) !== null && _a !== void 0 ? _a : e) : 'unknown error';
            }
        });
    }
    async GetRegistrationMessage(msg) {
        const messageStr = msg.toString('utf8');
        const message = JSON.parse(messageStr);
        console.log(message);
        if (message.type !== 'register') {
            return;
        }
        const token = await this.parser.Parse(message.info.token);
        if (!token) {
            throw new Error('unauthorized');
        }
        return {
            room: message.info.room,
            token: token
        };
    }
};
YjsWebrtcController = __decorate([
    Injectable(),
    __metadata("design:paramtypes", [TokenParser])
], YjsWebrtcController);
export { YjsWebrtcController };
//# sourceMappingURL=yjs-webrtc-controller.service.js.map