"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeSharedTreeChangeCodecFamily = exports.makeSharedTreeChangeCodec = void 0;
const codec_1 = require("../codec");
const feature_libraries_1 = require("../feature-libraries");
const sharedTreeChangeFormat_1 = require("./sharedTreeChangeFormat");
function makeSharedTreeChangeCodec(modularChangeCodec, codecOptions) {
    const schemaChangeCodec = (0, feature_libraries_1.makeSchemaChangeCodec)(codecOptions);
    const decoderLibrary = new codec_1.DiscriminatedUnionDispatcher({
        data(encoded, context) {
            return {
                type: "data",
                innerChange: modularChangeCodec.decode(encoded, context),
            };
        },
        schema(encoded) {
            return {
                type: "schema",
                innerChange: schemaChangeCodec.decode(encoded),
            };
        },
    });
    return {
        encode: (change, context) => {
            const changes = [];
            for (const decodedChange of change.changes) {
                if (decodedChange.type === "data") {
                    changes.push({
                        data: modularChangeCodec.encode(decodedChange.innerChange, context),
                    });
                }
                else if (decodedChange.type === "schema") {
                    changes.push({
                        schema: schemaChangeCodec.encode(decodedChange.innerChange),
                    });
                }
            }
            return changes;
        },
        decode: (encodedChange, context) => {
            const changes = [];
            for (const subChange of encodedChange) {
                changes.push(decoderLibrary.dispatch(subChange, context));
            }
            return { changes };
        },
        encodedSchema: sharedTreeChangeFormat_1.EncodedSharedTreeChange,
    };
}
exports.makeSharedTreeChangeCodec = makeSharedTreeChangeCodec;
function makeSharedTreeChangeCodecFamily(modularChangeCodec, options) {
    return (0, codec_1.makeCodecFamily)([[0, makeSharedTreeChangeCodec(modularChangeCodec, options)]]);
}
exports.makeSharedTreeChangeCodecFamily = makeSharedTreeChangeCodecFamily;
//# sourceMappingURL=sharedTreeChangeCodecs.js.map