/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { inCursorNode, isCursor, iterateCursorField, keyAsDetachedField, } from "../../core/index.js";
import { assertValidIndex, assertValidRangeIndices, disposeSymbol, fail, getOrCreate, } from "../../util/index.js";
// TODO: stop depending on contextuallyTyped
import { applyTypesFromContext, cursorFromContextualData } from "../contextuallyTyped.js";
import { FieldKinds, } from "../default-schema/index.js";
import { cursorForMapTreeField } from "../mapTreeCursor.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 { unboxedUnion } from "./unboxed.js";
import { indexForAt, treeStatusFromAnchorCache, treeStatusFromDetachedField, } from "./utilities.js";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
/**
 * 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;
}
/**
 * A Proxy target, which together with a `fieldProxyHandler` implements a basic access to
 * the nodes of {@link EditableField} by means of the cursors.
 */
export class LazyField extends LazyEntity {
    get [flexTreeMarker]() {
        return FlexTreeEntityKind.Field;
    }
    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(schema) {
        assert(this.context.schema.policy.fieldKinds.get(schema.kind.identifier) === schema.kind, 0x77c /* Narrowing must be done to a kind that exists in this context */);
        return this.schema.equals(schema);
    }
    isSameAs(other) {
        assert(other.context === this.context, 0x77d /* Content from different flex trees should not be used together */);
        return this.key === other.key && this.parent === other.parent;
    }
    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) => unboxedUnion(this.context, this.schema, 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);
    }
    mapBoxed(callbackfn) {
        return Array.from(this.boxedIterator(), callbackfn);
    }
    boxedIterator() {
        return iterateCursorField(this[cursorSymbol], (cursor) => makeTree(this.context, cursor));
    }
    [Symbol.iterator]() {
        return iterateCursorField(this[cursorSymbol], (cursor) => unboxedUnion(this.context, this.schema, cursor));
    }
    treeStatus() {
        if (this[isFreedSymbol]()) {
            return TreeStatus.Deleted;
        }
        const fieldAnchor = this[anchorSymbol];
        const parentAnchor = fieldAnchor.parent;
        // If the parentAnchor is undefined it is a detached field.
        if (parentAnchor === undefined) {
            return treeStatusFromDetachedField(keyAsDetachedField(fieldAnchor.fieldKey));
        }
        const parentAnchorNode = this.context.checkout.forest.anchors.locate(parentAnchor);
        // As the "parentAnchor === undefined" case is handled above, parentAnchorNode should exist.
        assert(parentAnchorNode !== undefined, 0x77e /* parentAnchorNode must exist. */);
        return treeStatusFromAnchorCache(parentAnchorNode);
    }
    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.treeStatus() !== TreeStatus.InDocument) {
            throw new UsageError("Editing only allowed on fields with TreeStatus.InDocument status");
        }
        return this.getFieldPath();
    }
}
export class LazySequence extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    at(index) {
        const finalIndex = indexForAt(index, this.length);
        if (finalIndex === undefined) {
            return undefined;
        }
        return inCursorNode(this[cursorSymbol], finalIndex, (cursor) => unboxedUnion(this.context, this.schema, cursor));
    }
    get asArray() {
        return this.map((x) => x);
    }
    sequenceEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.checkout.editor.sequenceField(fieldPath);
        return fieldEditor;
    }
    insertAt(index, value) {
        assertValidIndex(index, this, true);
        const content = isCursor(value)
            ? prepareFieldCursorForInsert(value)
            : cursorForMapTreeField(Array.from(value, (item) => applyTypesFromContext(this.context, this.schema.allowedTypeSet, item)));
        const fieldEditor = this.sequenceEditor();
        fieldEditor.insert(index, content);
    }
    insertAtStart(value) {
        this.insertAt(0, value);
    }
    insertAtEnd(value) {
        this.insertAt(this.length, value);
    }
    removeAt(index) {
        const fieldEditor = this.sequenceEditor();
        fieldEditor.remove(index, 1);
    }
    moveToStart(sourceIndex, source) {
        this._moveRangeToIndex(0, sourceIndex, sourceIndex + 1, source);
    }
    moveToEnd(sourceIndex, source) {
        this._moveRangeToIndex(this.length, sourceIndex, sourceIndex + 1, source);
    }
    moveToIndex(index, sourceIndex, source) {
        this._moveRangeToIndex(index, sourceIndex, sourceIndex + 1, source);
    }
    moveRangeToStart(sourceStart, sourceEnd, source) {
        this._moveRangeToIndex(0, sourceStart, sourceEnd, source);
    }
    moveRangeToEnd(sourceStart, sourceEnd, source) {
        this._moveRangeToIndex(this.length, sourceStart, sourceEnd, source);
    }
    moveRangeToIndex(index, sourceStart, sourceEnd, source) {
        this._moveRangeToIndex(index, sourceStart, sourceEnd, source);
    }
    _moveRangeToIndex(index, sourceStart, sourceEnd, source) {
        const sourceField = source !== undefined ? (this.isSameAs(source) ? this : source) : this;
        // TODO: determine support for move across different sequence types
        assert(sourceField instanceof LazySequence, 0x7b1 /* Unsupported sequence implementation. */);
        assertValidRangeIndices(sourceStart, sourceEnd, sourceField);
        if (this.schema.types !== undefined && sourceField !== this) {
            for (let i = sourceStart; i < sourceEnd; i++) {
                const sourceNode = sourceField.boxedAt(sourceStart) ?? fail("impossible out of bounds index");
                if (!this.schema.types.has(sourceNode.schema.name)) {
                    throw new Error("Type in source sequence is not allowed in destination.");
                }
            }
        }
        const movedCount = sourceEnd - sourceStart;
        assertValidIndex(index, this, true);
        const sourceFieldPath = sourceField.getFieldPath();
        const destinationFieldPath = this.getFieldPath();
        this.context.checkout.editor.move(sourceFieldPath, sourceStart, movedCount, destinationFieldPath, index);
    }
}
export class ReadonlyLazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    get content() {
        return this.atIndex(0);
    }
    set content(newContent) {
        fail("cannot set content in readonly field");
    }
    get boxedContent() {
        return this.boxedAt(0) ?? fail("value node must have 1 item");
    }
}
export class LazyValueField extends ReadonlyLazyValueField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    valueFieldEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.checkout.editor.valueField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.atIndex(0);
    }
    set content(newContent) {
        const content = isCursor(newContent)
            ? prepareNodeCursorForInsert(newContent)
            : [cursorFromContextualData(this.context, this.schema.allowedTypeSet, newContent)];
        const fieldEditor = this.valueFieldEditor();
        assert(content.length === 1, 0x780 /* value field content should normalize to one item */);
        fieldEditor.set(content[0]);
    }
    get boxedContent() {
        return this.boxedAt(0) ?? fail("value node must have 1 item");
    }
}
export class LazyIdentifierField extends ReadonlyLazyValueField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
}
export class LazyOptionalField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    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);
    }
    set content(newContent) {
        const content = newContent === undefined
            ? []
            : isCursor(newContent)
                ? prepareNodeCursorForInsert(newContent)
                : [cursorFromContextualData(this.context, this.schema.allowedTypeSet, newContent)];
        const fieldEditor = this.optionalEditor();
        assert(content.length <= 1, 0x781 /* optional field content should normalize at most one item */);
        fieldEditor.set(content.length === 0 ? undefined : content[0], this.length === 0);
    }
    get boxedContent() {
        return this.length === 0 ? undefined : this.boxedAt(0);
    }
}
export class LazyForbiddenField extends LazyField {
}
const builderList = [
    [FieldKinds.forbidden, LazyForbiddenField],
    [FieldKinds.optional, LazyOptionalField],
    [FieldKinds.sequence, LazySequence],
    [FieldKinds.required, LazyValueField],
    [FieldKinds.identifier, LazyIdentifierField],
];
const kindToClass = new Map(builderList);
/**
 * Prepare a fields cursor (holding a sequence of nodes) for inserting.
 */
function prepareFieldCursorForInsert(cursor) {
    // TODO: optionally validate content against schema.
    assert(cursor.mode === 1 /* CursorLocationType.Fields */, 0x8cb /* should be in fields mode */);
    return cursor;
}
/**
 * Prepare a node cursor (holding a single node) for inserting.
 */
function prepareNodeCursorForInsert(cursor) {
    // TODO: optionally validate content against schema.
    assert(cursor.mode === 0 /* CursorLocationType.Nodes */, 0x805 /* should be in nodes mode */);
    return [cursor];
}
//# sourceMappingURL=lazyField.js.map