/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { AnchorSet, InMemoryStoredSchemaRepository, assertIsRevisionTag, combineVisitors, visitDelta, makeDetachedFieldIndex, } from "../core";
import { createEmitter } from "../events";
import { buildForest, DefaultChangeFamily, intoDelta, } from "../feature-libraries";
import { SharedTreeBranch, getChangeReplaceType } from "../shared-tree-core";
import { TransactionResult } from "../util";
import { noopValidator } from "../codec";
/**
 * Creates a {@link TreeCheckout}.
 * @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 ITreeCheckout}.
 */
export function createTreeCheckout(args) {
    const schema = args?.schema ?? new InMemoryStoredSchemaRepository();
    const forest = args?.forest ?? buildForest();
    const changeFamily = args?.changeFamily ?? new DefaultChangeFamily({ jsonValidator: noopValidator });
    const branch = args?.branch ??
        new SharedTreeBranch({
            change: changeFamily.rebaser.compose([]),
            revision: assertIsRevisionTag("00000000-0000-4000-8000-000000000000"),
        }, changeFamily);
    const events = args?.events ?? createEmitter();
    const transaction = new Transaction(branch);
    return new TreeCheckout(transaction, branch, changeFamily, schema, forest, events, args?.removedRoots);
}
class Transaction {
    constructor(branch) {
        this.branch = branch;
    }
    start() {
        this.branch.startTransaction();
        this.branch.editor.enterTransaction();
    }
    commit() {
        this.branch.commitTransaction();
        this.branch.editor.exitTransaction();
        return TransactionResult.Commit;
    }
    abort() {
        this.branch.abortTransaction();
        this.branch.editor.exitTransaction();
        return TransactionResult.Abort;
    }
    inProgress() {
        return this.branch.isTransacting();
    }
}
/**
 * An implementation of {@link ITreeCheckoutFork}.
 */
export class TreeCheckout {
    constructor(transaction, branch, changeFamily, storedSchema, forest, events, removedRoots = makeDetachedFieldIndex("repair")) {
        this.transaction = transaction;
        this.branch = branch;
        this.changeFamily = changeFamily;
        this.storedSchema = storedSchema;
        this.forest = forest;
        this.events = events;
        this.removedRoots = removedRoots;
        // We subscribe to `beforeChange` rather than `afterChange` here because it's possible that the change is invalid WRT our forest.
        // For example, a bug in the editor might produce a malformed change object and thus applying the change to the forest will throw an error.
        // In such a case we will crash here, preventing the change from being added to the commit graph, and preventing `afterChange` from firing.
        // One important consequence of this is that we will not submit the op containing the invalid change, since op submissions happens in response to `afterChange`.
        branch.on("beforeChange", (event) => {
            if (event.change !== undefined) {
                const delta = intoDelta(event.change);
                const anchorVisitor = this.forest.anchors.acquireVisitor();
                const combinedVisitor = combineVisitors([this.forest.acquireVisitor(), anchorVisitor], [anchorVisitor]);
                visitDelta(delta, combinedVisitor, this.removedRoots);
                combinedVisitor.free();
                this.events.emit("afterBatch");
            }
            if (event.type === "replace" && getChangeReplaceType(event) === "transactionCommit") {
                const transactionRevision = event.newCommits[0].revision;
                for (const transactionStep of event.removedCommits) {
                    this.removedRoots.updateMajor(transactionStep.revision, transactionRevision);
                }
            }
        });
        branch.on("revertible", (revertible) => {
            // if there are no listeners, discard the revertible to avoid memory leaks
            if (!this.events.hasListeners("revertible")) {
                revertible.discard();
            }
            else {
                this.events.emit("revertible", revertible);
            }
        });
    }
    get rootEvents() {
        return this.forest.anchors;
    }
    get editor() {
        return this.branch.editor;
    }
    locate(anchor) {
        return this.forest.anchors.locate(anchor);
    }
    fork() {
        const anchors = new AnchorSet();
        // TODO: ensure editing this clone of the schema does the right thing.
        const storedSchema = new InMemoryStoredSchemaRepository(this.storedSchema);
        const forest = this.forest.clone(storedSchema, anchors);
        const branch = this.branch.fork();
        const transaction = new Transaction(branch);
        return new TreeCheckout(transaction, branch, this.changeFamily, storedSchema, forest, createEmitter(), this.removedRoots.clone());
    }
    rebase(view) {
        view.branch.rebaseOnto(this.branch);
    }
    rebaseOnto(view) {
        view.rebase(this);
    }
    merge(view, disposeView = true) {
        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();
        }
    }
    /**
     * 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();
    }
}
/**
 * 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
 */
export function runSynchronous(view, transaction) {
    view.transaction.start();
    const result = transaction(view);
    return result === TransactionResult.Abort
        ? view.transaction.abort()
        : view.transaction.commit();
}
//# sourceMappingURL=treeCheckout.js.map