/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { inCursorNode, EmptyKey } from "../../core";
import { FieldKinds } from "../default-field-kinds";
import { fail, oneFromSet } from "../../util";
import { schemaIsFieldNode, schemaIsLeaf, } from "../typed-schema";
import { makeTree } from "./lazyTree";
import { makeField } from "./lazyField";
/**
 * See {@link UnboxNode} for documentation on what unwrapping this performs.
 */
export function unboxedTree(context, schema, cursor) {
    if (schemaIsLeaf(schema)) {
        return cursor.value;
    }
    if (schemaIsFieldNode(schema)) {
        cursor.enterField(EmptyKey);
        const primaryField = makeField(context, schema.objectNodeFields.get(EmptyKey) ?? fail("invalid schema"), cursor);
        cursor.exitField();
        return primaryField;
    }
    return makeTree(context, cursor);
}
/**
 * See {@link UnboxNodeUnion} for documentation on what unwrapping this performs.
 */
export 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 TreeFieldStoredSchema 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.required) {
        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=unboxed.js.map