/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { noopValidator } from "../codec";
import { InMemoryStoredSchemaRepository, AnchorSet, } from "../core";
import { SharedTreeCore } from "../shared-tree-core";
import { defaultSchemaPolicy, ForestSummarizer, SchemaSummarizer as SchemaSummarizer, DefaultChangeFamily, buildForest, ForestRepairDataStoreProvider, SchemaEditor, NodeKeyIndex, createNodeKeyManager, nodeKeyFieldKey, } from "../feature-libraries";
import { createEmitter } from "../events";
import { brand } from "../util";
import { schematizeView } from "./schematizedTree";
import { createSharedTreeView, } from "./sharedTreeView";
/**
 * Shared tree, configured with a good set of indexes and field kinds which will maintain compatibility over time.
 *
 * TODO: detail compatibility requirements.
 */
export class SharedTree extends SharedTreeCore {
    constructor(id, runtime, attributes, optionsParam, telemetryContextPrefix) {
        const options = { jsonValidator: noopValidator, ...optionsParam };
        const schema = new InMemoryStoredSchemaRepository(defaultSchemaPolicy);
        const forest = buildForest(schema, new AnchorSet());
        const schemaSummarizer = new SchemaSummarizer(runtime, schema, options);
        const forestSummarizer = new ForestSummarizer(forest);
        const changeFamily = new DefaultChangeFamily(options);
        const repairProvider = new ForestRepairDataStoreProvider(forest, schema, (change) => changeFamily.intoDelta(change));
        super([schemaSummarizer, forestSummarizer], changeFamily, forest.anchors, repairProvider, options, id, runtime, attributes, telemetryContextPrefix);
        this.schema = new SchemaEditor(schema, (op) => this.submitLocalMessage(op), options);
        this.nodeKeyIndex = new NodeKeyIndex(brand(nodeKeyFieldKey));
        this._events = createEmitter();
        this.view = createSharedTreeView({
            branch: this.getLocalBranch(),
            schema,
            forest,
            repairProvider,
            nodeKeyManager: 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 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");
    }
}
/**
 * A channel factory that creates {@link ISharedTree}s.
 * @alpha
 */
export 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;
    }
}
//# sourceMappingURL=sharedTree.js.map