"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.defaultSharedTreeOptions = exports.ForestType = 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 = { ...exports.defaultSharedTreeOptions, ...optionsParam };
        const schema = new core_1.InMemoryStoredSchemaRepository();
        const forest = options.forest === ForestType.Optimized
            ? (0, feature_libraries_1.buildChunkedForest)((0, feature_libraries_1.makeTreeChunker)(schema, feature_libraries_1.defaultSchemaPolicy))
            : (0, feature_libraries_1.buildForest)();
        const removedTrees = (0, core_1.makeDetachedFieldIndex)("repair");
        const schemaSummarizer = new feature_libraries_1.SchemaSummarizer(runtime, schema, options);
        const forestSummarizer = new feature_libraries_1.ForestSummarizer(forest);
        const removedTreesSummarizer = new feature_libraries_1.DetachedFieldIndexSummarizer(removedTrees);
        const changeFamily = new feature_libraries_1.DefaultChangeFamily(options);
        super([schemaSummarizer, forestSummarizer, removedTreesSummarizer], changeFamily, options, id, runtime, attributes, telemetryContextPrefix);
        this.storedSchema = new feature_libraries_1.SchemaEditor(schema, (op) => this.submitLocalMessage(op), options);
        this._events = (0, events_1.createEmitter)();
        this.view = (0, sharedTreeView_1.createSharedTreeView)({
            branch: this.getLocalBranch(),
            // TODO:
            // This passes in a version of schema thats not wrapped with the editor.
            // This allows editing schema on the view without sending ops, which is incorrect behavior.
            schema,
            forest,
            events: this._events,
            removedTrees,
        });
    }
    contentSnapshot() {
        const cursor = this.view.forest.allocateCursor();
        try {
            (0, core_1.moveToDetachedField)(this.view.forest, cursor);
            return {
                schema: new core_1.InMemoryStoredSchemaRepository(this.storedSchema),
                tree: (0, feature_libraries_1.jsonableTreeFromFieldCursor)(cursor),
            };
        }
        finally {
            cursor.free();
        }
    }
    schematizeView(config) {
        // TODO:
        // When this becomes a more proper out of schema adapter, editing should be made lazy.
        // This will improve support for readonly documents, cross version collaboration and attribution.
        // Check for empty.
        if (this.view.forest.isEmpty && (0, core_1.schemaDataIsEmpty)(this.storedSchema)) {
            this.view.transaction.start();
            (0, schematizedTree_1.initializeContent)(this.storedSchema, config.schema, () => this.view.setContent(config.initialTree));
            this.view.transaction.commit();
        }
        (0, schematizedTree_1.schematize)(this.view.events, this.storedSchema, config);
        return this.view;
    }
    schematize(config) {
        const nodeKeyManager = (0, feature_libraries_1.createNodeKeyManager)(this.runtime.idCompressor);
        const view = this.schematizeView(config);
        return view.editableTree2(config.schema, nodeKeyManager, (0, util_1.brand)(feature_libraries_1.nodeKeyFieldKey));
    }
    /**
     * 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) {
        // TODO: Get rid of this `as any`. There should be a better way to narrow the type of message.contents.
        if (!this.storedSchema.tryHandleOp(message.contents)) {
            super.processCore(message, local, localOpMetadata);
        }
    }
    reSubmitCore(content, localOpMetadata) {
        if (!this.storedSchema.tryResubmitOp(content)) {
            super.reSubmitCore(content, localOpMetadata);
        }
    }
    applyStashedOp(content) {
        if (!this.storedSchema.tryApplyStashedOp(content)) {
            return super.applyStashedOp(content);
        }
    }
    async loadCore(services) {
        await super.loadCore(services);
        this._events.emit("afterBatch");
    }
}
exports.SharedTree = SharedTree;
/**
 * Used to distinguish between different forest types.
 * @alpha
 */
var ForestType;
(function (ForestType) {
    /**
     * The "ObjectForest" forest type.
     */
    ForestType[ForestType["Reference"] = 0] = "Reference";
    /**
     * The "ChunkedForest" forest type.
     */
    ForestType[ForestType["Optimized"] = 1] = "Optimized";
})(ForestType || (exports.ForestType = ForestType = {}));
exports.defaultSharedTreeOptions = {
    jsonValidator: codec_1.noopValidator,
    forest: ForestType.Reference,
};
/**
 * A channel factory that creates {@link ISharedTree}s.
 * @alpha
 */
class SharedTreeFactory {
    constructor(options = {}) {
        this.options = options;
        this.type = "https://graph.microsoft.com/types/tree";
        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