/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert, debugAssert } from "@fluidframework/core-utils/internal";
import { anchorSlot, moveToDetachedField, rootField, } from "../../core/index.js";
import { disposeSymbol } from "../../util/index.js";
import { makeField } from "./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.
 */
export const ContextSlot = anchorSlot();
/**
 * Implementation of `FlexTreeContext`.
 *
 * @remarks An editor is required to edit the FlexTree.
 *
 * A {@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.
 *
 * This context and the trees it produces observe the kinds of fields from the schema
 */
export class Context {
    constructor(schemaPolicy, checkout, 
    /**
     * An object which handles node key generation and conversion
     */
    nodeKeyManager) {
        this.schemaPolicy = schemaPolicy;
        this.checkout = checkout;
        this.nodeKeyManager = nodeKeyManager;
        this.withCursors = new Set();
        this.withAnchors = new Set();
        this.disposed = false;
        this.eventUnregister = [
            this.checkout.forest.events.on("beforeChange", () => {
                this.prepareForEdit();
            }),
        ];
        assert(!this.checkout.forest.anchors.slots.has(ContextSlot), 0x92b /* Cannot create second flex-tree from checkout */);
        this.checkout.forest.anchors.slots.set(ContextSlot, this);
    }
    isHydrated() {
        debugAssert(() => !this.disposed || "Disposed");
        return true;
    }
    isDisposed() {
        return this.disposed;
    }
    get schema() {
        return this.checkout.storedSchema;
    }
    /**
     * Called before editing.
     * Clears all cursors so editing can proceed.
     */
    prepareForEdit() {
        assert(this.disposed === false, 0x802 /* use after dispose */);
        for (const target of this.withCursors) {
            target.prepareForEdit();
        }
        assert(this.withCursors.size === 0, 0x773 /* prepareForEdit should remove all cursors */);
    }
    [disposeSymbol]() {
        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(ContextSlot);
        assert(deleted, 0x8c4 /* unexpected dispose */);
    }
    /**
     * Release any cursors and anchors held by tree entities created in this context.
     * @remarks
     * 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[disposeSymbol]();
        }
        this.lazyRootCache = undefined;
        assert(this.withCursors.size === 0, 0x774 /* free should remove all cursors */);
        assert(this.withAnchors.size === 0, 0x775 /* free should remove all anchors */);
    }
    /**
     * Gets the root field of the tree.
     * @remarks
     * This is a cached value: it should not be disposed by the accessor.
     * Like all other fields from this context, it will become invalid to use after {@link clear} is called or the {@link disposeSymbol} method is called.
     */
    get root() {
        assert(this.disposed === false, 0x804 /* use after dispose */);
        this.lazyRootCache ??= this.detachedField(rootField, this.schema.rootFieldSchema.kind);
        return this.lazyRootCache;
    }
    /**
     * Returns a new {@link FlexTreeField} that will live as long as the caller allows up to the next call to {@link clear} or disposal of the context.
     * @remarks
     * Due to limited support for detached fields, not all operations are supported.
     * Additionally if the detached field's content is deleted, the field will become out of schema if it is required: it must not be used after that point.
     */
    detachedField(key, schema) {
        assert(this.disposed === false, 0xb9c /* use after dispose */);
        const cursor = this.checkout.forest.allocateCursor("root");
        moveToDetachedField(this.checkout.forest, cursor, key);
        const field = makeField(this, schema, cursor);
        cursor.free();
        return field;
    }
    get events() {
        return this.checkout.forest.events;
    }
}
//# sourceMappingURL=context.js.map