"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTreeContext = exports.Context = exports.ContextSlot = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../../core/index.js");
const index_js_2 = require("../../util/index.js");
const lazyEntity_js_1 = require("./lazyEntity.js");
const lazyField_js_1 = require("./lazyField.js");
/**
 * Creating multiple flex tree contexts for the same branch, and thus with the same underlying AnchorSet does not work due to how TreeNode caching works.
 * This slot is used to detect if one already exists and error if creating a second.
 *
 * TODO:
 * 1. API docs need to reflect this limitation or the limitation has to be removed.
 */
exports.ContextSlot = (0, index_js_1.anchorSlot)();
/**
 * Implementation of `FlexTreeContext`.
 *
 * @remarks An editor is required to edit the FlexTree.
 */
class Context {
    /**
     * @param schema - Schema to use when working with the  tree.
     * @param checkout - The checkout.
     * @param nodeKeyManager - An object which handles node key generation and conversion
     */
    constructor(schema, checkout, nodeKeyManager) {
        this.schema = schema;
        this.checkout = checkout;
        this.nodeKeyManager = nodeKeyManager;
        this.withCursors = new Set();
        this.withAnchors = new Set();
        this.disposed = false;
        this.eventUnregister = [
            this.checkout.forest.on("beforeChange", () => {
                this.prepareForEdit();
            }),
        ];
        (0, internal_1.assert)(!this.checkout.forest.anchors.slots.has(exports.ContextSlot), 0x92b /* Cannot create second flex-tree from checkout */);
        this.checkout.forest.anchors.slots.set(exports.ContextSlot, this);
    }
    /**
     * Called before editing.
     * Clears all cursors so editing can proceed.
     */
    prepareForEdit() {
        (0, internal_1.assert)(this.disposed === false, 0x802 /* use after dispose */);
        for (const target of this.withCursors) {
            target[lazyEntity_js_1.prepareForEditSymbol]();
        }
        (0, internal_1.assert)(this.withCursors.size === 0, 0x773 /* prepareForEdit should remove all cursors */);
    }
    [index_js_2.disposeSymbol]() {
        (0, internal_1.assert)(this.disposed === false, 0x803 /* double dispose */);
        this.disposed = true;
        this.clear();
        for (const unregister of this.eventUnregister) {
            unregister();
        }
        this.eventUnregister.length = 0;
        const deleted = this.checkout.forest.anchors.slots.delete(exports.ContextSlot);
        (0, internal_1.assert)(deleted, 0x8c4 /* unexpected dispose */);
    }
    /**
     * Release any cursors and anchors held by tree entities created in this context.
     * Ensures the cashed references to those entities on the Anchors are also cleared.
     * The tree entities are invalid to use after this, but the context may still be used
     * to create new trees starting from the root.
     */
    clear() {
        for (const target of this.withAnchors) {
            target[index_js_2.disposeSymbol]();
        }
        (0, internal_1.assert)(this.withCursors.size === 0, 0x774 /* free should remove all cursors */);
        (0, internal_1.assert)(this.withAnchors.size === 0, 0x775 /* free should remove all anchors */);
    }
    get root() {
        (0, internal_1.assert)(this.disposed === false, 0x804 /* use after dispose */);
        const cursor = this.checkout.forest.allocateCursor("root");
        (0, index_js_1.moveToDetachedField)(this.checkout.forest, cursor);
        const field = (0, lazyField_js_1.makeField)(this, this.schema.rootFieldSchema, cursor);
        cursor.free();
        return field;
    }
    on(eventName, listener) {
        return this.checkout.forest.on(eventName, listener);
    }
}
exports.Context = Context;
/**
 * A simple API for a Forest to interact with the tree.
 *
 * @param forest - the Forest
 * @param editor - an editor that makes changes to the forest.
 * @param nodeKeyManager - an object which handles node key generation and conversion.
 * @returns {@link FlexTreeContext} which is used to manage the cursors and anchors within the FlexTrees:
 * This is necessary for supporting using this tree across edits to the forest, and not leaking memory.
 */
function getTreeContext(schema, checkout, nodeKeyManager) {
    return new Context(schema, checkout, nodeKeyManager);
}
exports.getTreeContext = getTreeContext;
//# sourceMappingURL=context.js.map