"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTarget = void 0;
const common_utils_1 = require("@fluidframework/common-utils");
const core_1 = require("../../core");
/**
 * This is a base class for `NodeProxyTarget` and `FieldProxyTarget`, which uniformly handles cursors and anchors.
 */
class ProxyTarget {
    constructor(context, cursor, anchor) {
        this.context = context;
        this.anchor = anchor;
        this.lazyCursor = cursor.fork();
        context.withCursors.add(this);
        if (anchor !== undefined) {
            this.context.withAnchors.add(this);
        }
    }
    free() {
        this.lazyCursor.free();
        this.context.withCursors.delete(this);
        if (this.anchor !== undefined) {
            this.forgetAnchor(this.anchor);
            this.context.withAnchors.delete(this);
            this.anchor = undefined;
        }
    }
    getAnchor() {
        if (this.anchor === undefined) {
            this.anchor = this.buildAnchor();
            this.context.withAnchors.add(this);
        }
        return this.anchor;
    }
    prepareForEdit() {
        this.getAnchor();
        this.lazyCursor.clear();
        this.context.withCursors.delete(this);
    }
    get cursor() {
        if (this.lazyCursor.state === core_1.ITreeSubscriptionCursorState.Cleared) {
            (0, common_utils_1.assert)(this.anchor !== undefined, 0x3c3 /* EditableTree should have an anchor if it does not have a cursor */);
            const result = this.tryMoveCursorToAnchor(this.anchor, this.lazyCursor);
            (0, common_utils_1.assert)(result === 1 /* Ok */, 0x3c4 /* It is invalid to access an EditableTree node which no longer exists */);
            this.context.withCursors.add(this);
        }
        return this.lazyCursor;
    }
}
exports.ProxyTarget = ProxyTarget;
//# sourceMappingURL=ProxyTarget.js.map