"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeV0Codec = void 0;
const core_utils_1 = require("@fluidframework/core-utils");
const index_js_1 = require("../../util/index.js");
const index_js_2 = require("../chunked-forest/index.js");
const treeCompressionUtils_js_1 = require("../treeCompressionUtils.js");
const genericFieldKind_js_1 = require("./genericFieldKind.js");
const modularChangeFormat_js_1 = require("./modularChangeFormat.js");
function makeV0Codec(fieldKinds, revisionTagCodec, fieldsCodec, { jsonValidator: validator }, chunkCompressionStrategy = treeCompressionUtils_js_1.TreeCompressionStrategy.Compressed) {
    const nodeChangesetCodec = {
        encode: encodeNodeChangesForJson,
        decode: decodeNodeChangesetFromJson,
        encodedSchema: modularChangeFormat_js_1.EncodedNodeChangeset,
    };
    const getMapEntry = (field) => {
        const codec = field.changeHandler
            .codecsFactory(nodeChangesetCodec, revisionTagCodec)
            .resolve(0);
        return {
            codec,
            compiledSchema: codec.json.encodedSchema
                ? validator.compile(codec.json.encodedSchema)
                : undefined,
        };
    };
    const fieldChangesetCodecs = new Map([[genericFieldKind_js_1.genericFieldKind.identifier, getMapEntry(genericFieldKind_js_1.genericFieldKind)]]);
    fieldKinds.forEach((fieldKind, identifier) => {
        fieldChangesetCodecs.set(identifier, getMapEntry(fieldKind));
    });
    const getFieldChangesetCodec = (fieldKind) => {
        const entry = fieldChangesetCodecs.get(fieldKind);
        (0, core_utils_1.assert)(entry !== undefined, 0x5ea /* Tried to encode unsupported fieldKind */);
        return entry;
    };
    function encodeFieldChangesForJson(change, context) {
        const encodedFields = [];
        for (const [field, fieldChange] of change) {
            const { codec, compiledSchema } = getFieldChangesetCodec(fieldChange.fieldKind);
            const encodedChange = codec.json.encode(fieldChange.change, context);
            if (compiledSchema !== undefined && !compiledSchema.check(encodedChange)) {
                (0, index_js_1.fail)("Encoded change didn't pass schema validation.");
            }
            const fieldKey = field;
            const encodedField = {
                fieldKey,
                fieldKind: fieldChange.fieldKind,
                change: encodedChange,
            };
            encodedFields.push(encodedField);
        }
        return encodedFields;
    }
    function encodeNodeChangesForJson(change, context) {
        const encodedChange = {};
        const { fieldChanges, nodeExistsConstraint } = change;
        if (fieldChanges !== undefined) {
            encodedChange.fieldChanges = encodeFieldChangesForJson(fieldChanges, context);
        }
        if (nodeExistsConstraint !== undefined) {
            encodedChange.nodeExistsConstraint = nodeExistsConstraint;
        }
        return encodedChange;
    }
    function decodeFieldChangesFromJson(encodedChange, context) {
        const decodedFields = new Map();
        for (const field of encodedChange) {
            const { codec, compiledSchema } = getFieldChangesetCodec(field.fieldKind);
            if (compiledSchema !== undefined && !compiledSchema.check(field.change)) {
                (0, index_js_1.fail)("Encoded change didn't pass schema validation.");
            }
            const fieldChangeset = codec.json.decode(field.change, context);
            const fieldKey = (0, index_js_1.brand)(field.fieldKey);
            decodedFields.set(fieldKey, {
                fieldKind: field.fieldKind,
                change: (0, index_js_1.brand)(fieldChangeset),
            });
        }
        return decodedFields;
    }
    function decodeNodeChangesetFromJson(encodedChange, context) {
        const decodedChange = {};
        const { fieldChanges, nodeExistsConstraint } = encodedChange;
        if (fieldChanges !== undefined) {
            decodedChange.fieldChanges = decodeFieldChangesFromJson(fieldChanges, context);
        }
        if (nodeExistsConstraint !== undefined) {
            decodedChange.nodeExistsConstraint = nodeExistsConstraint;
        }
        return decodedChange;
    }
    function encodeDetachedNodes(detachedNodes, context) {
        if (detachedNodes === undefined) {
            return undefined;
        }
        const treesToEncode = [];
        const buildsArray = Array.from(detachedNodes.entries()).map(([r, commitBuilds]) => {
            const commitBuildsEncoded = Array.from(commitBuilds.entries()).map(([i, t]) => {
                treesToEncode.push(t.cursor());
                const treeIndexInBatch = treesToEncode.length - 1;
                return [i, treeIndexInBatch];
            });
            // `undefined` does not round-trip through JSON strings, so it needs special handling.
            // Most entries will have an undefined revision due to the revision information being inherited from the `ModularChangeset`.
            // We therefore optimize for the common case by omitting the revision when it is undefined.
            return r !== undefined
                ? [commitBuildsEncoded, revisionTagCodec.encode(r, context)]
                : [commitBuildsEncoded];
        });
        return buildsArray.length === 0
            ? undefined
            : {
                builds: buildsArray,
                trees: fieldsCodec.encode(treesToEncode, {
                    encodeType: chunkCompressionStrategy,
                    schema: context.schema,
                }),
            };
    }
    function decodeDetachedNodes(encoded, context) {
        if (encoded === undefined || encoded.builds.length === 0) {
            return undefined;
        }
        const chunks = fieldsCodec.decode(encoded.trees, {
            encodeType: chunkCompressionStrategy,
        });
        const getChunk = (index) => {
            (0, core_utils_1.assert)(index < chunks.length, 0x898 /* out of bounds index for build chunk */);
            return (0, index_js_2.chunkFieldSingle)(chunks[index], index_js_2.defaultChunkPolicy);
        };
        const map = new Map();
        encoded.builds.forEach((build) => {
            // EncodedRevisionTag cannot be an array so this ensures that we can isolate the tuple
            const revision = build[1] === undefined ? undefined : revisionTagCodec.decode(build[1], context);
            map.set(revision, new Map(build[0].map(([i, n]) => [i, getChunk(n)])));
        });
        return map;
    }
    function encodeRevisionInfos(revisions, context) {
        const encodedRevisions = [];
        for (const revision of revisions) {
            const encodedRevision = {
                revision: revisionTagCodec.encode(revision.revision, context),
            };
            if (revision.rollbackOf !== undefined) {
                encodedRevision.rollbackOf = revisionTagCodec.encode(revision.rollbackOf, context);
            }
            encodedRevisions.push(encodedRevision);
        }
        return encodedRevisions;
    }
    function decodeRevisionInfos(revisions, context) {
        const decodedRevisions = [];
        for (const revision of revisions) {
            const decodedRevision = {
                revision: revisionTagCodec.decode(revision.revision, context),
            };
            if (revision.rollbackOf !== undefined) {
                decodedRevision.rollbackOf = revisionTagCodec.decode(revision.rollbackOf, context);
            }
            decodedRevisions.push(decodedRevision);
        }
        return decodedRevisions;
    }
    // TODO: use withSchemaValidation here to validate data against format.
    return {
        encode: (change, context) => {
            // Destroys only exist in rollback changesets, which are never sent.
            (0, core_utils_1.assert)(change.destroys === undefined, 0x899 /* Unexpected changeset with destroys */);
            return {
                maxId: change.maxId,
                revisions: change.revisions === undefined
                    ? change.revisions
                    : encodeRevisionInfos(change.revisions, context),
                changes: encodeFieldChangesForJson(change.fieldChanges, context),
                builds: encodeDetachedNodes(change.builds, context),
                refreshers: encodeDetachedNodes(change.refreshers, context),
            };
        },
        decode: (change, context) => {
            const encodedChange = change;
            const decoded = {
                fieldChanges: decodeFieldChangesFromJson(encodedChange.changes, context),
            };
            if (encodedChange.builds !== undefined) {
                decoded.builds = decodeDetachedNodes(encodedChange.builds, context);
            }
            if (encodedChange.refreshers !== undefined) {
                decoded.refreshers = decodeDetachedNodes(encodedChange.builds, context);
            }
            if (encodedChange.revisions !== undefined) {
                decoded.revisions = decodeRevisionInfos(encodedChange.revisions, context);
            }
            if (encodedChange.maxId !== undefined) {
                decoded.maxId = encodedChange.maxId;
            }
            return decoded;
        },
        encodedSchema: modularChangeFormat_js_1.EncodedModularChangeset,
    };
}
exports.makeV0Codec = makeV0Codec;
//# sourceMappingURL=modularChangeCodecs.js.map