"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _LazyTreeNode_removeDeleteCallback;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBoxedField = exports.buildLazyObjectNode = exports.LazyObjectNode = exports.propertyNameFromFieldKey = exports.reservedObjectNodeFieldPropertyNameSet = exports.LazyFieldNode = exports.LazyLeaf = exports.LazyMap = exports.LazyTreeNode = exports.makeTree = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../../core/index.js");
const index_js_2 = require("../../util/index.js");
const index_js_3 = require("../default-schema/index.js");
const index_js_4 = require("../typed-schema/index.js");
const flexTreeTypes_js_1 = require("./flexTreeTypes.js");
const lazyEntity_js_1 = require("./lazyEntity.js");
const lazyField_js_1 = require("./lazyField.js");
const unboxed_js_1 = require("./unboxed.js");
const utilities_js_1 = require("./utilities.js");
/**
 * @param cursor - This does not take ownership of this cursor: Node will fork it as needed.
 */
function makeTree(context, cursor) {
    const anchor = cursor.buildAnchor();
    const anchorNode = context.forest.anchors.locate(anchor) ??
        (0, index_js_2.fail)("cursor should point to a node that is not the root of the AnchorSet");
    const cached = anchorNode.slots.get(flexTreeTypes_js_1.flexTreeSlot);
    if (cached !== undefined) {
        context.forest.anchors.forget(anchor);
        (0, internal_1.assert)(cached.context === context, 0x782 /* contexts must match */);
        (0, internal_1.assert)(cached instanceof LazyTreeNode, "Expected LazyTreeNode");
        return cached;
    }
    const schema = context.schema.nodeSchema.get(cursor.type) ?? (0, index_js_2.fail)("missing schema");
    const output = buildSubclass(context, schema, cursor, anchorNode, anchor);
    anchorNode.slots.set(flexTreeTypes_js_1.flexTreeSlot, output);
    anchorNode.on("afterDestroy", cleanupTree);
    return output;
}
exports.makeTree = makeTree;
function cleanupTree(anchor) {
    const cached = anchor.slots.get(flexTreeTypes_js_1.flexTreeSlot) ?? (0, index_js_2.fail)("tree should only be cleaned up once");
    (0, internal_1.assert)(cached instanceof LazyTreeNode, "Expected LazyTreeNode");
    cached[index_js_2.disposeSymbol]();
}
function buildSubclass(context, schema, cursor, anchorNode, anchor) {
    if ((0, index_js_4.schemaIsMap)(schema)) {
        return new LazyMap(context, schema, cursor, anchorNode, anchor);
    }
    if ((0, index_js_4.schemaIsLeaf)(schema)) {
        return new LazyLeaf(context, schema, cursor, anchorNode, anchor);
    }
    if ((0, index_js_4.schemaIsFieldNode)(schema)) {
        return new LazyFieldNode(context, schema, cursor, anchorNode, anchor);
    }
    if ((0, index_js_4.schemaIsObjectNode)(schema)) {
        return buildLazyObjectNode(context, schema, cursor, anchorNode, anchor);
    }
    // TODO: there should be a common fallback that works for cases without a specialized implementation.
    (0, index_js_2.fail)("unrecognized node kind");
}
/**
 * Lazy implementation of {@link FlexTreeNode}.
 */
class LazyTreeNode extends lazyEntity_js_1.LazyEntity {
    get [(_LazyTreeNode_removeDeleteCallback = new WeakMap(), flexTreeTypes_js_1.flexTreeMarker)]() {
        return flexTreeTypes_js_1.FlexTreeEntityKind.Node;
    }
    constructor(context, schema, cursor, anchorNode, anchor) {
        super(context, schema, cursor, anchor);
        this.anchorNode = anchorNode;
        // Using JS private here prevents it from showing up as a enumerable own property, or conflicting with struct fields.
        _LazyTreeNode_removeDeleteCallback.set(this, void 0);
        (0, internal_1.assert)(cursor.mode === 0 /* CursorLocationType.Nodes */, 0x783 /* must be in nodes mode */);
        anchorNode.slots.set(flexTreeTypes_js_1.flexTreeSlot, this);
        __classPrivateFieldSet(this, _LazyTreeNode_removeDeleteCallback, anchorNode.on("afterDestroy", cleanupTree), "f");
        (0, internal_1.assert)(this.context.schema.nodeSchema.get(this.schema.name) !== undefined, 0x784 /* There is no explicit schema for this node type. Ensure that the type is correct and the schema for it was added to the TreeStoredSchema */);
        this.type = schema.name;
    }
    is(schema) {
        (0, internal_1.assert)(this.context.schema.nodeSchema.get(schema.name) === schema, 0x785 /* Narrowing must be done to a schema that exists in this context */);
        return this.schema === schema;
    }
    [lazyEntity_js_1.tryMoveCursorToAnchorSymbol](cursor) {
        return this.context.forest.tryMoveCursorToNode(this[lazyEntity_js_1.anchorSymbol], cursor);
    }
    [lazyEntity_js_1.forgetAnchorSymbol]() {
        // This type unconditionally has an anchor, so `forgetAnchor` is always called and cleanup can be done here:
        // After this point this node will not be usable,
        // so remove it from the anchor incase a different context (or the same context later) uses this AnchorSet.
        this.anchorNode.slots.delete(flexTreeTypes_js_1.flexTreeSlot);
        __classPrivateFieldGet(this, _LazyTreeNode_removeDeleteCallback, "f").call(this);
        this.context.forest.anchors.forget(this[lazyEntity_js_1.anchorSymbol]);
    }
    get value() {
        return this[lazyEntity_js_1.cursorSymbol].value;
    }
    tryGetField(fieldKey) {
        const schema = this.schema.getFieldSchema(fieldKey);
        return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], fieldKey, (cursor) => {
            if (cursor.getFieldLength() === 0) {
                return undefined;
            }
            return (0, lazyField_js_1.makeField)(this.context, schema, cursor);
        });
    }
    getBoxed(key) {
        return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], (0, index_js_2.brand)(key), (cursor) => (0, lazyField_js_1.makeField)(this.context, this.schema.getFieldSchema(key), cursor));
    }
    boxedIterator() {
        return (0, index_js_1.mapCursorFields)(this[lazyEntity_js_1.cursorSymbol], (cursor) => (0, lazyField_js_1.makeField)(this.context, this.schema.getFieldSchema(cursor.getFieldKey()), cursor)).values();
    }
    get parentField() {
        const cursor = this[lazyEntity_js_1.cursorSymbol];
        const index = this.anchorNode.parentIndex;
        (0, internal_1.assert)(cursor.fieldIndex === index, 0x786 /* mismatched indexes */);
        const key = this.anchorNode.parentField;
        cursor.exitNode();
        (0, internal_1.assert)(key === cursor.getFieldKey(), 0x787 /* mismatched keys */);
        let fieldSchema;
        // Check if the current node is in a detached sequence.
        if (this.anchorNode.parent === undefined) {
            // Parent field is a detached sequence, and thus needs special handling for its schema.
            // eslint-disable-next-line unicorn/prefer-ternary
            if (key === index_js_1.rootFieldKey) {
                fieldSchema = this.context.schema.rootFieldSchema;
            }
            else {
                // All fields (in the flex tree API) have a schema.
                // Since currently there is no known schema for detached field other than the special default root:
                // give all other detached fields a schema of sequence of any.
                // That schema is the only one that is safe since its the only field schema that allows any possible field content.
                //
                // TODO:
                // if any of the following are done this schema will need to be more specific:
                // 1. Editing APIs start exposing user created detached sequences.
                // 2. Remove (and its inverse) start working on subsequences or fields contents (like everything in a sequence or optional field) and not just single nodes.
                // 3. Possibly other unknown cases.
                // Additionally this approach makes it possible for a user to take a FlexTree node, get its parent, check its schema, down cast based on that, then edit that detached field (ex: removing the node in it).
                // This MIGHT work properly with existing merge resolution logic (it must keep client in sync and be unable to violate schema), but this either needs robust testing or to be explicitly banned (error before s3ending the op).
                // Issues like replacing a node in the a removed sequenced then undoing the remove could easily violate schema if not everything works exactly right!
                fieldSchema = index_js_4.FlexFieldSchema.create(index_js_3.FieldKinds.sequence, [index_js_4.Any]);
            }
        }
        else {
            cursor.exitField();
            const parentType = cursor.type;
            cursor.enterField(key);
            const nodeSchema = this.context.schema.nodeSchema.get(parentType) ??
                (0, index_js_2.fail)("requested schema that does not exist");
            fieldSchema = nodeSchema.getFieldSchema(key);
        }
        const proxifiedField = (0, lazyField_js_1.makeField)(this.context, fieldSchema, cursor);
        cursor.enterNode(index);
        return { parent: proxifiedField, index };
    }
    treeStatus() {
        if (this[lazyEntity_js_1.isFreedSymbol]()) {
            return flexTreeTypes_js_1.TreeStatus.Deleted;
        }
        return (0, utilities_js_1.treeStatusFromAnchorCache)(this.context.forest.anchors, this.anchorNode);
    }
    on(eventName, listener) {
        switch (eventName) {
            case "changing": {
                const unsubscribeFromChildrenChange = this.anchorNode.on("childrenChanging", (anchorNode) => listener(anchorNode));
                return unsubscribeFromChildrenChange;
            }
            case "subtreeChanging": {
                const unsubscribeFromSubtreeChange = this.anchorNode.on("subtreeChanging", (anchorNode) => listener(anchorNode));
                return unsubscribeFromSubtreeChange;
            }
            default:
                (0, internal_1.unreachableCase)(eventName);
        }
    }
}
exports.LazyTreeNode = LazyTreeNode;
class LazyMap extends LazyTreeNode {
    constructor(context, schema, cursor, anchorNode, anchor) {
        super(context, schema, cursor, anchorNode, anchor);
    }
    get size() {
        let fieldCount = 0;
        (0, index_js_1.forEachField)(this[lazyEntity_js_1.cursorSymbol], () => (fieldCount += 1));
        return fieldCount;
    }
    keys() {
        return (0, index_js_1.mapCursorFields)(this[lazyEntity_js_1.cursorSymbol], (cursor) => cursor.getFieldKey()).values();
    }
    values() {
        return (0, index_js_1.mapCursorFields)(this[lazyEntity_js_1.cursorSymbol], (cursor) => (0, unboxed_js_1.unboxedField)(this.context, this.schema.info, cursor)).values();
    }
    entries() {
        return (0, index_js_1.mapCursorFields)(this[lazyEntity_js_1.cursorSymbol], (cursor) => {
            const entry = [
                cursor.getFieldKey(),
                (0, unboxed_js_1.unboxedField)(this.context, this.schema.info, cursor),
            ];
            return entry;
        }).values();
    }
    forEach(callbackFn, thisArg) {
        const fn = thisArg !== undefined ? callbackFn.bind(thisArg) : callbackFn;
        for (const [key, value] of this.entries()) {
            fn(value, key, this);
        }
    }
    has(key) {
        return this.tryGetField((0, index_js_2.brand)(key)) !== undefined;
    }
    get(key) {
        return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], (0, index_js_2.brand)(key), (cursor) => (0, unboxed_js_1.unboxedField)(this.context, this.schema.info, cursor));
    }
    getBoxed(key) {
        return super.getBoxed((0, index_js_2.brand)(key));
    }
    set(key, content) {
        const field = this.getBoxed(key);
        const fieldSchema = this.schema.info;
        if (fieldSchema.kind === index_js_3.FieldKinds.optional) {
            const optionalField = field;
            optionalField.content = content;
        }
        else {
            (0, internal_1.assert)(fieldSchema.kind === index_js_3.FieldKinds.sequence, 0x807 /* Unexpected map field kind */);
            // TODO: implement setting of sequence fields once we have defined clear merged semantics for doing so.
            // For now, we will throw an error, since the public API does not currently expose a way to do this anyways.
            throw new Error("Setting of sequence values in maps is not yet supported.");
        }
    }
    delete(key) {
        // Since all keys implicitly exist under a Map node, and we represent "no value" with `undefined`,
        // "deleting" a key/value pair is the same as setting the value to `undefined`.
        this.set(key, undefined);
    }
    boxedIterator() {
        return super.boxedIterator();
    }
    [Symbol.iterator]() {
        return this.entries();
    }
}
exports.LazyMap = LazyMap;
class LazyLeaf extends LazyTreeNode {
    constructor(context, schema, cursor, anchorNode, anchor) {
        super(context, schema, cursor, anchorNode, anchor);
    }
    get value() {
        return super.value;
    }
}
exports.LazyLeaf = LazyLeaf;
class LazyFieldNode extends LazyTreeNode {
    get content() {
        return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], index_js_1.EmptyKey, (cursor) => (0, unboxed_js_1.unboxedField)(this.context, this.schema.info, cursor));
    }
    get boxedContent() {
        return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], index_js_1.EmptyKey, (cursor) => (0, lazyField_js_1.makeField)(this.context, this.schema.info, cursor));
    }
}
exports.LazyFieldNode = LazyFieldNode;
/**
 * {@link reservedObjectNodeFieldPropertyNames} but as a set.
 */
exports.reservedObjectNodeFieldPropertyNameSet = new Set(flexTreeTypes_js_1.reservedObjectNodeFieldPropertyNames);
function propertyNameFromFieldKey(key) {
    if (exports.reservedObjectNodeFieldPropertyNameSet.has(key)) {
        return `field${(0, index_js_2.capitalize)(key)}`;
    }
    for (const prefix of flexTreeTypes_js_1.reservedObjectNodeFieldPropertyNamePrefixes) {
        if (key.startsWith(prefix)) {
            const afterPrefix = key.slice(prefix.length);
            if (afterPrefix === (0, index_js_2.capitalize)(afterPrefix)) {
                return `field${(0, index_js_2.capitalize)(key)}`;
            }
        }
    }
    return key;
}
exports.propertyNameFromFieldKey = propertyNameFromFieldKey;
class LazyObjectNode extends LazyTreeNode {
    get localNodeKey() {
        // TODO: Optimize this to be in the derived class so it can cache schema lookup.
        // TODO: Optimize this to avoid allocating the field object.
        const key = this.context.nodeKeyFieldKey;
        const fieldSchema = this.schema.objectNodeFields.get(key);
        if (fieldSchema === undefined) {
            return undefined;
        }
        const field = this.tryGetField(key);
        (0, internal_1.assert)(field instanceof lazyField_js_1.LazyNodeKeyField, 0x7b4 /* unexpected node key field */);
        // TODO: ideally we would do something like this, but that adds dependencies we can't have here:
        // assert(
        // 	field.is(FlexFieldSchema.create(FieldKinds.nodeKey, [nodeKeyTreeSchema])),
        // 	"invalid node key field",
        // );
        if (this.context.nodeKeyFieldKey === undefined) {
            return undefined;
        }
        return field.localNodeKey;
    }
}
exports.LazyObjectNode = LazyObjectNode;
function buildLazyObjectNode(context, schema, cursor, anchorNode, anchor) {
    const objectNodeClass = (0, index_js_2.getOrCreate)(cachedStructClasses, schema, () => buildStructClass(schema));
    return new objectNodeClass(context, cursor, anchorNode, anchor);
}
exports.buildLazyObjectNode = buildLazyObjectNode;
const cachedStructClasses = new WeakMap();
function getBoxedField(objectNode, key, fieldSchema) {
    return (0, index_js_1.inCursorField)(objectNode[lazyEntity_js_1.cursorSymbol], key, (cursor) => {
        return (0, lazyField_js_1.makeField)(objectNode.context, fieldSchema, cursor);
    });
}
exports.getBoxedField = getBoxedField;
function buildStructClass(schema) {
    const propertyDescriptorMap = {};
    for (const [key, fieldSchema] of schema.objectNodeFields) {
        const escapedKey = propertyNameFromFieldKey(key);
        let setter;
        switch (fieldSchema.kind) {
            case index_js_3.FieldKinds.optional: {
                setter = function (newContent) {
                    const field = getBoxedField(this, key, fieldSchema);
                    field.content = newContent;
                };
                break;
            }
            case index_js_3.FieldKinds.required: {
                setter = function (newContent) {
                    const field = getBoxedField(this, key, fieldSchema);
                    field.content = newContent;
                };
                break;
            }
            default:
                setter = undefined;
                break;
        }
        // Create getter and setter (when appropriate) for property
        propertyDescriptorMap[escapedKey] = {
            enumerable: true,
            get() {
                return (0, index_js_1.inCursorField)(this[lazyEntity_js_1.cursorSymbol], key, (cursor) => (0, unboxed_js_1.unboxedField)(this.context, fieldSchema, cursor));
            },
            set: setter,
        };
        // Create set method for property (when appropriate)
        if (setter !== undefined) {
            propertyDescriptorMap[`set${(0, index_js_2.capitalize)(escapedKey)}`] = {
                enumerable: false,
                get() {
                    return setter;
                },
            };
        }
        propertyDescriptorMap[`boxed${(0, index_js_2.capitalize)(escapedKey)}`] = {
            enumerable: false,
            get() {
                return getBoxedField(this, key, fieldSchema);
            },
        };
    }
    // This must implement `StructTyped<TSchema>`, but TypeScript can't constrain it to do so.
    class CustomStruct extends LazyObjectNode {
        constructor(context, cursor, anchorNode, anchor) {
            super(context, schema, cursor, anchorNode, anchor);
        }
    }
    Object.defineProperties(CustomStruct.prototype, propertyDescriptorMap);
    return CustomStruct;
}
//# sourceMappingURL=lazyNode.js.map