/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { UsageError, } from "@fluidframework/telemetry-utils/internal";
import { noopValidator } from "../codec/index.js";
import { AnchorSet, CommitKind, RevertibleStatus, TreeStoredSchemaRepository, combineVisitors, makeAnonChange, makeDetachedFieldIndex, rebaseChange, tagChange, visitDelta, } from "../core/index.js";
import { createEmitter, } from "../events/index.js";
import { buildForest, intoDelta, jsonableTreeFromCursor, makeFieldBatchCodec, } from "../feature-libraries/index.js";
import { SharedTreeBranch, getChangeReplaceType } from "../shared-tree-core/index.js";
import { TransactionResult, disposeSymbol, fail } from "../util/index.js";
import { SharedTreeChangeFamily, hasSchemaChange } from "./sharedTreeChangeFamily.js";
/**
 * 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(idCompressor, mintRevisionTag, revisionTagCodec, args) {
    const forest = args?.forest ?? buildForest();
    const schema = args?.schema ?? new TreeStoredSchemaRepository();
    const defaultCodecOptions = { jsonValidator: noopValidator };
    const defaultFieldBatchVersion = 1;
    const changeFamily = args?.changeFamily ??
        new SharedTreeChangeFamily(revisionTagCodec, args?.fieldBatchCodec ??
            makeFieldBatchCodec(defaultCodecOptions, defaultFieldBatchVersion), { jsonValidator: noopValidator }, args?.chunkCompressionStrategy);
    const branch = args?.branch ??
        new SharedTreeBranch({
            change: changeFamily.rebaser.compose([]),
            revision: "root",
        }, changeFamily, () => idCompressor.generateCompressedId());
    const events = args?.events ?? createEmitter();
    const transaction = new Transaction(branch);
    return new TreeCheckout(transaction, branch, changeFamily, schema, forest, events, mintRevisionTag, revisionTagCodec, idCompressor, args?.removedRoots, args?.logger);
}
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, mintRevisionTag, revisionTagCodec, idCompressor, removedRoots = makeDetachedFieldIndex("repair", revisionTagCodec, idCompressor), 
    /** Optional logger for telemetry. */
    logger) {
        this.transaction = transaction;
        this.branch = branch;
        this.changeFamily = changeFamily;
        this.storedSchema = storedSchema;
        this.forest = forest;
        this.events = events;
        this.mintRevisionTag = mintRevisionTag;
        this.revisionTagCodec = revisionTagCodec;
        this.idCompressor = idCompressor;
        this.removedRoots = removedRoots;
        this.logger = logger;
        this.isDisposed = false;
        /**
         * Set of revertibles maintained for automatic disposal
         */
        this.revertibles = new Set();
        /**
         * Each branch's head commit corresponds to a revertible commit.
         * Maintaining a whole branch ensures the commit graph is not pruned in a way that would prevent the commit from
         * being reverted.
         */
        this.revertibleCommitBranches = new Map();
        // 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) {
                // Conflicts due to schema will be empty and thus are not applied.
                for (const change of event.change.change.changes) {
                    if (change.type === "data") {
                        const delta = intoDelta(tagChange(change.innerChange, event.change.revision));
                        this.withCombinedVisitor((visitor) => {
                            visitDelta(delta, visitor, this.removedRoots);
                        });
                    }
                    else if (change.type === "schema") {
                        // Schema changes from a current to a new schema are expected to be backwards compatible.
                        // This guarantees that all data in the forest (which is valid before the schema change)
                        // is also valid under the new schema.
                        // Note however, that such schema changes may in some cases be rolled back:
                        // Case 1: A transaction with a schema change may be aborted.
                        // The transaction may have made some data changes that would render some trees invalid
                        // under the old schema, but these changes will also be rolled back, thereby putting the forest
                        // back in the state before the transaction, which is valid under the original (reinstated) schema.
                        // Case 2: A branch with a schema change may be rebased such that the schema change (because
                        // of a constraint) is no longer applied.
                        // Such a branch may contain data changes that would render some trees invalid under the
                        // original schema. These data changes may not necessarily be rolled back.
                        // They will however be rebased over the rollback of the schema change. This rebasing will
                        // ensure that these data changes are muted if they would render some trees invalid under the
                        // original (reinstated) schema.
                        storedSchema.apply(change.innerChange.schema.new);
                    }
                    else {
                        fail("Unknown Shared Tree change type.");
                    }
                }
                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("commitApplied", (data) => {
            const commit = branch.getHead();
            const { change, revision } = commit;
            let withinEventContext = true;
            const getRevertible = hasSchemaChange(change)
                ? undefined
                : (onRevertibleDisposed) => {
                    if (!withinEventContext) {
                        throw new UsageError("Cannot get a revertible outside of the context of a commitApplied event.");
                    }
                    if (this.revertibleCommitBranches.get(revision) !== undefined) {
                        throw new UsageError("Cannot generate the same revertible more than once. Note that this can happen when multiple commitApplied event listeners are registered.");
                    }
                    const revertibleCommits = this.revertibleCommitBranches;
                    const revertible = {
                        get status() {
                            const revertibleCommit = revertibleCommits.get(revision);
                            return revertibleCommit === undefined
                                ? RevertibleStatus.Disposed
                                : RevertibleStatus.Valid;
                        },
                        revert: (release = true) => {
                            if (revertible.status === RevertibleStatus.Disposed) {
                                throw new UsageError("Unable to revert a revertible that has been disposed.");
                            }
                            const revertMetrics = this.revertRevertible(revision, data.kind);
                            this.logger?.sendTelemetryEvent({
                                eventName: TreeCheckout.revertTelemetryEventName,
                                ...revertMetrics,
                            });
                            if (release) {
                                revertible.dispose();
                            }
                        },
                        dispose: () => {
                            if (revertible.status === RevertibleStatus.Disposed) {
                                throw new UsageError("Unable to dispose a revertible that has already been disposed.");
                            }
                            this.disposeRevertible(revertible, revision);
                            onRevertibleDisposed?.(revertible);
                        },
                    };
                    this.revertibleCommitBranches.set(revision, branch.fork());
                    this.revertibles.add(revertible);
                    return revertible;
                };
            this.events.emit("commitApplied", data, getRevertible);
            withinEventContext = false;
        });
    }
    withCombinedVisitor(fn) {
        const anchorVisitor = this.forest.anchors.acquireVisitor();
        const combinedVisitor = combineVisitors([this.forest.acquireVisitor(), anchorVisitor], [anchorVisitor]);
        fn(combinedVisitor);
        combinedVisitor.free();
    }
    checkNotDisposed() {
        assert(!this.isDisposed, 0x911 /* Invalid operation on a disposed TreeCheckout */);
    }
    get rootEvents() {
        return this.forest.anchors;
    }
    get editor() {
        this.checkNotDisposed();
        return this.branch.editor;
    }
    locate(anchor) {
        this.checkNotDisposed();
        return this.forest.anchors.locate(anchor);
    }
    fork() {
        this.checkNotDisposed();
        const anchors = new AnchorSet();
        const branch = this.branch.fork();
        const storedSchema = this.storedSchema.clone();
        const forest = this.forest.clone(storedSchema, anchors);
        const transaction = new Transaction(branch);
        return new TreeCheckout(transaction, branch, this.changeFamily, storedSchema, forest, createEmitter(), this.mintRevisionTag, this.revisionTagCodec, this.idCompressor, this.removedRoots.clone(), this.logger);
    }
    rebase(view) {
        this.checkNotDisposed();
        view.branch.rebaseOnto(this.branch);
    }
    rebaseOnto(view) {
        this.checkNotDisposed();
        view.rebase(this);
    }
    merge(view, disposeView = true) {
        this.checkNotDisposed();
        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[disposeSymbol]();
        }
    }
    updateSchema(newSchema) {
        this.checkNotDisposed();
        this.editor.schema.setStoredSchema(this.storedSchema.clone(), newSchema);
    }
    [disposeSymbol]() {
        this.checkNotDisposed();
        this.isDisposed = true;
        this.purgeRevertibles();
        this.branch.dispose();
    }
    getRemovedRoots() {
        const trees = [];
        const cursor = this.forest.allocateCursor("getRemovedRoots");
        for (const { id, root } of this.removedRoots.entries()) {
            const parentField = this.removedRoots.toFieldKey(root);
            this.forest.moveCursorToPath({ parent: undefined, parentField, parentIndex: 0 }, cursor);
            const tree = jsonableTreeFromCursor(cursor);
            // This method is used for tree consistency comparison.
            const { major, minor } = id;
            const finalizedMajor = major !== undefined ? this.revisionTagCodec.encode(major) : major;
            trees.push([finalizedMajor, minor, tree]);
        }
        cursor.free();
        return trees;
    }
    purgeRevertibles() {
        for (const revertible of this.revertibles) {
            revertible.dispose();
        }
    }
    disposeRevertible(revertible, revision) {
        this.revertibleCommitBranches.get(revision)?.dispose();
        this.revertibleCommitBranches.delete(revision);
        this.revertibles.delete(revertible);
    }
    revertRevertible(revision, kind) {
        if (this.branch.isTransacting()) {
            throw new UsageError("Undo is not yet supported during transactions.");
        }
        const revertibleBranch = this.revertibleCommitBranches.get(revision);
        assert(revertibleBranch !== undefined, 0x7cc /* expected to find a revertible commit */);
        const commitToRevert = revertibleBranch.getHead();
        let change = makeAnonChange(this.changeFamily.rebaser.invert(tagChange(commitToRevert.change, revision), false));
        const headCommit = this.branch.getHead();
        // Rebase the inverted change onto any commits that occurred after the undoable commits.
        if (commitToRevert !== headCommit) {
            change = makeAnonChange(rebaseChange(this.changeFamily.rebaser, change, commitToRevert, headCommit, this.mintRevisionTag).change);
        }
        this.branch.apply(change.change, this.mintRevisionTag(), kind === CommitKind.Default || kind === CommitKind.Redo
            ? CommitKind.Undo
            : CommitKind.Redo);
        // Derive some stats about the reversion to return to the caller.
        let revertAge = 0;
        let currentCommit = headCommit;
        while (commitToRevert.revision !== currentCommit.revision) {
            revertAge++;
            const parentCommit = currentCommit.parent;
            assert(parentCommit !== undefined, 0x9a9 /* expected to find a parent commit */);
            currentCommit = parentCommit;
        }
        return { age: revertAge };
    }
}
/**
 * The name of the telemetry event logged for calls to {@link TreeCheckout.revertRevertible}.
 * @privateRemarks Exposed for testing purposes.
 */
TreeCheckout.revertTelemetryEventName = "RevertRevertible";
/**
 * 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
 * @internal
 */
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