/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { makeCodecFamily, DiscriminatedUnionDispatcher, } from "../codec/index.js";
import { defaultSchemaPolicy, makeSchemaChangeCodec, } from "../feature-libraries/index.js";
import { EncodedSharedTreeChange } from "./sharedTreeChangeFormat.js";
export function makeSharedTreeChangeCodec(modularChangeCodec, codecOptions) {
    const schemaChangeCodec = makeSchemaChangeCodec(codecOptions);
    const decoderLibrary = new 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 = [];
            let updatedSchema;
            for (const decodedChange of change.changes) {
                if (decodedChange.type === "data") {
                    const schemaAndPolicy = updatedSchema !== undefined
                        ? {
                            policy: context.schema !== undefined
                                ? context.schema.policy
                                : defaultSchemaPolicy,
                            schema: updatedSchema,
                        }
                        : context.schema;
                    changes.push({
                        data: modularChangeCodec.encode(decodedChange.innerChange, {
                            originatorId: context.originatorId,
                            schema: schemaAndPolicy,
                        }),
                    });
                }
                else if (decodedChange.type === "schema") {
                    changes.push({
                        schema: schemaChangeCodec.encode(decodedChange.innerChange),
                    });
                    updatedSchema = decodedChange.innerChange.schema.new;
                }
            }
            return changes;
        },
        decode: (encodedChange, context) => {
            const changes = [];
            for (const subChange of encodedChange) {
                changes.push(decoderLibrary.dispatch(subChange, context));
            }
            return { changes };
        },
        encodedSchema: EncodedSharedTreeChange,
    };
}
export function makeSharedTreeChangeCodecFamily(modularChangeCodec, options) {
    return makeCodecFamily([[0, makeSharedTreeChangeCodec(modularChangeCodec, options)]]);
}
//# sourceMappingURL=sharedTreeChangeCodecs.js.map