"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultEditBuilder = exports.relevantRemovedRoots = exports.intoDelta = exports.DefaultChangeFamily = void 0;
const internal_1 = require("@fluidframework/telemetry-utils/internal");
const index_js_1 = require("../../core/index.js");
const index_js_2 = require("../../util/index.js");
const index_js_3 = require("../modular-schema/index.js");
const defaultFieldKinds_js_1 = require("./defaultFieldKinds.js");
/**
 * Implementation of {@link ChangeFamily} based on the default set of supported field kinds.
 *
 * @sealed
 */
class DefaultChangeFamily {
    constructor(codecs) {
        this.modularFamily = new index_js_3.ModularChangeFamily(defaultFieldKinds_js_1.fieldKinds, codecs);
    }
    get rebaser() {
        return this.modularFamily.rebaser;
    }
    get codecs() {
        return this.modularFamily.codecs;
    }
    buildEditor(changeReceiver) {
        return new DefaultEditBuilder(this, changeReceiver);
    }
}
exports.DefaultChangeFamily = DefaultChangeFamily;
/**
 * @param change - The change to convert into a delta.
 */
function intoDelta(taggedChange) {
    return (0, index_js_3.intoDelta)(taggedChange, defaultFieldKinds_js_1.fieldKinds);
}
exports.intoDelta = intoDelta;
/**
 * 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.
 */
function relevantRemovedRoots(change) {
    return (0, index_js_3.relevantRemovedRoots)(change, defaultFieldKinds_js_1.fieldKinds);
}
exports.relevantRemovedRoots = relevantRemovedRoots;
/**
 * Implementation of {@link IDefaultEditBuilder} based on the default set of supported field kinds.
 * @sealed
 */
class DefaultEditBuilder {
    constructor(family, changeReceiver) {
        this.modularBuilder = new index_js_3.ModularEditBuilder(family, changeReceiver);
    }
    enterTransaction() {
        this.modularBuilder.enterTransaction();
    }
    exitTransaction() {
        this.modularBuilder.exitTransaction();
    }
    addNodeExistsConstraint(path) {
        this.modularBuilder.addNodeExistsConstraint(path);
    }
    valueField(field) {
        return {
            set: (newContent) => {
                const fillId = this.modularBuilder.generateId();
                const build = this.modularBuilder.buildTrees(fillId, newContent);
                const change = (0, index_js_2.brand)(defaultFieldKinds_js_1.required.changeHandler.editor.set({
                    fill: fillId,
                    detach: this.modularBuilder.generateId(),
                }));
                const edit = {
                    type: "field",
                    field,
                    fieldKind: defaultFieldKinds_js_1.required.identifier,
                    change,
                };
                this.modularBuilder.submitChanges([build, edit]);
            },
        };
    }
    optionalField(field) {
        return {
            set: (newContent, wasEmpty) => {
                const detachId = this.modularBuilder.generateId();
                let fillId;
                const edits = [];
                let optionalChange;
                if (newContent !== undefined) {
                    fillId = this.modularBuilder.generateId();
                    const build = this.modularBuilder.buildTrees(fillId, newContent);
                    edits.push(build);
                    optionalChange = defaultFieldKinds_js_1.optional.changeHandler.editor.set(wasEmpty, {
                        fill: fillId,
                        detach: detachId,
                    });
                }
                else {
                    optionalChange = defaultFieldKinds_js_1.optional.changeHandler.editor.clear(wasEmpty, detachId);
                }
                const change = (0, index_js_2.brand)(optionalChange);
                const edit = {
                    type: "field",
                    field,
                    fieldKind: defaultFieldKinds_js_1.optional.identifier,
                    change,
                };
                edits.push(edit);
                this.modularBuilder.submitChanges(edits);
            },
        };
    }
    move(sourceField, sourceIndex, count, destinationField, destIndex) {
        if (count === 0) {
            return;
        }
        else if (count < 0 || !Number.isSafeInteger(count)) {
            throw new internal_1.UsageError(`Expected non-negative integer count, got ${count}.`);
        }
        const detachId = this.modularBuilder.generateId(count);
        const attachId = this.modularBuilder.generateId(count);
        if ((0, index_js_1.compareFieldUpPaths)(sourceField, destinationField)) {
            const change = defaultFieldKinds_js_1.sequence.changeHandler.editor.move(sourceIndex, count, destIndex, detachId, attachId);
            this.modularBuilder.submitChange(sourceField, defaultFieldKinds_js_1.sequence.identifier, (0, index_js_2.brand)(change));
        }
        else {
            const detachPath = (0, index_js_1.topDownPath)(sourceField.parent);
            const attachPath = (0, index_js_1.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];
                        parent = {
                            parent,
                            parentIndex: attachAncestorIndex,
                            parentField: attachPath[sharedDepth].parentField,
                        };
                        for (let i = sharedDepth + 1; i < attachPath.length; i += 1) {
                            parent = {
                                ...attachPath[i],
                                parent,
                            };
                        }
                        adjustedAttachField = { parent, field: destinationField.field };
                    }
                    else {
                        throw new internal_1.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 = defaultFieldKinds_js_1.sequence.changeHandler.editor.moveOut(sourceIndex, count, detachId);
            const moveIn = defaultFieldKinds_js_1.sequence.changeHandler.editor.moveIn(destIndex, count, detachId, attachId);
            this.modularBuilder.submitChanges([
                {
                    type: "field",
                    field: sourceField,
                    fieldKind: defaultFieldKinds_js_1.sequence.identifier,
                    change: (0, index_js_2.brand)(moveOut),
                },
                {
                    type: "field",
                    field: adjustedAttachField,
                    fieldKind: defaultFieldKinds_js_1.sequence.identifier,
                    change: (0, index_js_2.brand)(moveIn),
                },
            ]);
        }
    }
    sequenceField(field) {
        return {
            insert: (index, content) => {
                const length = content.mode === 1 /* CursorLocationType.Fields */ ? content.getFieldLength() : 1;
                if (length === 0) {
                    return;
                }
                const firstId = this.modularBuilder.generateId(length);
                const build = this.modularBuilder.buildTrees(firstId, content);
                const change = (0, index_js_2.brand)(defaultFieldKinds_js_1.sequence.changeHandler.editor.insert(index, length, firstId));
                const attach = {
                    type: "field",
                    field,
                    fieldKind: defaultFieldKinds_js_1.sequence.identifier,
                    change,
                };
                // 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]);
            },
            remove: (index, count) => {
                if (count === 0) {
                    return;
                }
                const id = this.modularBuilder.generateId(count);
                const change = (0, index_js_2.brand)(defaultFieldKinds_js_1.sequence.changeHandler.editor.remove(index, count, id));
                this.modularBuilder.submitChange(field, defaultFieldKinds_js_1.sequence.identifier, change);
            },
            move: (sourceIndex, count, destIndex) => {
                if (count === 0) {
                    return;
                }
                else if (count < 0 || !Number.isSafeInteger(count)) {
                    throw new internal_1.UsageError(`Expected non-negative integer count, got ${count}.`);
                }
                const detachId = this.modularBuilder.generateId(count);
                const attachId = this.modularBuilder.generateId(count);
                const change = defaultFieldKinds_js_1.sequence.changeHandler.editor.move(sourceIndex, count, destIndex, detachId, attachId);
                this.modularBuilder.submitChange(field, defaultFieldKinds_js_1.sequence.identifier, (0, index_js_2.brand)(change));
            },
        };
    }
}
exports.DefaultEditBuilder = DefaultEditBuilder;
/**
 * @returns 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];
        const attachStep = pathB[sharedDepth];
        if (detachStep !== attachStep) {
            if (detachStep.parentField !== attachStep.parentField ||
                detachStep.parentIndex !== attachStep.parentIndex) {
                break;
            }
        }
        sharedDepth += 1;
    }
    return sharedDepth;
}
//# sourceMappingURL=defaultEditBuilder.js.map