import { compare, printTs } from '../../../json-crdt-patch/clock';
import { printTree } from 'tree-dump/lib/printTree';
import { UNDEFINED } from '../../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
 */
export class ValNode {
    doc;
    id;
    val;
    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
     */
    set(val) {
        if (compare(val, this.val) <= 0 && this.val.sid !== 0 /* SESSION.SYSTEM */)
            return;
        if (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 */ ? 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;
    }
    /**
     * @ignore
     */
    api = undefined;
    name() {
        return 'val';
    }
    // ---------------------------------------------------------------- Printable
    toString(tab = '') {
        const node = this.node();
        const header = this.name() + ' ' + printTs(this.id);
        return header + printTree(tab, [(tab) => (node ? node.toString(tab) : printTs(this.val))]);
    }
}
//# sourceMappingURL=ValNode.js.map