"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cnt = void 0;
const constants_1 = require("../constants");
const nodes_1 = require("../../json-crdt/model/api/nodes");
const ExtNode_1 = require("../../json-crdt/extensions/ExtNode");
const Extension_1 = require("../../json-crdt/extensions/Extension");
const json_crdt_1 = require("../../json-crdt");
const MNEMONIC = constants_1.ExtensionName[constants_1.ExtensionId.cnt];
class CntNode extends ExtNode_1.ExtNode {
    constructor() {
        super(...arguments);
        this.extId = constants_1.ExtensionId.cnt;
    }
    name() {
        return MNEMONIC;
    }
    view() {
        const obj = this.data.view();
        let sum = 0;
        for (const key in obj)
            sum += Number(obj[key]);
        return sum;
    }
}
class CntApi extends nodes_1.NodeApi {
    inc(increment) {
        const { api, node } = this;
        const sid = api.model.clock.sid;
        const sidStr = sid.toString(36);
        const value = Number(node.data.get(sidStr)?.view() ?? 0);
        const newValue = value + increment;
        const obj = api.wrap(node.data);
        obj.set({
            [sidStr]: newValue,
        });
        return this;
    }
}
const create = (value, sid = 0) => new json_crdt_1.NodeBuilder((builder) => {
    if (!sid)
        sid = builder.clock.sid;
    const schema = value === undefined
        ? json_crdt_1.s.map({})
        : json_crdt_1.s.map({ [sid.toString(36)]: json_crdt_1.s.con(value ?? 0) });
    return schema.build(builder);
});
exports.cnt = new Extension_1.Extension(constants_1.ExtensionId.cnt, MNEMONIC, CntNode, CntApi, create);
//# sourceMappingURL=index.js.map