"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runSynchronous = exports.SharedTreeView = exports.createSharedTreeView = exports.create = void 0;
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
const common_utils_1 = require("@fluidframework/common-utils");
const core_1 = require("../core");
const events_1 = require("../events");
const feature_libraries_1 = require("../feature-libraries");
const shared_tree_core_1 = require("../shared-tree-core");
const util_1 = require("../util");
const codec_1 = require("../codec");
const schematizedTree_1 = require("./schematizedTree");
/**
 * Used as a static property to access the creation function for a {@link SharedTreeView}.
 */
exports.create = Symbol("Create SharedTreeView");
/**
 * Creates a {@link SharedTreeView}.
 * @param args - an object containing optional components that will be used to build the view.
 * Any components not provided will be created by default.
 * @remarks This does not create a {@link SharedTree}, but rather a view with the minimal state
 * and functionality required to implement {@link ISharedTreeView}.
 */
function createSharedTreeView(args) {
    const schema = args?.schema ?? new core_1.InMemoryStoredSchemaRepository(feature_libraries_1.defaultSchemaPolicy);
    const forest = args?.forest ?? (0, feature_libraries_1.buildForest)(schema, new core_1.AnchorSet());
    const changeFamily = args?.changeFamily ?? new feature_libraries_1.DefaultChangeFamily({ jsonValidator: codec_1.noopValidator });
    const repairDataStoreProvider = args?.repairProvider ??
        new feature_libraries_1.ForestRepairDataStoreProvider(forest, schema, (change) => changeFamily.intoDelta(change));
    const undoRedoManager = core_1.UndoRedoManager.create(changeFamily);
    const branch = args?.branch ??
        new shared_tree_core_1.SharedTreeBranch({
            change: changeFamily.rebaser.compose([]),
            revision: (0, core_1.assertIsRevisionTag)("00000000-0000-4000-8000-000000000000"),
        }, changeFamily, repairDataStoreProvider, undoRedoManager, forest.anchors);
    const nodeKeyManager = args?.nodeKeyManager ?? (0, feature_libraries_1.createNodeKeyManager)();
    const context = (0, feature_libraries_1.getEditableTreeContext)(forest, branch.editor, nodeKeyManager, (0, util_1.brand)(feature_libraries_1.nodeKeyFieldKey));
    const nodeKeyIndex = args?.nodeKeyIndex ?? new feature_libraries_1.NodeKeyIndex((0, util_1.brand)(feature_libraries_1.nodeKeyFieldKey));
    const events = args?.events ?? (0, events_1.createEmitter)();
    return SharedTreeView[exports.create](branch, changeFamily, schema, forest, context, nodeKeyManager, nodeKeyIndex, events);
}
exports.createSharedTreeView = createSharedTreeView;
/**
 * An implementation of {@link ISharedTreeView}.
 * @alpha
 */
class SharedTreeView {
    constructor(branch, changeFamily, _storedSchema, _forest, context, _nodeKeyManager, _nodeKeyIndex, _events) {
        this.branch = branch;
        this.changeFamily = changeFamily;
        this._storedSchema = _storedSchema;
        this._forest = _forest;
        this.context = context;
        this._nodeKeyManager = _nodeKeyManager;
        this._nodeKeyIndex = _nodeKeyIndex;
        this._events = _events;
        this.transaction = {
            start: () => {
                this.branch.startTransaction(new feature_libraries_1.ForestRepairDataStore(this.forest, (change) => this.changeFamily.intoDelta(change)));
                this.branch.editor.enterTransaction();
            },
            commit: () => {
                this.branch.commitTransaction();
                this.branch.editor.exitTransaction();
                return util_1.TransactionResult.Commit;
            },
            abort: () => {
                this.branch.abortTransaction();
                this.branch.editor.exitTransaction();
                return util_1.TransactionResult.Abort;
            },
            inProgress: () => this.branch.isTransacting(),
        };
        this.nodeKey = {
            generate: () => this._nodeKeyManager.generateLocalNodeKey(),
            stabilize: (key) => this._nodeKeyManager.stabilizeNodeKey(key),
            localize: (key) => this._nodeKeyManager.localizeNodeKey(key),
            map: this._nodeKeyIndex,
        };
        branch.on("change", ({ change }) => {
            if (change !== undefined) {
                const delta = this.changeFamily.intoDelta(change);
                this._forest.applyDelta(delta);
                this._nodeKeyIndex.scanKeys(this.context);
                this._events.emit("afterBatch");
            }
        });
        branch.on("revertible", (type) => {
            this._events.emit("revertible", type);
        });
    }
    // SharedTreeView is a public type, but its instantiation is internal
    static [exports.create](branch, changeFamily, storedSchema, forest, context, _nodeKeyManager, nodeKeyIndex, events) {
        return new SharedTreeView(branch, changeFamily, storedSchema, forest, context, _nodeKeyManager, nodeKeyIndex, events);
    }
    get events() {
        return this._events;
    }
    get storedSchema() {
        return this._storedSchema;
    }
    get forest() {
        return this._forest;
    }
    get rootEvents() {
        return this._forest.anchors;
    }
    get editor() {
        return this.branch.editor;
    }
    undo() {
        this.branch.undo();
    }
    redo() {
        this.branch.redo();
    }
    schematize(config) {
        return (0, schematizedTree_1.schematizeView)(this, config);
    }
    locate(anchor) {
        return this._forest.anchors.locate(anchor);
    }
    fork() {
        const anchors = new core_1.AnchorSet();
        const storedSchema = this._storedSchema.clone();
        const forest = this._forest.clone(storedSchema, anchors);
        const repairDataStoreProvider = new feature_libraries_1.ForestRepairDataStoreProvider(forest, storedSchema, (change) => this.changeFamily.intoDelta(change));
        const branch = this.branch.fork(repairDataStoreProvider, anchors);
        const context = (0, feature_libraries_1.getEditableTreeContext)(forest, branch.editor, this._nodeKeyManager, this._nodeKeyIndex.fieldKey);
        return new SharedTreeView(branch, this.changeFamily, storedSchema, forest, context, this._nodeKeyManager, this._nodeKeyIndex.clone(context), (0, events_1.createEmitter)());
    }
    rebase(view) {
        view.branch.rebaseOnto(this.branch);
    }
    /**
     * Rebase the changes that have been applied to this view over all the new changes in the given view.
     * @param view - Either the root view or a view that was created by a call to `fork()`. It is not modified by this operation.
     */
    rebaseOnto(view) {
        view.rebase(this);
    }
    merge(view, disposeView = true) {
        (0, common_utils_1.assert)(!this.transaction.inProgress() || disposeView, 0x710 /* A view that is merged into an in-progress transaction must be disposed */);
        while (view.transaction.inProgress()) {
            view.transaction.commit();
        }
        this.branch.merge(view.branch);
        if (disposeView) {
            view.dispose();
        }
    }
    get root() {
        return this.context.unwrappedRoot;
    }
    setContent(data) {
        this.context.setContent(data);
    }
    /**
     * Dispose this view, freezing its state and allowing the SharedTree to release resources required by it.
     * Attempts to further mutate or dispose this view will error.
     */
    dispose() {
        this.branch.dispose();
    }
}
exports.SharedTreeView = SharedTreeView;
/**
 * Run a synchronous transaction on the given shared tree view.
 * This is a convenience helper around the {@link SharedTreeFork#transaction} APIs.
 * @param view - the view on which to run the transaction
 * @param transaction - the transaction function. This will be executed immediately. It is passed `view` as an argument for convenience.
 * If this function returns an `Abort` result then the transaction will be aborted. Otherwise, it will be committed.
 * @returns whether or not the transaction was committed or aborted
 * @alpha
 */
function runSynchronous(view, transaction) {
    view.transaction.start();
    const result = transaction(view);
    return result === util_1.TransactionResult.Abort
        ? view.transaction.abort()
        : view.transaction.commit();
}
exports.runSynchronous = runSynchronous;
//# sourceMappingURL=sharedTreeView.js.map