"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.invert = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../../util/index.js");
const index_js_2 = require("../modular-schema/index.js");
const format_js_1 = require("./format.js");
const markListFactory_js_1 = require("./markListFactory.js");
const types_js_1 = require("./types.js");
const utils_js_1 = require("./utils.js");
/**
 * Inverts a given changeset.
 * @param change - The changeset to produce the inverse of.
 * @returns The inverse of the given `change` such that the inverse can be applied after `change`.
 *
 * WARNING! This implementation is incomplete:
 * - Support for slices is not implemented.
 */
function invert(change, isRollback, genId, crossFieldManager, revisionMetadata) {
    return invertMarkList(change.change, change.revision, crossFieldManager, revisionMetadata);
}
exports.invert = invert;
function invertMarkList(markList, revision, crossFieldManager, revisionMetadata) {
    const inverseMarkList = new markListFactory_js_1.MarkListFactory();
    for (const mark of markList) {
        const inverseMarks = invertMark(mark, revision, crossFieldManager, revisionMetadata);
        inverseMarkList.push(...inverseMarks);
    }
    return inverseMarkList.list;
}
function invertMark(mark, revision, crossFieldManager, revisionMetadata) {
    if (!(0, utils_js_1.isImpactful)(mark, revision, revisionMetadata)) {
        const inputId = (0, utils_js_1.getInputCellId)(mark, revision, revisionMetadata);
        return [invertNodeChangeOrSkip(mark.count, mark.changes, inputId)];
    }
    const type = mark.type;
    switch (type) {
        case types_js_1.NoopMarkType: {
            return [mark];
        }
        case "Remove": {
            (0, internal_1.assert)(revision !== undefined, 0x5a1 /* Unable to revert to undefined revision */);
            const outputId = (0, utils_js_1.getOutputCellId)(mark, revision, revisionMetadata);
            const inputId = (0, utils_js_1.getInputCellId)(mark, revision, revisionMetadata);
            const inverse = inputId === undefined
                ? {
                    type: "Insert",
                    id: mark.id,
                    cellId: outputId,
                    count: mark.count,
                }
                : {
                    type: "Remove",
                    id: mark.id,
                    cellId: outputId,
                    count: mark.count,
                    idOverride: {
                        type: format_js_1.DetachIdOverrideType.Redetach,
                        id: inputId,
                    },
                };
            return [(0, utils_js_1.withNodeChange)(inverse, mark.changes)];
        }
        case "Insert": {
            const inputId = (0, utils_js_1.getInputCellId)(mark, revision, revisionMetadata);
            (0, internal_1.assert)(inputId !== undefined, 0x80c /* Active inserts should target empty cells */);
            const removeMark = {
                type: "Remove",
                count: mark.count,
                id: inputId.localId,
            };
            removeMark.idOverride = {
                type: (0, utils_js_1.isReattach)(mark)
                    ? format_js_1.DetachIdOverrideType.Redetach
                    : format_js_1.DetachIdOverrideType.Unattach,
                id: inputId,
            };
            const inverse = (0, utils_js_1.withNodeChange)(removeMark, mark.changes);
            return [inverse];
        }
        case "MoveOut": {
            if (mark.changes !== undefined) {
                (0, internal_1.assert)(mark.count === 1, 0x6ed /* Mark with changes can only target a single cell */);
                const endpoint = (0, utils_js_1.getEndpoint)(mark, revision);
                crossFieldManager.set(index_js_2.CrossFieldTarget.Destination, endpoint.revision, endpoint.localId, mark.count, mark.changes, true);
            }
            const cellId = (0, utils_js_1.getDetachOutputCellId)(mark, mark.revision ?? revision ?? (0, index_js_1.fail)("Revision must be defined"), revisionMetadata) ?? {
                revision: mark.revision ?? revision ?? (0, index_js_1.fail)("Revision must be defined"),
                localId: mark.id,
            };
            const moveIn = {
                type: "MoveIn",
                id: mark.id,
            };
            if (mark.finalEndpoint !== undefined) {
                moveIn.finalEndpoint = { localId: mark.finalEndpoint.localId };
            }
            let effect = moveIn;
            const inputId = (0, utils_js_1.getInputCellId)(mark, revision, revisionMetadata);
            if (inputId !== undefined) {
                effect = {
                    type: "AttachAndDetach",
                    attach: moveIn,
                    detach: {
                        type: "Remove",
                        id: mark.id,
                        idOverride: {
                            type: format_js_1.DetachIdOverrideType.Redetach,
                            id: inputId,
                        },
                    },
                };
            }
            return [{ ...effect, count: mark.count, cellId }];
        }
        case "MoveIn": {
            const inputId = (0, utils_js_1.getInputCellId)(mark, revision, revisionMetadata);
            (0, internal_1.assert)(inputId !== undefined, 0x89e /* Active move-ins should target empty cells */);
            const invertedMark = {
                type: "MoveOut",
                id: mark.id,
                count: mark.count,
            };
            if (mark.finalEndpoint) {
                invertedMark.finalEndpoint = { localId: mark.finalEndpoint.localId };
            }
            invertedMark.idOverride = {
                type: (0, utils_js_1.isReattach)(mark)
                    ? format_js_1.DetachIdOverrideType.Redetach
                    : format_js_1.DetachIdOverrideType.Unattach,
                id: inputId,
            };
            return applyMovedChanges(invertedMark, revision, crossFieldManager);
        }
        case "AttachAndDetach": {
            // Which should get the child change? Don't want to invert twice
            const attach = {
                count: mark.count,
                cellId: mark.cellId,
                ...mark.attach,
            };
            const idAfterAttach = (0, utils_js_1.getOutputCellId)(attach, revision, undefined);
            // We put `mark.changes` on the detach so that if it is a move source
            // the changes can be sent to the endpoint.
            const detach = {
                count: mark.count,
                cellId: idAfterAttach,
                changes: mark.changes,
                ...mark.detach,
            };
            const attachInverses = invertMark(attach, revision, crossFieldManager, revisionMetadata);
            const detachInverses = invertMark(detach, revision, crossFieldManager, revisionMetadata);
            if (detachInverses.length === 0) {
                return attachInverses;
            }
            (0, internal_1.assert)(detachInverses.length === 1, 0x80d /* Only expected MoveIn marks to be split when inverting */);
            let detachInverse = detachInverses[0];
            (0, internal_1.assert)((0, utils_js_1.isAttach)(detachInverse), 0x80e /* Inverse of a detach should be an attach */);
            const inverses = [];
            for (const attachInverse of attachInverses) {
                let detachInverseCurr = detachInverse;
                if (attachInverse.count !== detachInverse.count) {
                    [detachInverseCurr, detachInverse] = (0, utils_js_1.splitMark)(detachInverse, attachInverse.count);
                }
                if (attachInverse.type === types_js_1.NoopMarkType) {
                    if (attachInverse.changes !== undefined) {
                        (0, internal_1.assert)(detachInverseCurr.changes === undefined, 0x80f /* Unexpected node changes */);
                        detachInverseCurr.changes = attachInverse.changes;
                    }
                    inverses.push(detachInverseCurr);
                    continue;
                }
                (0, internal_1.assert)((0, utils_js_1.isDetach)(attachInverse), 0x810 /* Inverse of an attach should be a detach */);
                const inverted = {
                    type: "AttachAndDetach",
                    count: attachInverse.count,
                    attach: (0, utils_js_1.extractMarkEffect)(detachInverseCurr),
                    detach: (0, utils_js_1.extractMarkEffect)(attachInverse),
                };
                if (detachInverseCurr.cellId !== undefined) {
                    inverted.cellId = detachInverseCurr.cellId;
                }
                if (detachInverseCurr.changes !== undefined) {
                    inverted.changes = detachInverseCurr.changes;
                }
                if (attachInverse.changes !== undefined) {
                    (0, internal_1.assert)(inverted.changes === undefined, 0x811 /* Unexpected node changes */);
                    inverted.changes = attachInverse.changes;
                }
                inverses.push((0, utils_js_1.normalizeCellRename)(inverted));
            }
            return inverses;
        }
        default:
            (0, internal_1.unreachableCase)(type);
    }
}
function applyMovedChanges(mark, revision, manager) {
    // Although this is a source mark, we query the destination because this was a destination mark during the original invert pass.
    const entry = manager.get(index_js_2.CrossFieldTarget.Destination, mark.revision ?? revision, mark.id, mark.count, true);
    if (entry.length < mark.count) {
        const [mark1, mark2] = (0, utils_js_1.splitMark)(mark, entry.length);
        const mark1WithChanges = entry.value !== undefined
            ? (0, utils_js_1.withNodeChange)(mark1, entry.value)
            : mark1;
        return [mark1WithChanges, ...applyMovedChanges(mark2, revision, manager)];
    }
    if (entry.value !== undefined) {
        return [(0, utils_js_1.withNodeChange)(mark, entry.value)];
    }
    return [mark];
}
function invertNodeChangeOrSkip(count, changes, cellId) {
    if (changes !== undefined) {
        (0, internal_1.assert)(count === 1, 0x66c /* A modify mark must have length equal to one */);
        const noop = {
            count,
            changes,
        };
        if (cellId !== undefined) {
            noop.cellId = cellId;
        }
        return noop;
    }
    if (cellId !== undefined) {
        return { count, cellId };
    }
    return { count };
}
//# sourceMappingURL=invert.js.map