"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValNode = void 0;
const clock_1 = require("../../../json-crdt-patch/clock");
const printTree_1 = require("tree-dump/lib/printTree");
const Model_1 = require("../../model/Model");
/**
 * Represents a `val` JSON CRDT node, which is a Last-write-wins (LWW) register.
 * The `val` node holds a single value, which is a reference to another JSON
 * CRDT node.
 *
 * @category CRDT Node
 */
class ValNode {
    constructor(
    /**
     * @ignore
     */
    doc, id, 
    /**
     * The current value of the node, which is a reference to another JSON CRDT
     * node.
     */
    val) {
        this.doc = doc;
        this.id = id;
        this.val = val;
        /**
         * @ignore
         */
        this.api = undefined;
    }
    /**
     * @ignore
     */
    set(val) {
        if ((0, clock_1.compare)(val, this.val) <= 0 && this.val.sid !== 0 /* SESSION.SYSTEM */)
            return;
        if ((0, clock_1.compare)(val, this.id) <= 0)
            return;
        const oldVal = this.val;
        this.val = val;
        return oldVal;
    }
    /**
     * Returns the latest value of the node, the JSON CRDT node that `val` points
     * to.
     *
     * @returns The latest value of the node.
     */
    node() {
        return this.val.sid === 0 /* SESSION.SYSTEM */ ? Model_1.UNDEFINED : this.child();
    }
    // ----------------------------------------------------------------- JsonNode
    view() {
        return this.node()?.view();
    }
    /**
     * @ignore
     */
    children(callback) {
        callback(this.node());
    }
    /**
     * @ignore
     */
    child() {
        return this.doc.index.get(this.val);
    }
    /**
     * @ignore
     */
    container() {
        const child = this.node();
        return child ? child.container() : undefined;
    }
    name() {
        return 'val';
    }
    // ---------------------------------------------------------------- Printable
    toString(tab = '') {
        const node = this.node();
        const header = this.name() + ' ' + (0, clock_1.printTs)(this.id);
        return header + (0, printTree_1.printTree)(tab, [(tab) => (node ? node.toString(tab) : (0, clock_1.printTs)(this.val))]);
    }
}
exports.ValNode = ValNode;
//# sourceMappingURL=ValNode.js.map