/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils";
import { compareFieldUpPaths, topDownPath, } from "../../core";
import { brand, isReadonlyArray } from "../../util";
import { ModularChangeFamily, ModularEditBuilder, intoDelta as intoModularDelta, } from "../modular-schema";
import { fieldKinds, optional, sequence, required as valueFieldKind } from "./defaultFieldKinds";
/**
 * Implementation of {@link ChangeFamily} based on the default set of supported field kinds.
 *
 * @sealed
 */
export class DefaultChangeFamily {
    constructor(codecOptions) {
        this.modularFamily = new ModularChangeFamily(fieldKinds, codecOptions);
    }
    get rebaser() {
        return this.modularFamily.rebaser;
    }
    get codecs() {
        return this.modularFamily.codecs;
    }
    buildEditor(changeReceiver) {
        return new DefaultEditBuilder(this, changeReceiver);
    }
}
DefaultChangeFamily.emptyChange = ModularChangeFamily.emptyChange;
/**
 * @param change - The change to convert into a delta.
 */
export function intoDelta(taggedChange) {
    return intoModularDelta(taggedChange, fieldKinds);
}
/**
 * Implementation of {@link IDefaultEditBuilder} based on the default set of supported field kinds.
 * @sealed
 */
export class DefaultEditBuilder {
    constructor(family, changeReceiver) {
        this.modularBuilder = new ModularEditBuilder(family, changeReceiver);
    }
    enterTransaction() {
        this.modularBuilder.enterTransaction();
    }
    exitTransaction() {
        this.modularBuilder.exitTransaction();
    }
    apply(change) {
        this.modularBuilder.apply(change);
    }
    addNodeExistsConstraint(path) {
        this.modularBuilder.addNodeExistsConstraint(path);
    }
    valueField(field) {
        return {
            set: (newContent) => {
                const change = brand(valueFieldKind.changeHandler.editor.set(newContent, {
                    fill: this.modularBuilder.generateId(),
                    detach: this.modularBuilder.generateId(),
                }));
                this.modularBuilder.submitChange(field, valueFieldKind.identifier, change);
            },
        };
    }
    optionalField(field) {
        return {
            set: (newContent, wasEmpty) => {
                const id = this.modularBuilder.generateId();
                const optionalChange = newContent === undefined
                    ? optional.changeHandler.editor.clear(wasEmpty, id)
                    : optional.changeHandler.editor.set(newContent, wasEmpty, {
                        fill: this.modularBuilder.generateId(),
                        detach: this.modularBuilder.generateId(),
                    });
                const change = brand(optionalChange);
                this.modularBuilder.submitChange(field, optional.identifier, change);
            },
        };
    }
    move(sourceField, sourceIndex, count, destinationField, destIndex) {
        const moveId = this.modularBuilder.generateId(count);
        if (compareFieldUpPaths(sourceField, destinationField)) {
            const change = sequence.changeHandler.editor.move(sourceIndex, count, destIndex, moveId);
            this.modularBuilder.submitChange(sourceField, sequence.identifier, brand(change));
        }
        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 {
                        assert(sourceIndex + count <= attachAncestorIndex, 0x801 /* Invalid move: the destination is below one of the moved elements. */);
                        // 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 };
                    }
                }
            }
            const moveOut = sequence.changeHandler.editor.moveOut(sourceIndex, count, moveId);
            const moveIn = sequence.changeHandler.editor.moveIn(destIndex, count, moveId);
            this.modularBuilder.submitChanges([
                {
                    type: "field",
                    field: sourceField,
                    fieldKind: sequence.identifier,
                    change: brand(moveOut),
                },
                {
                    type: "field",
                    field: adjustedAttachField,
                    fieldKind: sequence.identifier,
                    change: brand(moveIn),
                },
            ], moveId);
        }
    }
    sequenceField(field) {
        return {
            insert: (index, newContent) => {
                const content = isReadonlyArray(newContent) ? newContent : [newContent];
                const length = content.length;
                if (length === 0) {
                    return;
                }
                const firstId = this.modularBuilder.generateId(length);
                const build = this.modularBuilder.buildTrees(firstId, content);
                const change = brand(sequence.changeHandler.editor.insert(index, length, firstId));
                const attach = {
                    type: "field",
                    field,
                    fieldKind: 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], brand(firstId + length - 1));
            },
            delete: (index, count) => {
                if (count === 0) {
                    return;
                }
                const id = this.modularBuilder.generateId(count);
                const change = brand(sequence.changeHandler.editor.delete(index, count, id));
                this.modularBuilder.submitChange(field, sequence.identifier, change);
            },
            move: (sourceIndex, count, destIndex) => {
                const moveId = this.modularBuilder.generateId(count);
                const change = sequence.changeHandler.editor.move(sourceIndex, count, destIndex, moveId);
                this.modularBuilder.submitChange(field, sequence.identifier, brand(change));
            },
        };
    }
}
/**
 * @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=defaultChangeFamily.js.map