"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createIdentifierIndex = void 0;
const internal_1 = require("@fluidframework/telemetry-utils/internal");
const schemaTypes_js_1 = require("../schemaTypes.js");
const objectNodeTypes_js_1 = require("../objectNodeTypes.js");
const walkFieldSchema_js_1 = require("../walkFieldSchema.js");
const simpleTreeIndex_js_1 = require("./simpleTreeIndex.js");
function isStringKey(key) {
    return typeof key === "string";
}
/**
 * Creates an {@link IdentifierIndex} for a given {@link TreeView}.
 *
 * @alpha
 */
function createIdentifierIndex(view) {
    // For each node schema, find which field key the identifier field is under.
    // This can be done easily because identifiers are their own field kinds.
    const identifierFields = new Map();
    (0, walkFieldSchema_js_1.walkFieldSchema)(view.schema, {
        node: (schemus) => {
            if (schemus instanceof objectNodeTypes_js_1.ObjectNodeSchema) {
                for (const [fieldKey, fieldSchema] of schemus.fields.entries()) {
                    if (fieldSchema.kind === schemaTypes_js_1.FieldKind.Identifier) {
                        identifierFields.set(schemus.identifier, fieldKey);
                        break;
                    }
                }
            }
        },
    });
    return (0, simpleTreeIndex_js_1.createSimpleTreeIndex)(view, (schemus) => identifierFields.get(schemus.identifier), (nodes) => {
        if (nodes.length > 1) {
            throw new internal_1.UsageError("cannot retrieve node from index: there are multiple nodes with the same identifier");
        }
        return nodes[0];
    }, isStringKey);
}
exports.createIdentifierIndex = createIdentifierIndex;
//# sourceMappingURL=identifierIndex.js.map