"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.LazyForbiddenField = exports.LazyNodeKeyField = exports.LazyOptionalField = exports.LazyValueField = exports.LazySequence = exports.LazyField = exports.makeField = void 0;
const core_utils_1 = require("@fluidframework/core-utils");
const core_1 = require("../../core");
const contextuallyTyped_1 = require("../contextuallyTyped");
const default_field_kinds_1 = require("../default-field-kinds");
const util_1 = require("../../util");
const node_key_1 = require("../node-key");
const editableTreeTypes_1 = require("./editableTreeTypes");
const lazyTree_1 = require("./lazyTree");
const lazyEntity_1 = require("./lazyEntity");
const unboxed_1 = require("./unboxed");
const utilities_1 = require("./utilities");
function makeField(context, schema, cursor) {
    const fieldAnchor = cursor.buildFieldAnchor();
    const field = new (kindToClass.get(schema.kind) ?? (0, util_1.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) ??
            (0, util_1.fail)("parent anchor node should always exist since field is under a node");
        anchorNode.on("afterDestroy", () => {
            field[util_1.disposeSymbol]();
        });
    }
    return field;
}
exports.makeField = makeField;
/**
 * A Proxy target, which together with a `fieldProxyHandler` implements a basic access to
 * the nodes of {@link EditableField} by means of the cursors.
 */
class LazyField extends lazyEntity_1.LazyEntity {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        (0, core_utils_1.assert)(cursor.mode === 1 /* CursorLocationType.Fields */, 0x77b /* must be in fields mode */);
        this.key = cursor.getFieldKey();
        (0, lazyEntity_1.makePropertyNotEnumerable)(this, "key");
    }
    is(schema) {
        (0, core_utils_1.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) {
        (0, core_utils_1.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 (0, contextuallyTyped_1.normalizeNewFieldContent)(this.context, this.schema, content);
    }
    get parent() {
        if (this[lazyEntity_1.anchorSymbol].parent === undefined) {
            return undefined;
        }
        const cursor = this[lazyEntity_1.cursorSymbol];
        cursor.exitField();
        const output = (0, lazyTree_1.makeTree)(this.context, cursor);
        cursor.enterField(this.key);
        return output;
    }
    [lazyEntity_1.tryMoveCursorToAnchorSymbol](anchor, cursor) {
        return this.context.forest.tryMoveCursorToField(anchor, cursor);
    }
    [lazyEntity_1.forgetAnchorSymbol](anchor) {
        if (anchor.parent === undefined)
            return;
        this.context.forest.anchors.forget(anchor.parent);
    }
    get length() {
        return this[lazyEntity_1.cursorSymbol].getFieldLength();
    }
    at(index) {
        return (0, core_1.inCursorNode)(this[lazyEntity_1.cursorSymbol], index, (cursor) => (0, unboxed_1.unboxedUnion)(this.context, this.schema, cursor));
    }
    boxedAt(index) {
        return (0, core_1.inCursorNode)(this[lazyEntity_1.cursorSymbol], index, (cursor) => (0, lazyTree_1.makeTree)(this.context, cursor));
    }
    map(callbackfn) {
        return Array.from(this, callbackfn);
    }
    mapBoxed(callbackfn) {
        return Array.from(this[editableTreeTypes_1.boxedIterator](), callbackfn);
    }
    [editableTreeTypes_1.boxedIterator]() {
        return (0, core_1.iterateCursorField)(this[lazyEntity_1.cursorSymbol], (cursor) => (0, lazyTree_1.makeTree)(this.context, cursor));
    }
    [Symbol.iterator]() {
        return (0, core_1.iterateCursorField)(this[lazyEntity_1.cursorSymbol], (cursor) => (0, unboxed_1.unboxedUnion)(this.context, this.schema, cursor));
    }
    treeStatus() {
        if (this[lazyEntity_1.isFreedSymbol]()) {
            return editableTreeTypes_1.TreeStatus.Deleted;
        }
        const fieldAnchor = this[lazyEntity_1.anchorSymbol];
        const parentAnchor = fieldAnchor.parent;
        // If the parentAnchor is undefined it is a detached field.
        if (parentAnchor === undefined) {
            return (0, utilities_1.treeStatusFromDetachedField)((0, core_1.keyAsDetachedField)(fieldAnchor.fieldKey));
        }
        const parentAnchorNode = this.context.forest.anchors.locate(parentAnchor);
        // As the "parentAnchor === undefined" case is handled above, parentAnchorNode should exist.
        (0, core_utils_1.assert)(parentAnchorNode !== undefined, 0x77e /* parentAnchorNode must exist. */);
        return (0, utilities_1.treeStatusFromAnchorCache)(this.context.forest.anchors, parentAnchorNode);
    }
    getFieldPath() {
        return this[lazyEntity_1.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() {
        (0, core_utils_1.assert)(this.treeStatus() === editableTreeTypes_1.TreeStatus.InDocument, 0x77f /* Editing only allowed on fields with TreeStatus.InDocument status */);
        return this.getFieldPath();
    }
}
exports.LazyField = LazyField;
function assertIsLazySequence(sourceField) {
    (0, core_utils_1.assert)(sourceField instanceof LazySequence, 0x7b1 /* Unsupported sequence implementation. */);
}
class LazySequence extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        (0, lazyEntity_1.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));
        (0, util_1.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);
        (0, util_1.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);
        (0, util_1.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
            }
        }
        (0, util_1.assertValidIndex)(destinationIndex, this, true);
        const sourceFieldPath = sourceField.getFieldPath();
        const destinationFieldPath = this.getFieldPath();
        this.context.editor.move(sourceFieldPath, sourceStart, movedCount, destinationFieldPath, destinationIndex);
    }
}
exports.LazySequence = LazySequence;
class LazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        (0, lazyEntity_1.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();
        (0, core_utils_1.assert)(content.length === 1, 0x780 /* value field content should normalize to one item */);
        fieldEditor.set(content[0]);
    }
    get boxedContent() {
        return this.boxedAt(0);
    }
}
exports.LazyValueField = LazyValueField;
class LazyOptionalField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        (0, lazyEntity_1.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();
        (0, core_utils_1.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);
    }
}
exports.LazyOptionalField = LazyOptionalField;
class LazyNodeKeyField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        (0, lazyEntity_1.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[lazyEntity_1.cursorSymbol];
        cursor.enterNode(0);
        (0, core_utils_1.assert)(cursor.type === node_key_1.nodeKeyTreeIdentifier, 0x7b2 /* invalid node key type */);
        const stableKey = cursor.value;
        (0, core_utils_1.assert)(typeof stableKey === "string", 0x7b3 /* invalid node key type */);
        cursor.exitNode();
        return (0, util_1.brand)(stableKey);
    }
}
exports.LazyNodeKeyField = LazyNodeKeyField;
class LazyForbiddenField extends LazyField {
}
exports.LazyForbiddenField = LazyForbiddenField;
const builderList = [
    [default_field_kinds_1.FieldKinds.forbidden, LazyForbiddenField],
    [default_field_kinds_1.FieldKinds.nodeKey, LazyNodeKeyField],
    [default_field_kinds_1.FieldKinds.optional, LazyOptionalField],
    [default_field_kinds_1.FieldKinds.sequence, LazySequence],
    [default_field_kinds_1.FieldKinds.required, LazyValueField],
];
const kindToClass = new Map(builderList);
//# sourceMappingURL=lazyField.js.map