/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { ITreeSubscriptionCursorState, } from "../../core";
/**
 * This is a base class for `NodeProxyTarget` and `FieldProxyTarget`, which uniformly handles cursors and anchors.
 */
export class ProxyTarget {
    constructor(context, cursor, anchor) {
        this.context = context;
        this.anchor = anchor;
        this.lazyCursor = cursor.fork();
        context.withCursors.add(this);
        this.context.withAnchors.add(this);
    }
    free() {
        this.lazyCursor.free();
        this.context.withCursors.delete(this);
        this.forgetAnchor(this.anchor);
        this.context.withAnchors.delete(this);
    }
    getAnchor() {
        return this.anchor;
    }
    prepareForEdit() {
        this.getAnchor();
        this.lazyCursor.clear();
        this.context.withCursors.delete(this);
    }
    isFreed() {
        return this.lazyCursor.state === ITreeSubscriptionCursorState.Freed;
    }
    get cursor() {
        if (this.lazyCursor.state !== ITreeSubscriptionCursorState.Current) {
            assert(this.lazyCursor.state === ITreeSubscriptionCursorState.Cleared, 0x749 /* Unset cursor should be in cleared state */);
            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);
            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;
    }
}
//# sourceMappingURL=ProxyTarget.js.map