/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { mapCursorField, inCursorNode, keyAsDetachedField, rootField, EmptyKey, } from "../../core";
import { normalizeNewFieldContent } from "../contextuallyTyped";
import { FieldKinds, } from "../default-field-kinds";
import { compareSets, disposeSymbol, fail, oneFromSet } from "../../util";
import { schemaIsFieldNode, schemaIsLeaf, } from "../typed-schema";
import { TreeStatus, treeStatusFromPath } from "../editable-tree";
import { makeTree } from "./lazyTree";
import { LazyEntity, anchorSymbol, cursorSymbol, forgetAnchorSymbol, isFreedSymbol, makePropertyEnumerableOwn, makePropertyNotEnumerable, tryMoveCursorToAnchorSymbol, } from "./lazyEntity";
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("afterDelete", () => {
            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 /* Fields */, "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, "Narrowing must be done to a kind that exists in this context");
        if (schema.kind !== schema.kind) {
            return false;
        }
        if (schema.types === undefined) {
            return this.schema.types === undefined;
        }
        if (this.schema.types === undefined) {
            return false;
        }
        return compareSets({ a: this.schema.types, b: schema.types });
    }
    isSameAs(other) {
        assert(other.context === this.context, "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 mapCursorField(this[cursorSymbol], (cursor) => callbackfn(unboxedUnion(this.context, this.schema, cursor), cursor.fieldIndex, this));
    }
    mapBoxed(callbackfn) {
        return mapCursorField(this[cursorSymbol], (cursor) => callbackfn(makeTree(this.context, cursor), cursor.fieldIndex, this));
    }
    [Symbol.iterator]() {
        return this.mapBoxed((x) => x)[Symbol.iterator]();
    }
    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 keyAsDetachedField(fieldAnchor.fieldKey) === rootField
                ? TreeStatus.InDocument
                : TreeStatus.Removed;
        }
        const parentAnchorNode = this.context.forest.anchors.locate(parentAnchor);
        // As the "parentAnchor === undefined" case is handled above, parentAnchorNode should exist.
        assert(parentAnchorNode !== undefined, "parentAnchorNode must exist.");
        return treeStatusFromPath(parentAnchorNode);
    }
    getFieldPath() {
        return this[cursorSymbol].getFieldPath();
    }
}
export class LazySequence extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        makePropertyEnumerableOwn(this, "asArray", LazySequence.prototype);
    }
    sequenceEditor() {
        const fieldPath = this[cursorSymbol].getFieldPath();
        const fieldEditor = this.context.editor.sequenceField(fieldPath);
        return fieldEditor;
    }
    replaceRange(index, count, newContent) {
        const fieldEditor = this.sequenceEditor();
        const content = this.normalizeNewContent([...newContent]);
        fieldEditor.delete(index, count);
        fieldEditor.insert(index, content);
    }
    get asArray() {
        return this.map((x) => x);
    }
}
export class LazyValueField extends LazyField {
    constructor(context, schema, cursor, fieldAnchor) {
        super(context, schema, cursor, fieldAnchor);
        makePropertyEnumerableOwn(this, "content", LazyValueField.prototype);
    }
    valueFieldEditor() {
        const fieldPath = this[cursorSymbol].getFieldPath();
        const fieldEditor = this.context.editor.valueField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.at(0);
    }
    get boxedContent() {
        return this.boxedAt(0);
    }
    setContent(newContent) {
        const content = this.normalizeNewContent(newContent);
        const fieldEditor = this.valueFieldEditor();
        assert(content.length === 1, "value field content should normalize to one item");
        fieldEditor.set(content[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[cursorSymbol].getFieldPath();
        const fieldEditor = this.context.editor.optionalField(fieldPath);
        return fieldEditor;
    }
    get content() {
        return this.length === 0 ? undefined : this.at(0);
    }
    get boxedContent() {
        return this.length === 0 ? undefined : this.boxedAt(0);
    }
    setContent(newContent) {
        const content = this.normalizeNewContent(newContent);
        const fieldEditor = this.optionalEditor();
        assert(content.length <= 1, "optional field content should normalize at most one item");
        fieldEditor.set(content.length === 0 ? undefined : content[0], this.length === 0);
    }
}
export class LazyForbiddenField extends LazyField {
}
const builderList = [
    [FieldKinds.forbidden, LazyForbiddenField],
    [FieldKinds.nodeKey, LazyOptionalField],
    [FieldKinds.optional, LazyOptionalField],
    [FieldKinds.sequence, LazySequence],
    [FieldKinds.value, LazyValueField],
];
const kindToClass = new Map(builderList);
/**
 * See {@link UnboxNode} for documentation on what unwrapping this performs.
 */
function unboxedTree(context, schema, cursor) {
    if (schemaIsLeaf(schema)) {
        return cursor.value;
    }
    if (schemaIsFieldNode(schema)) {
        cursor.enterField(EmptyKey);
        const primaryField = makeField(context, schema.structFields.get(EmptyKey) ?? fail("invalid schema"), cursor);
        cursor.exitField();
        return primaryField;
    }
    return makeTree(context, cursor);
}
/**
 * See {@link UnboxNodeUnion} for documentation on what unwrapping this performs.
 */
function unboxedUnion(context, schema, cursor) {
    const type = oneFromSet(schema.types);
    if (type !== undefined) {
        return unboxedTree(context, context.schema.treeSchema.get(type) ?? fail("missing schema"), cursor);
    }
    return makeTree(context, cursor);
}
/**
 * @param context - the common context of the field.
 * @param schema - the FieldStoredSchema of the field.
 * @param cursor - the cursor, which must point to the field being proxified.
 */
export function unboxedField(context, schema, cursor) {
    const kind = schema.kind;
    if (kind === FieldKinds.value) {
        return inCursorNode(cursor, 0, (innerCursor) => unboxedUnion(context, schema, innerCursor));
    }
    if (kind === FieldKinds.optional) {
        if (cursor.getFieldLength() === 0) {
            return undefined;
        }
        return inCursorNode(cursor, 0, (innerCursor) => unboxedUnion(context, schema, innerCursor));
    }
    // TODO: forbidden and nodeKey
    return makeField(context, schema, cursor);
}
//# sourceMappingURL=lazyField.js.map