import { ObservableObject } from "@cmmn/cell";
/** @internal **/
export class SyncObject extends ObservableObject {
    constructor(doc, map) {
        super(Object.fromEntries(map.entries()));
        this.doc = doc;
        this.map = map;
        this.subscriptions = [];
    }
    subscribe(eventName) {
        super.subscribe(eventName);
        this.Set(Object.fromEntries(this.map.entries()));
        this.subscriptions.push(this.map.on('Set', (event) => {
            this.Diff({
                [event.key]: event.value
            });
        }), this.map.on('Delete', (event) => {
            this.Diff({
                [event.key]: null
            });
        }), this.on('change', async (e) => {
            this.doc.transact(() => {
                for (let key of e.keys) {
                    if (this.map.get(key) !== e.value[key])
                        this.map.set(key, e.value[key]);
                }
            });
        }));
    }
    unsubscribe(eventName) {
        super.unsubscribe(eventName);
        this.subscriptions.forEach(x => x());
        this.subscriptions.length = 0;
    }
}
