"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildForest = exports.ObjectForest = void 0;
const core_utils_1 = require("@fluidframework/core-utils");
const core_1 = require("../../core");
const util_1 = require("../../util");
const treeCursorUtils_1 = require("../treeCursorUtils");
const mapTreeCursor_1 = require("../mapTreeCursor");
const events_1 = require("../../events");
function makeRoot() {
    return {
        type: core_1.aboveRootPlaceholder,
        fields: new Map(),
    };
}
/**
 * Reference implementation of IEditableForest.
 *
 * This implementation focuses on correctness and simplicity, not performance.
 * It does not use compressed chunks: instead nodes are implemented using objects.
 */
class ObjectForest {
    constructor(anchors = new core_1.AnchorSet()) {
        this.anchors = anchors;
        this.roots = makeRoot();
        // All cursors that are in the "Current" state. Must be empty when editing.
        this.currentCursors = new Set();
        this.events = (0, events_1.createEmitter)();
        this.nextRange = 0;
    }
    get isEmpty() {
        return this.roots.fields.size === 0;
    }
    on(eventName, listener) {
        return this.events.on(eventName, listener);
    }
    clone(schema, anchors) {
        const forest = new ObjectForest(anchors);
        // Deep copy the trees.
        for (const [key, value] of this.roots.fields) {
            // TODO: this references the existing TreeValues instead of copying them:
            // they are assumed to be copy on write. See TODO on NodeData.
            forest.roots.fields.set(key, value.map((v) => (0, mapTreeCursor_1.mapTreeFromCursor)((0, mapTreeCursor_1.cursorForMapTreeNode)(v))));
        }
        return forest;
    }
    forgetAnchor(anchor) {
        this.anchors.forget(anchor);
    }
    acquireVisitor() {
        (0, core_utils_1.assert)(this.activeVisitor === undefined, 0x76c /* Must release existing visitor before acquiring another */);
        this.events.emit("beforeChange");
        (0, core_utils_1.assert)(this.currentCursors.size === 0, 0x374 /* No cursors can be current when modifying forest */);
        // Note: This code uses cursors, however it also modifies the tree.
        // In general this is not safe, but this code happens to only modify the tree below the current cursor location,
        // which happens to work.
        // This pattern could be generalized/formalized with a concept of an exclusive cursor,
        // which can edit, but is the only cursor allowed at the time.
        const cursor = this.allocateCursor();
        cursor.setToAboveDetachedSequences();
        const visitor = {
            forest: this,
            cursor,
            free() {
                this.cursor.free();
                (0, core_utils_1.assert)(this.forest.activeVisitor !== undefined, 0x76d /* Multiple free calls for same visitor */);
                this.forest.activeVisitor = undefined;
                this.forest.events.emit("afterChange");
            },
            destroy(detachedField, count) {
                this.forest.delete(detachedField);
            },
            create(content, destination) {
                this.forest.add(content, destination);
            },
            attach(source, count, destination) {
                this.attachEdit(source, count, destination);
            },
            detach(source, destination) {
                this.detachEdit(source, destination);
            },
            /**
             * Attaches the nodes from the given source field into the current field.
             * Does not invalidate dependents.
             * @param source - The the range to be attached.
             * @param count - The number of nodes being attached.
             * Expected to match the number of nodes in the source detached field.
             * @param destination - The index in the current field at which to attach the content.
             */
            attachEdit(source, count, destination) {
                (0, util_1.assertNonNegativeSafeInteger)(count);
                if (count === 0) {
                    return;
                }
                const [parent, key] = cursor.getParent();
                (0, core_utils_1.assert)(parent !== this.forest.roots || key !== source, 0x7b6 /* Attach source field must be different from current field */);
                const currentField = (0, core_1.getMapTreeField)(parent, key, true);
                (0, util_1.assertValidIndex)(destination, currentField, true);
                const sourceField = (0, core_1.getMapTreeField)(this.forest.roots, source, false);
                (0, core_utils_1.assert)(sourceField !== undefined, 0x7b7 /* Attach source field must exist */);
                (0, core_utils_1.assert)(sourceField.length === count, 0x7b8 /* Attach must consume all nodes in source field */);
                // TODO: this will fail for very large insertions due to argument limits.
                currentField.splice(destination, 0, ...sourceField);
                this.forest.delete(source);
            },
            /**
             * Detaches the range from the current field and transfers it to the given destination if any.
             * Does not invalidate dependents.
             * @param source - The bounds of the range to be detached from the current field.
             * @param destination - If specified, the destination to transfer the detached range to.
             * If not specified, the detached range is destroyed.
             */
            detachEdit(source, destination) {
                const [parent, key] = cursor.getParent();
                (0, core_utils_1.assert)(destination === undefined ||
                    parent !== this.forest.roots ||
                    key !== destination, 0x7b9 /* Detach destination field must be different from current field */);
                const currentField = (0, core_1.getMapTreeField)(parent, key, true);
                (0, util_1.assertValidRange)(source, currentField);
                const content = currentField.splice(source.start, source.end - source.start);
                if (destination !== undefined) {
                    this.forest.addFieldAsDetached(content, destination);
                }
                // This check is performed after the transfer to ensure that the field is not removed in scenarios
                // where the source and destination are the same.
                if (currentField.length === 0) {
                    parent.fields.delete(key);
                }
            },
            replace(newContentSource, range, oldContentDestination) {
                (0, core_utils_1.assert)(newContentSource !== oldContentDestination, 0x7ba /* Replace detached source field and detached destination field must be different */);
                this.detachEdit(range, oldContentDestination);
                this.attachEdit(newContentSource, range.end - range.start, range.start);
            },
            enterNode(index) {
                this.cursor.enterNode(index);
            },
            exitNode(index) {
                this.cursor.exitNode();
            },
            enterField(key) {
                this.cursor.enterField(key);
            },
            exitField(key) {
                this.cursor.exitField();
            },
        };
        this.activeVisitor = visitor;
        return visitor;
    }
    newDetachedField() {
        const range = (0, util_1.brand)(String(this.nextRange));
        this.nextRange += 1;
        return range;
    }
    add(nodes, key) {
        const field = Array.from(nodes, mapTreeCursor_1.mapTreeFromCursor);
        this.addFieldAsDetached(field, key);
    }
    addFieldAsDetached(field, key) {
        (0, core_utils_1.assert)(!this.roots.fields.has(key), 0x370 /* new range must not already exist */);
        if (field.length > 0) {
            this.roots.fields.set(key, field);
        }
    }
    delete(field) {
        this.roots.fields.delete(field);
    }
    allocateCursor() {
        return new Cursor(this);
    }
    tryMoveCursorToNode(destination, cursorToMove) {
        const path = this.anchors.locate(destination);
        if (path === undefined) {
            return -1 /* TreeNavigationResult.NotFound */;
        }
        this.moveCursorToPath(path, cursorToMove);
        return 1 /* TreeNavigationResult.Ok */;
    }
    tryMoveCursorToField(destination, cursorToMove) {
        if (destination.parent === undefined) {
            this.moveCursorToPath(undefined, cursorToMove);
        }
        else {
            const result = this.tryMoveCursorToNode(destination.parent, cursorToMove);
            if (result !== 1 /* TreeNavigationResult.Ok */) {
                return result;
            }
        }
        cursorToMove.enterField(destination.fieldKey);
        return 1 /* TreeNavigationResult.Ok */;
    }
    moveCursorToPath(destination, cursorToMove) {
        (0, core_utils_1.assert)(cursorToMove instanceof Cursor, 0x337 /* ObjectForest must only be given its own Cursor type */);
        (0, core_utils_1.assert)(cursorToMove.forest === this, 0x338 /* ObjectForest must only be given its own Cursor */);
        const indexStack = [];
        const keyStack = [];
        let path = destination;
        while (path !== undefined) {
            indexStack.push(path.parentIndex);
            keyStack.push(path.parentField);
            path = path.parent;
        }
        cursorToMove.setToAboveDetachedSequences();
        while (keyStack.length > 0) {
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            cursorToMove.enterField(keyStack.pop());
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            cursorToMove.enterNode(indexStack.pop());
        }
        return;
    }
    getCursorAboveDetachedFields() {
        return (0, mapTreeCursor_1.cursorForMapTreeNode)(this.roots);
    }
}
exports.ObjectForest = ObjectForest;
/**
 * Cursor implementation for ObjectForest.
 */
class Cursor extends treeCursorUtils_1.SynchronousCursor {
    /**
     * @param forest - forest this cursor navigates
     * @param innerCursor - underlying cursor implementation this wraps. `undefined` when state is not `Current`
     */
    constructor(forest, innerCursor) {
        super();
        this.forest = forest;
        this.innerCursor = innerCursor;
        if (innerCursor === undefined) {
            this.state = core_1.ITreeSubscriptionCursorState.Cleared;
        }
        else {
            this.state = core_1.ITreeSubscriptionCursorState.Current;
            this.forest.currentCursors.add(this);
        }
    }
    buildFieldAnchor() {
        const path = this.getFieldPath();
        const anchor = path.parent === undefined ? undefined : this.forest.anchors.track(path.parent);
        return { parent: anchor, fieldKey: path.field };
    }
    getFieldPath(prefix) {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x45f /* Cursor must be current to be used */);
        return this.innerCursor.getFieldPath(prefix);
    }
    get mode() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x42e /* Cursor must be current to be used */);
        return this.innerCursor.mode;
    }
    nextField() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x42f /* Cursor must be current to be used */);
        return this.innerCursor.nextField();
    }
    exitField() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x430 /* Cursor must be current to be used */);
        return this.innerCursor.exitField();
    }
    skipPendingFields() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x431 /* Cursor must be current to be used */);
        return this.innerCursor.skipPendingFields();
    }
    getFieldKey() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x432 /* Cursor must be current to be used */);
        return this.innerCursor.getFieldKey();
    }
    getFieldLength() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x433 /* Cursor must be current to be used */);
        return this.innerCursor.getFieldLength();
    }
    firstNode() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x434 /* Cursor must be current to be used */);
        return this.innerCursor.firstNode();
    }
    enterNode(childIndex) {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x435 /* Cursor must be current to be used */);
        return this.innerCursor.enterNode(childIndex);
    }
    getPath(prefix) {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x436 /* Cursor must be current to be used */);
        return this.innerCursor.getPath(prefix) ?? (0, util_1.fail)("no path when at root");
    }
    get fieldIndex() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x437 /* Cursor must be current to be used */);
        return this.innerCursor.fieldIndex;
    }
    get chunkStart() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x438 /* Cursor must be current to be used */);
        return this.innerCursor.chunkStart;
    }
    get chunkLength() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x439 /* Cursor must be current to be used */);
        return this.innerCursor.chunkLength;
    }
    seekNodes(offset) {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43a /* Cursor must be current to be used */);
        return this.innerCursor.seekNodes(offset);
    }
    nextNode() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43b /* Cursor must be current to be used */);
        return this.innerCursor.nextNode();
    }
    exitNode() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43c /* Cursor must be current to be used */);
        return this.innerCursor.exitNode();
    }
    firstField() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43d /* Cursor must be current to be used */);
        return this.innerCursor.firstField();
    }
    enterField(key) {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43e /* Cursor must be current to be used */);
        return this.innerCursor.enterField(key);
    }
    get type() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x43f /* Cursor must be current to be used */);
        return this.innerCursor.type;
    }
    get value() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x440 /* Cursor must be current to be used */);
        return this.innerCursor.value;
    }
    // TODO: tests for clear when not at root.
    clear() {
        (0, core_utils_1.assert)(this.state !== core_1.ITreeSubscriptionCursorState.Freed, 0x33b /* Cursor must not be freed */);
        this.state = core_1.ITreeSubscriptionCursorState.Cleared;
        this.innerCursor = undefined;
        this.forest.currentCursors.delete(this);
    }
    /**
     * Move this cursor to the special dummy node above the detached sequences.
     * Can be used when cleared (but not freed).
     */
    setToAboveDetachedSequences() {
        (0, core_utils_1.assert)(this.state !== core_1.ITreeSubscriptionCursorState.Freed, 0x33c /* Cursor must not be freed */);
        this.clear();
        this.state = core_1.ITreeSubscriptionCursorState.Current;
        this.innerCursor = (0, mapTreeCursor_1.cursorForMapTreeNode)(this.forest.roots);
        this.forest.currentCursors.add(this);
    }
    getNode() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x33e /* Cursor must be current to be used */);
        return this.innerCursor.getNode();
    }
    getParent() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x441 /* Cursor must be current to be used */);
        // This could be optimized to skip moving it accessing internals of cursor.
        const key = this.innerCursor.getFieldKey();
        this.innerCursor.exitField();
        const node = this.innerCursor.getNode();
        this.innerCursor.enterField(key);
        return [node, key];
    }
    fork() {
        (0, core_utils_1.assert)(this.innerCursor !== undefined, 0x460 /* Cursor must be current to be used */);
        return new Cursor(this.forest, this.innerCursor.fork());
    }
    free() {
        (0, core_utils_1.assert)(this.state !== core_1.ITreeSubscriptionCursorState.Freed, 0x33f /* Cursor must not be double freed */);
        this.forest.currentCursors.delete(this);
        this.state = core_1.ITreeSubscriptionCursorState.Freed;
    }
    buildAnchor() {
        (0, core_utils_1.assert)(this.state === core_1.ITreeSubscriptionCursorState.Current, 0x37a /* Cursor must be current to be used */);
        return this.forest.anchors.track(this.getPath());
    }
}
// This function is the folder level export for objectForest, and hides all the implementation types.
// When other forest implementations are created (ex: optimized ones),
// this function should likely be moved and updated to (at least conditionally) use them.
/**
 * @returns an implementation of {@link IEditableForest} with no data or schema.
 */
function buildForest(anchors) {
    return new ObjectForest(anchors);
}
exports.buildForest = buildForest;
//# sourceMappingURL=objectForest.js.map