/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { oob } from "@fluidframework/core-utils/internal";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { compareFieldUpPaths, topDownPath, } from "../../core/index.js";
import { brand } from "../../util/index.js";
import { ModularChangeFamily, ModularEditBuilder, intoDelta as intoModularDelta, relevantRemovedRoots as relevantModularRemovedRoots, } from "../modular-schema/index.js";
import { fieldKinds, optional, sequence, required as valueFieldKind, } from "./defaultFieldKinds.js";
/**
 * Implementation of {@link ChangeFamily} based on the default set of supported field kinds.
 *
 * @sealed
 */
export class DefaultChangeFamily {
    constructor(codecs) {
        this.modularFamily = new ModularChangeFamily(fieldKinds, codecs);
    }
    get rebaser() {
        return this.modularFamily.rebaser;
    }
    get codecs() {
        return this.modularFamily.codecs;
    }
    buildEditor(mintRevisionTag, changeReceiver) {
        return new DefaultEditBuilder(this, mintRevisionTag, changeReceiver);
    }
}
/**
 * @param change - The change to convert into a delta.
 */
export function intoDelta(taggedChange) {
    return intoModularDelta(taggedChange, fieldKinds);
}
/**
 * Returns the set of removed roots that should be in memory for the given change to be applied.
 * A removed root is relevant if any of the following is true:
 * - It is being inserted
 * - It is being restored
 * - It is being edited
 * - The ID it is associated with is being changed
 *
 * May be conservative by returning more removed roots than strictly necessary.
 *
 * Will never return IDs for non-root trees, even if they are removed.
 *
 * @param change - The change to be applied.
 */
export function relevantRemovedRoots(change) {
    return relevantModularRemovedRoots(change, fieldKinds);
}
/**
 * Implementation of {@link IDefaultEditBuilder} based on the default set of supported field kinds.
 * @sealed
 */
export class DefaultEditBuilder {
    constructor(family, mintRevisionTag, changeReceiver) {
        this.mintRevisionTag = mintRevisionTag;
        this.modularBuilder = new ModularEditBuilder(family, fieldKinds, changeReceiver);
    }
    enterTransaction() {
        this.modularBuilder.enterTransaction();
    }
    exitTransaction() {
        this.modularBuilder.exitTransaction();
    }
    addNodeExistsConstraint(path) {
        this.modularBuilder.addNodeExistsConstraint(path, this.mintRevisionTag());
    }
    addNodeExistsConstraintOnRevert(path) {
        this.modularBuilder.addNodeExistsConstraintOnRevert(path, this.mintRevisionTag());
    }
    valueField(field) {
        return {
            set: (newContent) => {
                const revision = this.mintRevisionTag();
                const fill = { localId: this.modularBuilder.generateId(), revision };
                const detach = { localId: this.modularBuilder.generateId(), revision };
                const build = this.modularBuilder.buildTrees(fill.localId, newContent, revision);
                const change = brand(valueFieldKind.changeHandler.editor.set({
                    fill,
                    detach,
                }));
                const edit = {
                    type: "field",
                    field,
                    fieldKind: valueFieldKind.identifier,
                    change,
                    revision,
                };
                this.modularBuilder.submitChanges([build, edit], revision);
            },
        };
    }
    optionalField(field) {
        return {
            set: (newContent, wasEmpty) => {
                const edits = [];
                let optionalChange;
                const revision = this.mintRevisionTag();
                const detach = { localId: this.modularBuilder.generateId(), revision };
                if (newContent !== undefined) {
                    const fill = { localId: this.modularBuilder.generateId(), revision };
                    const build = this.modularBuilder.buildTrees(fill.localId, newContent, revision);
                    edits.push(build);
                    optionalChange = optional.changeHandler.editor.set(wasEmpty, {
                        fill,
                        detach,
                    });
                }
                else {
                    optionalChange = optional.changeHandler.editor.clear(wasEmpty, detach);
                }
                const change = brand(optionalChange);
                const edit = {
                    type: "field",
                    field,
                    fieldKind: optional.identifier,
                    change,
                    revision,
                };
                edits.push(edit);
                this.modularBuilder.submitChanges(edits, revision);
            },
        };
    }
    move(sourceField, sourceIndex, count, destinationField, destIndex) {
        if (count === 0) {
            return;
        }
        else if (count < 0 || !Number.isSafeInteger(count)) {
            throw new UsageError(`Expected non-negative integer count, got ${count}.`);
        }
        const revision = this.mintRevisionTag();
        const detachCellId = this.modularBuilder.generateId(count);
        const attachCellId = { localId: this.modularBuilder.generateId(count), revision };
        if (compareFieldUpPaths(sourceField, destinationField)) {
            const change = sequence.changeHandler.editor.move(sourceIndex, count, destIndex, detachCellId, attachCellId, revision);
            this.modularBuilder.submitChange(sourceField, sequence.identifier, brand(change), revision);
        }
        else {
            const detachPath = topDownPath(sourceField.parent);
            const attachPath = topDownPath(destinationField.parent);
            const sharedDepth = getSharedPrefixLength(detachPath, attachPath);
            let adjustedAttachField = destinationField;
            // After the above loop, `sharedDepth` is the number of elements, starting from the root,
            // that both paths have in common.
            if (sharedDepth === detachPath.length) {
                const attachField = attachPath[sharedDepth]?.parentField ?? destinationField.field;
                if (attachField === sourceField.field) {
                    // The detach occurs in an ancestor field of the field where the attach occurs.
                    let attachAncestorIndex = attachPath[sharedDepth]?.parentIndex ?? sourceIndex;
                    if (attachAncestorIndex < sourceIndex) {
                        // The attach path runs through a node located before the detached nodes.
                        // No need to adjust the attach path.
                    }
                    else if (sourceIndex + count <= attachAncestorIndex) {
                        // The attach path runs through a node located after the detached nodes.
                        // adjust the index for the node at that depth of the path, so that it is interpreted correctly
                        // in the composition performed by `submitChanges`.
                        attachAncestorIndex -= count;
                        let parent = attachPath[sharedDepth - 1];
                        const parentField = attachPath[sharedDepth] ?? oob();
                        parent = {
                            parent,
                            parentIndex: attachAncestorIndex,
                            parentField: parentField.parentField,
                        };
                        for (let i = sharedDepth + 1; i < attachPath.length; i += 1) {
                            parent = {
                                ...(attachPath[i] ?? oob()),
                                parent,
                            };
                        }
                        adjustedAttachField = { parent, field: destinationField.field };
                    }
                    else {
                        throw new UsageError("Invalid move operation: the destination is located under one of the moved elements. Consider using the Tree.contains API to detect this.");
                    }
                }
            }
            const moveOut = sequence.changeHandler.editor.moveOut(sourceIndex, count, detachCellId, revision);
            const moveIn = sequence.changeHandler.editor.moveIn(destIndex, count, detachCellId, attachCellId, revision);
            this.modularBuilder.submitChanges([
                {
                    type: "field",
                    field: sourceField,
                    fieldKind: sequence.identifier,
                    change: brand(moveOut),
                    revision,
                },
                {
                    type: "field",
                    field: adjustedAttachField,
                    fieldKind: sequence.identifier,
                    change: brand(moveIn),
                    revision,
                },
            ], revision);
        }
    }
    sequenceField(field) {
        return {
            insert: (index, content) => {
                const length = content.topLevelLength;
                if (length === 0) {
                    return;
                }
                const revision = this.mintRevisionTag();
                const firstId = { localId: this.modularBuilder.generateId(length), revision };
                const build = this.modularBuilder.buildTrees(firstId.localId, content, revision);
                const change = brand(sequence.changeHandler.editor.insert(index, length, firstId, revision));
                const attach = {
                    type: "field",
                    field,
                    fieldKind: sequence.identifier,
                    change,
                    revision,
                };
                // The changes have to be submitted together, otherwise they will be assigned different revisions,
                // which will prevent the build ID and the insert ID from matching.
                this.modularBuilder.submitChanges([build, attach], revision);
            },
            remove: (index, count) => {
                if (count === 0) {
                    return;
                }
                const revision = this.mintRevisionTag();
                const id = this.modularBuilder.generateId(count);
                const change = brand(sequence.changeHandler.editor.remove(index, count, id, revision));
                this.modularBuilder.submitChange(field, sequence.identifier, change, revision);
            },
        };
    }
}
/**
 * Gets the number of path elements that both paths share, starting at index 0.
 */
function getSharedPrefixLength(pathA, pathB) {
    const minDepth = Math.min(pathA.length, pathB.length);
    let sharedDepth = 0;
    while (sharedDepth < minDepth) {
        const detachStep = pathA[sharedDepth] ?? oob();
        const attachStep = pathB[sharedDepth] ?? oob();
        if (detachStep !== attachStep) {
            if (detachStep.parentField !== attachStep.parentField ||
                detachStep.parentIndex !== attachStep.parentIndex) {
                break;
            }
        }
        sharedDepth += 1;
    }
    return sharedDepth;
}
//# sourceMappingURL=defaultEditBuilder.js.map