"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SharedTreeFactory = exports.SharedTree = void 0;
const codec_1 = require("../codec");
const core_1 = require("../core");
const shared_tree_core_1 = require("../shared-tree-core");
const feature_libraries_1 = require("../feature-libraries");
const events_1 = require("../events");
const util_1 = require("../util");
const schematizedTree_1 = require("./schematizedTree");
const sharedTreeView_1 = require("./sharedTreeView");
/**
 * Shared tree, configured with a good set of indexes and field kinds which will maintain compatibility over time.
 *
 * TODO: detail compatibility requirements.
 */
class SharedTree extends shared_tree_core_1.SharedTreeCore {
    constructor(id, runtime, attributes, optionsParam, telemetryContextPrefix) {
        const options = { jsonValidator: codec_1.noopValidator, ...optionsParam };
        const schema = new core_1.InMemoryStoredSchemaRepository(feature_libraries_1.defaultSchemaPolicy);
        const forest = (0, feature_libraries_1.buildForest)(schema, new core_1.AnchorSet());
        const schemaSummarizer = new feature_libraries_1.SchemaSummarizer(runtime, schema, options);
        const forestSummarizer = new feature_libraries_1.ForestSummarizer(forest);
        const changeFamily = new feature_libraries_1.DefaultChangeFamily(options);
        const repairProvider = new feature_libraries_1.ForestRepairDataStoreProvider(forest, schema, (change) => changeFamily.intoDelta(change));
        super([schemaSummarizer, forestSummarizer], changeFamily, forest.anchors, repairProvider, options, id, runtime, attributes, telemetryContextPrefix);
        this.schema = new feature_libraries_1.SchemaEditor(schema, (op) => this.submitLocalMessage(op), options);
        this.nodeKeyIndex = new feature_libraries_1.NodeKeyIndex((0, util_1.brand)(feature_libraries_1.nodeKeyFieldKey));
        this._events = (0, events_1.createEmitter)();
        this.view = (0, sharedTreeView_1.createSharedTreeView)({
            branch: this.getLocalBranch(),
            schema,
            forest,
            repairProvider,
            nodeKeyManager: (0, feature_libraries_1.createNodeKeyManager)(this.runtime.idCompressor),
            nodeKeyIndex: this.nodeKeyIndex,
            events: this._events,
        });
    }
    get events() {
        return this._events;
    }
    get rootEvents() {
        return this.view.rootEvents;
    }
    get storedSchema() {
        return this.schema;
    }
    get forest() {
        return this.view.forest;
    }
    get root() {
        return this.view.root;
    }
    setContent(data) {
        this.view.setContent(data);
    }
    get context() {
        return this.view.context;
    }
    locate(anchor) {
        return this.view.locate(anchor);
    }
    schematize(config) {
        return (0, schematizedTree_1.schematizeView)(this, config);
    }
    get transaction() {
        return this.view.transaction;
    }
    get nodeKey() {
        return this.view.nodeKey;
    }
    fork() {
        return this.view.fork();
    }
    merge(view, disposeView = true) {
        this.view.merge(view, disposeView);
    }
    rebase(fork) {
        fork.rebaseOnto(this.view);
    }
    getLocalBranch() {
        return super.getLocalBranch();
    }
    /**
     * TODO: Shared tree needs a pattern for handling non-changeset operations.
     * Whatever pattern is adopted should probably also handle multiple versions of changeset operations.
     * A single top level enum listing all ops (including their different versions),
     * with at least fine grained enough detail to direct them to the correct subsystem would be a good approach.
     * The current use-case (with an op applying to a specific index) is a temporary hack,
     * and its not clear how it would fit into such a system if implemented in shared-tree-core:
     * maybe op dispatch is part of the shared-tree level?
     */
    processCore(message, local, localOpMetadata) {
        if (!this.schema.tryHandleOp(message)) {
            super.processCore(message, local, localOpMetadata);
        }
    }
    reSubmitCore(content, localOpMetadata) {
        if (!this.schema.tryResubmitOp(content)) {
            super.reSubmitCore(content, localOpMetadata);
        }
    }
    async loadCore(services) {
        await super.loadCore(services);
        // The identifier index must be populated after both the schema and forest have loaded.
        // TODO: Create an ISummarizer for the identifier index and ensure it loads after the other indexes.
        this.nodeKeyIndex.scanKeys(this.context);
        this._events.emit("afterBatch");
    }
}
exports.SharedTree = SharedTree;
/**
 * A channel factory that creates {@link ISharedTree}s.
 * @alpha
 */
class SharedTreeFactory {
    constructor(options = {}) {
        this.options = options;
        this.type = "SharedTree";
        this.attributes = {
            type: this.type,
            snapshotFormatVersion: "0.0.0",
            packageVersion: "0.0.0",
        };
    }
    async load(runtime, id, services, channelAttributes) {
        const tree = new SharedTree(id, runtime, channelAttributes, this.options, "SharedTree");
        await tree.load(services);
        return tree;
    }
    create(runtime, id) {
        const tree = new SharedTree(id, runtime, this.attributes, this.options, "SharedTree");
        tree.initializeLocal();
        return tree;
    }
}
exports.SharedTreeFactory = SharedTreeFactory;
//# sourceMappingURL=sharedTree.js.map