"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.unboxedField = exports.unboxedUnion = exports.unboxedTree = void 0;
const core_1 = require("../../core");
const default_field_kinds_1 = require("../default-field-kinds");
const util_1 = require("../../util");
const typed_schema_1 = require("../typed-schema");
const lazyTree_1 = require("./lazyTree");
const lazyField_1 = require("./lazyField");
/**
 * See {@link UnboxNode} for documentation on what unwrapping this performs.
 */
function unboxedTree(context, schema, cursor) {
    if ((0, typed_schema_1.schemaIsLeaf)(schema)) {
        return cursor.value;
    }
    if ((0, typed_schema_1.schemaIsFieldNode)(schema)) {
        cursor.enterField(core_1.EmptyKey);
        const primaryField = (0, lazyField_1.makeField)(context, schema.objectNodeFields.get(core_1.EmptyKey) ?? (0, util_1.fail)("invalid schema"), cursor);
        cursor.exitField();
        return primaryField;
    }
    return (0, lazyTree_1.makeTree)(context, cursor);
}
exports.unboxedTree = unboxedTree;
/**
 * See {@link UnboxNodeUnion} for documentation on what unwrapping this performs.
 */
function unboxedUnion(context, schema, cursor) {
    const type = (0, util_1.oneFromSet)(schema.types);
    if (type !== undefined) {
        return unboxedTree(context, context.schema.treeSchema.get(type) ?? (0, util_1.fail)("missing schema"), cursor);
    }
    return (0, lazyTree_1.makeTree)(context, cursor);
}
exports.unboxedUnion = unboxedUnion;
/**
 * @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.
 */
function unboxedField(context, schema, cursor) {
    const kind = schema.kind;
    if (kind === default_field_kinds_1.FieldKinds.required) {
        return (0, core_1.inCursorNode)(cursor, 0, (innerCursor) => unboxedUnion(context, schema, innerCursor));
    }
    if (kind === default_field_kinds_1.FieldKinds.optional) {
        if (cursor.getFieldLength() === 0) {
            return undefined;
        }
        return (0, core_1.inCursorNode)(cursor, 0, (innerCursor) => unboxedUnion(context, schema, innerCursor));
    }
    // TODO: forbidden and nodeKey
    return (0, lazyField_1.makeField)(context, schema, cursor);
}
exports.unboxedField = unboxedField;
//# sourceMappingURL=unboxed.js.map