"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeV1Codec = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../../codec/index.js");
const index_js_2 = require("../../util/index.js");
const changeAtomIdCodec_js_1 = require("../changeAtomIdCodec.js");
const index_js_3 = require("../modular-schema/index.js");
const formatV1_js_1 = require("./formatV1.js");
const types_js_1 = require("./types.js");
const utils_js_1 = require("./utils.js");
function makeV1Codec(revisionTagCodec) {
    const changeAtomIdCodec = (0, changeAtomIdCodec_js_1.makeChangeAtomIdCodec)(revisionTagCodec);
    const markEffectCodec = {
        encode(effect, context) {
            function encodeRevision(revision) {
                if (revision === undefined || revision === context.revision) {
                    return undefined;
                }
                return revisionTagCodec.encode(revision, context);
            }
            const type = effect.type;
            switch (type) {
                case "MoveIn":
                    return {
                        moveIn: {
                            revision: encodeRevision(effect.revision),
                            finalEndpoint: effect.finalEndpoint === undefined
                                ? undefined
                                : changeAtomIdCodec.encode(effect.finalEndpoint, context),
                            id: effect.id,
                        },
                    };
                case "Insert":
                    return {
                        insert: {
                            revision: encodeRevision(effect.revision),
                            id: effect.id,
                        },
                    };
                case "Remove":
                    return {
                        delete: {
                            revision: encodeRevision(effect.revision),
                            idOverride: effect.idOverride === undefined
                                ? undefined
                                : {
                                    // An arbitrary override type is chosen here. It only had an impact on lineage logic which was not enabled in V1.
                                    type: formatV1_js_1.DetachIdOverrideType.Unattach,
                                    id: cellIdCodec.encode(effect.idOverride, context),
                                },
                            id: effect.id,
                        },
                    };
                case "MoveOut":
                    return {
                        moveOut: {
                            revision: encodeRevision(effect.revision),
                            finalEndpoint: effect.finalEndpoint === undefined
                                ? undefined
                                : changeAtomIdCodec.encode(effect.finalEndpoint, context),
                            idOverride: effect.idOverride === undefined
                                ? undefined
                                : {
                                    // An arbitrary override type is chosen here. It only had an impact on lineage logic which was not enabled in V1.
                                    type: formatV1_js_1.DetachIdOverrideType.Unattach,
                                    id: cellIdCodec.encode(effect.idOverride, context),
                                },
                            id: effect.id,
                        },
                    };
                case "AttachAndDetach":
                    return {
                        attachAndDetach: {
                            attach: markEffectCodec.encode(effect.attach, context),
                            detach: markEffectCodec.encode(effect.detach, context),
                        },
                    };
                case "Rename":
                    // In documents generated by clients on release >=2.2 (i.e., running the code from the PR that added this comment),
                    // renames are encoded as AttachAndDetach with a special id.
                    // This ensures forward-compatibility of clients on release <=2.1 with documents/ops generated by clients on release >=2.2.
                    return markEffectCodec.encode({
                        type: "AttachAndDetach",
                        attach: { type: "MoveIn", id: renameLocalId },
                        detach: { type: "MoveOut", id: renameLocalId, idOverride: effect.idOverride },
                    }, context);
                case types_js_1.NoopMarkType:
                    (0, internal_1.fail)(0xb2b /* Mark type: NoopMarkType should not be encoded. */);
                default:
                    (0, internal_1.unreachableCase)(type);
            }
        },
        decode(encoded, context) {
            return decoderLibrary.dispatch(encoded, context);
        },
    };
    function decodeRevision(encodedRevision, context) {
        if (encodedRevision === undefined) {
            (0, internal_1.assert)(context.revision !== undefined, 0x965 /* Implicit revision should be provided */);
            return context.revision;
        }
        return revisionTagCodec.decode(encodedRevision, context);
    }
    const decoderLibrary = new index_js_1.DiscriminatedUnionDispatcher({
        moveIn(encoded, context) {
            const { id, finalEndpoint, revision } = encoded;
            const mark = {
                type: "MoveIn",
                id,
            };
            mark.revision = decodeRevision(revision, context);
            if (finalEndpoint !== undefined) {
                mark.finalEndpoint = changeAtomIdCodec.decode(finalEndpoint, context);
            }
            return mark;
        },
        insert(encoded, context) {
            const { id, revision } = encoded;
            const mark = {
                type: "Insert",
                id,
            };
            mark.revision = decodeRevision(revision, context);
            return mark;
        },
        delete(encoded, context) {
            const { id, revision, idOverride } = encoded;
            const mark = {
                type: "Remove",
                id,
            };
            mark.revision = decodeRevision(revision, context);
            if (idOverride !== undefined) {
                mark.idOverride = cellIdCodec.decode(idOverride.id, context);
            }
            return mark;
        },
        moveOut(encoded, context) {
            const { id, finalEndpoint, idOverride, revision } = encoded;
            const mark = {
                type: "MoveOut",
                id,
            };
            mark.revision = decodeRevision(revision, context);
            if (finalEndpoint !== undefined) {
                mark.finalEndpoint = changeAtomIdCodec.decode(finalEndpoint, context);
            }
            if (idOverride !== undefined) {
                mark.idOverride = cellIdCodec.decode(idOverride.id, context);
            }
            return mark;
        },
        attachAndDetach(encoded, context) {
            const attach = decoderLibrary.dispatch(encoded.attach, context);
            const detach = decoderLibrary.dispatch(encoded.detach, context);
            // In documents generated by clients on release >=2.2 (i.e., running the code from the PR that added this comment),
            // renames are encoded as AttachAndDetach with a special id.
            // This ensures forward-compatibility of clients on release <=2.1 with documents/ops generated by clients on release >=2.2.
            if (attach.id === renameLocalId) {
                (0, internal_1.assert)(detach.idOverride !== undefined, 0x9f7 /* Rename must have idOverride */);
                return {
                    type: "Rename",
                    idOverride: detach.idOverride,
                };
            }
            return {
                type: "AttachAndDetach",
                attach,
                detach,
            };
        },
    });
    const cellIdCodec = {
        encode: (cellId, context) => {
            const encoded = {
                atom: changeAtomIdCodec.encode(cellId, context),
            };
            return encoded;
        },
        decode: ({ atom }, context) => {
            return changeAtomIdCodec.decode(atom, context);
        },
    };
    return {
        encode: (changeset, context) => {
            const jsonMarks = [];
            for (const mark of changeset) {
                const encodedMark = {
                    count: mark.count,
                };
                if (!(0, utils_js_1.isNoopMark)(mark)) {
                    encodedMark.effect = markEffectCodec.encode(mark, context.baseContext);
                }
                if (mark.cellId !== undefined) {
                    encodedMark.cellId = cellIdCodec.encode(mark.cellId, context.baseContext);
                }
                if (mark.changes !== undefined) {
                    encodedMark.changes = context.encodeNode(mark.changes);
                }
                jsonMarks.push(encodedMark);
            }
            return jsonMarks;
        },
        decode: (changeset, context) => {
            const marks = [];
            for (const mark of changeset) {
                const decodedMark = {
                    count: mark.count,
                };
                if (mark.effect !== undefined) {
                    Object.assign(decodedMark, markEffectCodec.decode(mark.effect, context.baseContext));
                }
                if (mark.cellId !== undefined) {
                    decodedMark.cellId = cellIdCodec.decode(mark.cellId, context.baseContext);
                }
                // Type deduction wrongly narrows the type of `decodedMark` to `NoopMark & HasMarkFields`.
                // We declare a new casted copy of `decodedMark` to recover the correct type.
                let decodedMark2 = decodedMark;
                if (decodedMark2.cellId !== undefined && decodedMark2.type === "AttachAndDetach") {
                    // In documents generated by clients on release <=2.1 (i.e., not running the code from the PR that added this comment),
                    // rename-like AttachAndDetach marks are not normalized to Rename marks thus requiring this normalization step.
                    // This ensures backward compatibility with documents generated by clients on release <=2.1.
                    decodedMark2 = (0, utils_js_1.normalizeCellRename)(decodedMark2.cellId, decodedMark2.count, decodedMark2.attach, decodedMark2.detach);
                }
                if (mark.changes !== undefined) {
                    decodedMark2.changes = context.decodeNode(mark.changes);
                }
                marks.push(decodedMark2);
            }
            return marks;
        },
        encodedSchema: (0, formatV1_js_1.Changeset)(index_js_3.EncodedNodeChangeset),
    };
}
exports.makeV1Codec = makeV1Codec;
/**
 * Arbitrary ID that is used to indicate a Rename effect.
 */
const renameLocalId = (0, index_js_2.brand)(-1);
//# sourceMappingURL=sequenceFieldCodecV1.js.map