/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { unreachableCase } from "@fluidframework/core-utils";
import { Type } from "@sinclair/typebox";
import { fail } from "../../util/index.js";
import { DiscriminatedUnionDispatcher, makeCodecFamily } from "../../codec/index.js";
import { makeChangeAtomIdCodec } from "../changeAtomIdCodec.js";
import { NoopMarkType, } from "./types.js";
import { Changeset as ChangesetSchema } from "./format.js";
import { isNoopMark } from "./utils.js";
export const sequenceFieldChangeCodecFactory = (childCodec, revisionTagCodec) => makeCodecFamily([
    [0, makeV0Codec(childCodec, revisionTagCodec)],
]);
function makeV0Codec(childCodec, revisionTagCodec) {
    const changeAtomIdCodec = makeChangeAtomIdCodec(revisionTagCodec);
    const markEffectCodec = {
        encode(effect, context) {
            const type = effect.type;
            switch (type) {
                case "MoveIn":
                    return {
                        moveIn: {
                            revision: effect.revision === undefined
                                ? undefined
                                : revisionTagCodec.encode(effect.revision, context),
                            finalEndpoint: effect.finalEndpoint === undefined
                                ? undefined
                                : changeAtomIdCodec.encode(effect.finalEndpoint, context),
                            id: effect.id,
                        },
                    };
                case "Insert":
                    return {
                        insert: {
                            revision: effect.revision === undefined
                                ? undefined
                                : revisionTagCodec.encode(effect.revision, context),
                            id: effect.id,
                        },
                    };
                case "Remove":
                    return {
                        delete: {
                            revision: effect.revision === undefined
                                ? undefined
                                : revisionTagCodec.encode(effect.revision, context),
                            idOverride: effect.idOverride === undefined
                                ? undefined
                                : {
                                    type: effect.idOverride.type,
                                    id: cellIdCodec.encode(effect.idOverride.id, context),
                                },
                            id: effect.id,
                        },
                    };
                case "MoveOut":
                    return {
                        moveOut: {
                            revision: effect.revision === undefined
                                ? undefined
                                : revisionTagCodec.encode(effect.revision, context),
                            finalEndpoint: effect.finalEndpoint === undefined
                                ? undefined
                                : changeAtomIdCodec.encode(effect.finalEndpoint, context),
                            idOverride: effect.idOverride === undefined
                                ? undefined
                                : {
                                    type: effect.idOverride.type,
                                    id: cellIdCodec.encode(effect.idOverride.id, context),
                                },
                            id: effect.id,
                        },
                    };
                case "AttachAndDetach":
                    return {
                        attachAndDetach: {
                            attach: markEffectCodec.encode(effect.attach, context),
                            detach: markEffectCodec.encode(effect.detach, context),
                        },
                    };
                case NoopMarkType:
                    fail(`Mark type: ${type} should not be encoded.`);
                default:
                    unreachableCase(type);
            }
        },
        decode(encoded, context) {
            return decoderLibrary.dispatch(encoded, context);
        },
    };
    const decoderLibrary = new DiscriminatedUnionDispatcher({
        moveIn(encoded, context) {
            const { id, finalEndpoint, revision } = encoded;
            const mark = {
                type: "MoveIn",
                id,
            };
            if (revision !== undefined) {
                mark.revision = revisionTagCodec.decode(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,
            };
            if (revision !== undefined) {
                mark.revision = revisionTagCodec.decode(revision, context);
            }
            return mark;
        },
        delete(encoded, context) {
            const { id, revision, idOverride } = encoded;
            const mark = {
                type: "Remove",
                id,
            };
            if (revision !== undefined) {
                mark.revision = revisionTagCodec.decode(revision, context);
            }
            if (idOverride !== undefined) {
                mark.idOverride = {
                    type: idOverride.type,
                    id: cellIdCodec.decode(idOverride.id, context),
                };
            }
            return mark;
        },
        moveOut(encoded, context) {
            const { id, finalEndpoint, idOverride, revision } = encoded;
            const mark = {
                type: "MoveOut",
                id,
            };
            if (revision !== undefined) {
                mark.revision = revisionTagCodec.decode(revision, context);
            }
            if (finalEndpoint !== undefined) {
                mark.finalEndpoint = changeAtomIdCodec.decode(finalEndpoint, context);
            }
            if (idOverride !== undefined) {
                mark.idOverride = {
                    type: idOverride.type,
                    id: cellIdCodec.decode(idOverride.id, context),
                };
            }
            return mark;
        },
        attachAndDetach(encoded, context) {
            return {
                type: "AttachAndDetach",
                attach: decoderLibrary.dispatch(encoded.attach, context),
                detach: decoderLibrary.dispatch(encoded.detach, context),
            };
        },
    });
    const cellIdCodec = {
        encode: ({ localId, adjacentCells, lineage, revision }, context) => {
            const encoded = {
                atom: changeAtomIdCodec.encode({ localId, revision }, context),
                adjacentCells: adjacentCells?.map(({ id, count }) => [id, count]),
                // eslint-disable-next-line @typescript-eslint/no-shadow
                lineage: lineage?.map(({ revision, id, count, offset }) => [
                    revisionTagCodec.encode(revision, context),
                    id,
                    count,
                    offset,
                ]),
            };
            return encoded;
        },
        decode: ({ atom, adjacentCells, lineage }, context) => {
            const { localId, revision } = changeAtomIdCodec.decode(atom, context);
            // Note: this isn't inlined on decode so that round-tripping changes compare as deep-equal works,
            // which is mostly just a convenience for tests. On encode, JSON.stringify() takes care of removing
            // explicit undefined properties.
            const decoded = { localId };
            if (revision !== undefined) {
                decoded.revision = revision;
            }
            if (adjacentCells !== undefined) {
                decoded.adjacentCells = adjacentCells.map(([id, count]) => ({
                    id,
                    count,
                }));
            }
            if (lineage !== undefined) {
                // eslint-disable-next-line @typescript-eslint/no-shadow
                decoded.lineage = lineage.map(([revision, id, count, offset]) => ({
                    revision: revisionTagCodec.decode(revision, context),
                    id,
                    count,
                    offset,
                }));
            }
            return decoded;
        },
    };
    return {
        encode: (changeset, context) => {
            const jsonMarks = [];
            for (const mark of changeset) {
                const encodedMark = {
                    count: mark.count,
                };
                if (!isNoopMark(mark)) {
                    encodedMark.effect = markEffectCodec.encode(mark, context);
                }
                if (mark.cellId !== undefined) {
                    encodedMark.cellId = cellIdCodec.encode(mark.cellId, context);
                }
                if (mark.changes !== undefined) {
                    encodedMark.changes = childCodec.encode(mark.changes, context);
                }
                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));
                }
                if (mark.cellId !== undefined) {
                    decodedMark.cellId = cellIdCodec.decode(mark.cellId, context);
                }
                if (mark.changes !== undefined) {
                    decodedMark.changes = childCodec.decode(mark.changes, context);
                }
                marks.push(decodedMark);
            }
            return marks;
        },
        encodedSchema: ChangesetSchema(childCodec.encodedSchema ?? Type.Any()),
    };
}
//# sourceMappingURL=sequenceFieldCodecs.js.map