/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { inCursorNode, keyAsDetachedField, iterateCursorField, } from "../../core";
import { normalizeNewFieldContent } from "../contextuallyTyped";
import { FieldKinds, } from "../default-field-kinds";
import { assertValidIndex, assertValidRangeIndices, brand, disposeSymbol, fail } from "../../util";
import { nodeKeyTreeIdentifier } from "../node-key";
import { boxedIterator, TreeStatus, } from "./editableTreeTypes";
import { makeTree } from "./lazyTree";
import { LazyEntity, anchorSymbol, cursorSymbol, forgetAnchorSymbol, isFreedSymbol, makePropertyEnumerableOwn, makePropertyNotEnumerable, tryMoveCursorToAnchorSymbol, } from "./lazyEntity";
import { unboxedUnion } from "./unboxed";
import { treeStatusFromAnchorCache, treeStatusFromDetachedField } from "./utilities";
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 {
    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();
        makePropertyNotEnumerable(this, "key");
    }
    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;
    }
    normalizeNewContent(content) {
        return normalizeNewFieldContent(this.context, this.schema, content);
    }
    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();
    }
    at(index) {
        return inCursorNode(this[cursorSymbol], index, (cursor) => unboxedUnion(this.context, this.schema, cursor));
    }
    boxedAt(index) {
        return inCursorNode(this[cursorSymbol], index, (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();
    }
}
function assertIsLazySequence(sourceField) {
    assert(sourceField instanceof LazySequence, 0x7b1 /* Unsupported sequence implementation. */);
}
export class LazySequence extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        makePropertyEnumerableOwn(this, "asArray", LazySequence.prototype);
    }
    get asArray() {
        return this.map((x) => x);
    }
    sequenceEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.editor.sequenceField(fieldPath);
        return fieldEditor;
    }
    insertAt(index, value) {
        const fieldEditor = this.sequenceEditor();
        const content = this.normalizeNewContent(Array.isArray(value) ? value : Array.from(value));
        assertValidIndex(index, this, true);
        fieldEditor.insert(index, content);
    }
    insertAtStart(value) {
        this.insertAt(0, value);
    }
    insertAtEnd(value) {
        this.insertAt(this.length, value);
    }
    removeAt(index) {
        const fieldEditor = this.sequenceEditor();
        fieldEditor.delete(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.delete(removeStart, removeEnd - removeStart);
    }
    moveToStart(sourceStart, sourceEnd, source) {
        this._moveToIndex(0, sourceStart, sourceEnd, source);
    }
    moveToEnd(sourceStart, sourceEnd, source) {
        this._moveToIndex(this.length, sourceStart, sourceEnd, source);
    }
    moveToIndex(index, sourceStart, sourceEnd, source) {
        this._moveToIndex(index, sourceStart, sourceEnd, source);
    }
    _moveToIndex(index, sourceStart, sourceEnd, source) {
        const sourceField = source !== undefined ? (this.isSameAs(source) ? this : source) : this;
        // TODO: determine support for move across different sequence types
        assertIsLazySequence(sourceField);
        assertValidRangeIndices(sourceStart, sourceEnd, sourceField);
        if (this.schema.types !== undefined && sourceField !== this) {
            for (let i = sourceStart; i < sourceEnd; i++) {
                const sourceNode = sourceField.boxedAt(sourceStart);
                if (!this.schema.types.has(sourceNode.schema.name)) {
                    throw new Error("Type in source sequence is not allowed in destination.");
                }
            }
        }
        const movedCount = sourceEnd - sourceStart;
        let destinationIndex = index;
        if (sourceField === this) {
            if (destinationIndex > sourceStart) {
                destinationIndex =
                    destinationIndex < sourceEnd
                        ? sourceStart // destination overlaps with source range -> slide to left
                        : (destinationIndex -= movedCount); // destination after source range -> subtract moved count
            }
        }
        assertValidIndex(destinationIndex, this, true);
        const sourceFieldPath = sourceField.getFieldPath();
        const destinationFieldPath = this.getFieldPath();
        this.context.editor.move(sourceFieldPath, sourceStart, movedCount, destinationFieldPath, destinationIndex);
    }
}
export class LazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        makePropertyEnumerableOwn(this, "content", LazyValueField.prototype);
    }
    valueFieldEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.editor.valueField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.at(0);
    }
    set content(newContent) {
        const content = this.normalizeNewContent(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);
    }
}
export class LazyOptionalField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        makePropertyEnumerableOwn(this, "content", LazyOptionalField.prototype);
    }
    optionalEditor() {
        const fieldPath = this.getFieldPathForEditing();
        const fieldEditor = this.context.editor.optionalField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.length === 0 ? undefined : this.at(0);
    }
    set content(newContent) {
        const content = this.normalizeNewContent(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);
        makePropertyEnumerableOwn(this, "stableNodeKey", LazyNodeKeyField.prototype);
    }
    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);
//# sourceMappingURL=lazyField.js.map