/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { makeChangeAtomIdCodec } from "../changeAtomIdCodec.js";
import { EncodedNodeChangeset, } from "../modular-schema/index.js";
import { EncodedOptionalChangeset } from "./optionalFieldChangeFormatV3.js";
export function makeOptionalFieldCodec(revisionTagCodec) {
    const changeAtomIdCodec = makeChangeAtomIdCodec(revisionTagCodec);
    return {
        encode: (change, context) => {
            const encoded = {};
            if (change.valueReplace !== undefined) {
                encoded.r = {
                    e: change.valueReplace.isEmpty,
                    d: changeAtomIdCodec.encode(change.valueReplace.dst, context.baseContext),
                };
                if (change.valueReplace.src !== undefined) {
                    encoded.r.s = changeAtomIdCodec.encode(change.valueReplace.src, context.baseContext);
                }
            }
            if (change.nodeDetach !== undefined) {
                encoded.d = changeAtomIdCodec.encode(change.nodeDetach, context.baseContext);
            }
            if (change.childChange !== undefined) {
                encoded.c = context.encodeNode(change.childChange);
            }
            return encoded;
        },
        decode: (encoded, context) => {
            const decoded = {};
            if (encoded.r !== undefined) {
                const replace = {
                    isEmpty: encoded.r.e,
                    dst: changeAtomIdCodec.decode(encoded.r.d, context.baseContext),
                };
                if (encoded.r.s !== undefined) {
                    replace.src = changeAtomIdCodec.decode(encoded.r.s, context.baseContext);
                }
                decoded.valueReplace = replace;
            }
            if (encoded.d !== undefined) {
                decoded.nodeDetach = changeAtomIdCodec.decode(encoded.d, context.baseContext);
            }
            if (encoded.c !== undefined) {
                decoded.childChange = context.decodeNode(encoded.c);
            }
            return decoded;
        },
        encodedSchema: EncodedOptionalChangeset(EncodedNodeChangeset),
    };
}
//# sourceMappingURL=optionalFieldCodecV3.js.map