import * as Y from "yjs";
import { applyUpdate } from "yjs";
import * as awarenessProtocol from 'y-protocols/awareness';
import { bind } from "@cmmn/core";
import { MessageType } from "../shared/types.js";
export class DocAdapter {
    constructor(doc, awareness) {
        this.doc = doc;
        this.awareness = awareness;
        this.connections = new Set();
        this.doc.on('update', update => {
            this.broadcast(MessageType.Update, update);
        });
    }
    connect(connection) {
        this.connections.add(connection);
        connection.on(MessageType.UpdateRequest, stateVector => {
            connection.send(MessageType.Update, Y.encodeStateAsUpdate(this.doc, stateVector));
        });
        connection.on(MessageType.AwarenessRequest, () => {
            connection.send(MessageType.Awareness, this.getAwarenessMessage());
        });
        connection.on(MessageType.Awareness, this.applyAwarenessUpdate);
        connection.on(MessageType.Update, this.applyUpdate);
        connection.once('close', () => {
            this.connections.delete(connection);
        });
        connection.send(MessageType.UpdateRequest, this.getStateVector());
        connection.send(MessageType.Awareness, this.getAwarenessMessage());
    }
    broadcast(type, data) {
        for (let connection of this.connections) {
            connection.send(type, data);
        }
    }
    getAwarenessMessage(changedClients = [this.doc.clientID]) {
        return awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients);
    }
    applyUpdate(update) {
        // TODO: specify origin
        applyUpdate(this.doc, update, 'origin');
    }
    applyAwarenessUpdate(update) {
        // TODO: specify origin
        awarenessProtocol.applyAwarenessUpdate(this.awareness, update, 'origin');
    }
    getStateVector() {
        return Y.encodeStateVector(this.doc);
    }
}
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Uint8Array]),
    __metadata("design:returntype", void 0)
], DocAdapter.prototype, "applyUpdate", null);
__decorate([
    bind,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Uint8Array]),
    __metadata("design:returntype", void 0)
], DocAdapter.prototype, "applyAwarenessUpdate", null);
//# sourceMappingURL=doc-adapter.js.map