/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { inCursorNode, iterateCursorField, rootFieldKey, } from "../../core/index.js";
import { disposeSymbol, fail, getOrCreate } from "../../util/index.js";
import { FieldKinds, } from "../default-schema/index.js";
import { FlexTreeEntityKind, TreeStatus, flexTreeMarker, flexTreeSlot, } from "./flexTreeTypes.js";
import { LazyEntity, anchorSymbol, cursorSymbol, forgetAnchorSymbol, isFreedSymbol, tryMoveCursorToAnchorSymbol, } from "./lazyEntity.js";
import { makeTree } from "./lazyNode.js";
import { unboxedFlexNode } from "./unboxed.js";
import { indexForAt, treeStatusFromAnchorCache } from "./utilities.js";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { cursorForMapTreeField, cursorForMapTreeNode } from "../mapTreeCursor.js";
/**
 * Reuse fields.
 * Since field currently own cursors and register themselves for disposal when the node hit end of life,
 * not reusing them results in memory leaks every time the field is accessed.
 * Since the fields stay alive until the node is end of life reusing them this way is safe.
 *
 * This ins't a perfect solution:
 *
 * - This can cause leaks, like map nodes will keep all accessed field objects around. Since other things cause this same leak already, its not too bad.
 * - This does not cache the root.
 * - Finding the parent anchor to do the caching on has significant cost.
 *
 * Despite these limitations, this cache provides a large performance win in some common cases (over 10x), especially with how simple tree requests far more field objects than necessary currently.
 */
const fieldCache = new WeakMap();
export function makeField(context, schema, cursor) {
    const fieldAnchor = cursor.buildFieldAnchor();
    let usedAnchor = false;
    const makeFlexTreeField = () => {
        usedAnchor = true;
        const field = new (kindToClass.get(schema.kind) ?? fail("missing field implementation"))(context, schema, cursor, fieldAnchor);
        return field;
    };
    if (fieldAnchor.parent === undefined) {
        return makeFlexTreeField();
    }
    // For the common case (all but roots), cache field associated with its node's anchor and field key.
    const anchorNode = context.checkout.forest.anchors.locate(fieldAnchor.parent) ?? fail("missing anchor");
    // Since anchor-set could be reused across a flex tree context getting disposed, key off the flex tree node not the anchor.
    const cacheKey = anchorNode.slots.get(flexTreeSlot);
    // If there is no flex tree parent node, skip caching: this is not expected to be a hot path, but should probably be fixed at some point.
    if (cacheKey === undefined) {
        return makeFlexTreeField();
    }
    const innerCache = getOrCreate(fieldCache, cacheKey, () => new Map());
    const result = getOrCreate(innerCache, fieldAnchor.fieldKey, makeFlexTreeField);
    if (!usedAnchor) {
        // The anchor must be disposed to avoid leaking. In the case of a cache hit,
        // we are not transferring ownership to a new FlexTreeField, so it must be disposed of here to avoid the leak.
        context.checkout.forest.anchors.forget(fieldAnchor.parent);
    }
    return result;
}
/**
 * Base type for fields implementing {@link FlexTreeField} using cursors.
 */
export class LazyField extends LazyEntity {
    get [flexTreeMarker]() {
        return FlexTreeEntityKind.Field;
    }
    get schema() {
        return this.flexSchema.stored;
    }
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        assert(cursor.mode === 1 /* CursorLocationType.Fields */, 0x77b /* must be in fields mode */);
        this.key = cursor.getFieldKey();
        // Fields currently live as long as their parent does.
        // For root fields, this means forever, but other cases can be cleaned up when their parent anchor is deleted.
        if (fieldAnchor.parent !== undefined) {
            const anchorNode = context.checkout.forest.anchors.locate(fieldAnchor.parent) ??
                fail("parent anchor node should always exist since field is under a node");
            this.offAfterDestroy = anchorNode.on("afterDestroy", () => {
                this[disposeSymbol]();
            });
        }
    }
    is(kind) {
        assert(this.context.flexSchema.policy.fieldKinds.get(kind.identifier) === kind, 0xa26 /* Narrowing must be done to a kind that exists in this context */);
        return this.flexSchema.kind === kind;
    }
    get parent() {
        if (this[anchorSymbol].parent === undefined) {
            return undefined;
        }
        const cursor = this[cursorSymbol];
        cursor.exitField();
        const output = makeTree(this.context, cursor);
        cursor.enterField(this.key);
        return output;
    }
    [tryMoveCursorToAnchorSymbol](cursor) {
        return this.context.checkout.forest.tryMoveCursorToField(this[anchorSymbol], cursor);
    }
    [forgetAnchorSymbol]() {
        this.offAfterDestroy?.();
        if (this[anchorSymbol].parent === undefined)
            return;
        this.context.checkout.forest.anchors.forget(this[anchorSymbol].parent);
    }
    get length() {
        return this[cursorSymbol].getFieldLength();
    }
    atIndex(index) {
        return inCursorNode(this[cursorSymbol], index, (cursor) => unboxedFlexNode(this.context, cursor));
    }
    boxedAt(index) {
        const finalIndex = indexForAt(index, this.length);
        if (finalIndex === undefined) {
            return undefined;
        }
        return inCursorNode(this[cursorSymbol], finalIndex, (cursor) => makeTree(this.context, cursor));
    }
    map(callbackfn) {
        return Array.from(this, callbackfn);
    }
    boxedIterator() {
        return iterateCursorField(this[cursorSymbol], (cursor) => makeTree(this.context, cursor));
    }
    [Symbol.iterator]() {
        return iterateCursorField(this[cursorSymbol], (cursor) => unboxedFlexNode(this.context, cursor));
    }
    getFieldPath() {
        return this[cursorSymbol].getFieldPath();
    }
    /**
     * Returns the path to this field to use for editing. Throws iff this path is not {@link TreeStatus#InDocument}.
     * This path is not valid to hold onto across edits: this must be recalled for each edit.
     */
    getFieldPathForEditing() {
        if (!this[isFreedSymbol]()) {
            if (
            // Only allow editing if we are the root document field...
            (this.parent === undefined && this[anchorSymbol].fieldKey === rootFieldKey) ||
                // ...or are under a node in the document
                (this.parent !== undefined &&
                    treeStatusFromAnchorCache(this.parent.anchorNode) === TreeStatus.InDocument)) {
                return this.getFieldPath();
            }
        }
        throw new UsageError("Editing only allowed on fields with TreeStatus.InDocument status");
    }
}
export class LazySequence extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        this.editor = {
            insert: (index, newContent) => {
                this.sequenceEditor().insert(index, cursorForMapTreeField(newContent));
            },
            remove: (index, count) => {
                this.sequenceEditor().remove(index, count);
            },
        };
    }
    at(index) {
        const finalIndex = indexForAt(index, this.length);
        if (finalIndex === undefined) {
            return undefined;
        }
        return inCursorNode(this[cursorSymbol], finalIndex, (cursor) => unboxedFlexNode(this.context, cursor));
    }
    get asArray() {
        return this.map((x) => x);
    }
    sequenceEditor() {
        const fieldPath = this.getFieldPathForEditing();
        return this.context.checkout.editor.sequenceField(fieldPath);
    }
}
export class ReadonlyLazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        this.editor = {
            set: (newContent) => {
                assert(false, 0xa0c /* Unexpected set of readonly field */);
            },
        };
    }
    get content() {
        return this.atIndex(0);
    }
}
export class LazyValueField extends ReadonlyLazyValueField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        this.editor = {
            set: (newContent) => {
                this.valueFieldEditor().set(cursorForMapTreeNode(newContent));
            },
        };
    }
    valueFieldEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.checkout.editor.valueField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.atIndex(0);
    }
}
export class LazyOptionalField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        this.editor = {
            set: (newContent, wasEmpty) => {
                this.optionalEditor().set(newContent !== undefined ? cursorForMapTreeNode(newContent) : newContent, wasEmpty);
            },
        };
    }
    optionalEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.checkout.editor.optionalField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.length === 0 ? undefined : this.atIndex(0);
    }
}
export class LazyForbiddenField extends LazyField {
}
const builderList = [
    [FieldKinds.forbidden, LazyForbiddenField],
    [FieldKinds.optional, LazyOptionalField],
    [FieldKinds.sequence, LazySequence],
    [FieldKinds.required, LazyValueField],
    [FieldKinds.identifier, LazyValueField],
];
const kindToClass = new Map(builderList);
//# sourceMappingURL=lazyField.js.map