/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { inCursorNode, keyAsDetachedField, iterateCursorField, isCursor, } from "../../core/index.js";
// TODO: stop depending on contextuallyTyped
import { applyTypesFromContext, cursorFromContextualData } from "../contextuallyTyped.js";
import { FieldKinds, } from "../default-schema/index.js";
import { assertValidIndex, assertValidRangeIndices, brand, disposeSymbol, fail, } from "../../util/index.js";
import { nodeKeyTreeIdentifier } from "../node-key/index.js";
import { cursorForMapTreeField } from "../mapTreeCursor.js";
import { TreeStatus, FlexTreeEntityKind, flexTreeMarker, } from "./flexTreeTypes.js";
import { makeTree } from "./lazyNode.js";
import { LazyEntity, anchorSymbol, cursorSymbol, forgetAnchorSymbol, isFreedSymbol, tryMoveCursorToAnchorSymbol, } from "./lazyEntity.js";
import { unboxedUnion } from "./unboxed.js";
import { treeStatusFromAnchorCache, treeStatusFromDetachedField } from "./utilities.js";
/**
 * Indexing for {@link LazyField.at} and {@link LazyField.boxedAt} supports the
 * usage of negative indices, which regular indexing using `[` and `]` does not.
 *
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
 * for additional context on the semantics.
 *
 * @returns A positive index that can be used in regular indexing. Returns
 * undefined if that index would be out-of-bounds.
 */
function indexForAt(index, length) {
    let finalIndex = Math.trunc(+index);
    if (isNaN(finalIndex)) {
        finalIndex = 0;
    }
    if (finalIndex < -length || finalIndex >= length) {
        return undefined;
    }
    if (finalIndex < 0) {
        finalIndex = finalIndex + length;
    }
    return finalIndex;
}
export function makeField(context, schema, cursor) {
    const fieldAnchor = cursor.buildFieldAnchor();
    const field = new (kindToClass.get(schema.kind) ?? fail("missing field implementation"))(context, schema, cursor, fieldAnchor);
    // 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.forest.anchors.locate(fieldAnchor.parent) ??
            fail("parent anchor node should always exist since field is under a node");
        anchorNode.on("afterDestroy", () => {
            field[disposeSymbol]();
        });
    }
    return field;
}
/**
 * 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();
    }
    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 editable 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](anchor, cursor) {
        return this.context.forest.tryMoveCursorToField(anchor, cursor);
    }
    [forgetAnchorSymbol](anchor) {
        if (anchor.parent === undefined)
            return;
        this.context.forest.anchors.forget(anchor.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.forest.anchors.locate(parentAnchor);
        // As the "parentAnchor === undefined" case is handled above, parentAnchorNode should exist.
        assert(parentAnchorNode !== undefined, 0x77e /* parentAnchorNode must exist. */);
        return treeStatusFromAnchorCache(this.context.forest.anchors, 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() {
        assert(this.treeStatus() === TreeStatus.InDocument, 0x77f /* 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.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);
    }
    removeRange(start, end) {
        const fieldEditor = this.sequenceEditor();
        const { length } = this;
        const removeStart = start ?? 0;
        const removeEnd = Math.min(length, end ?? length);
        assertValidRangeIndices(removeStart, removeEnd, this);
        fieldEditor.remove(removeStart, removeEnd - removeStart);
    }
    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.editor.move(sourceFieldPath, sourceStart, movedCount, destinationFieldPath, index);
    }
}
export class LazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    valueFieldEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.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 LazyOptionalField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    optionalEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.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 LazyNodeKeyField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
    }
    get localNodeKey() {
        // TODO: Optimize this to be a fast path that gets a LocalNodeKey directly from the
        // forest rather than getting the StableNodeKey and the compressing it.
        return this.context.nodeKeys.localize(this.stableNodeKey);
    }
    get stableNodeKey() {
        const cursor = this[cursorSymbol];
        cursor.enterNode(0);
        assert(cursor.type === nodeKeyTreeIdentifier, 0x7b2 /* invalid node key type */);
        const stableKey = cursor.value;
        assert(typeof stableKey === "string", 0x7b3 /* invalid node key type */);
        cursor.exitNode();
        return brand(stableKey);
    }
}
export class LazyForbiddenField extends LazyField {
}
const builderList = [
    [FieldKinds.forbidden, LazyForbiddenField],
    [FieldKinds.nodeKey, LazyNodeKeyField],
    [FieldKinds.optional, LazyOptionalField],
    [FieldKinds.sequence, LazySequence],
    [FieldKinds.required, LazyValueField],
];
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