"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeDetachedFieldIndexCodecFromMajorCodec = void 0;
const index_js_1 = require("../../util/index.js");
const detachedFieldIndexFormatCommon_js_1 = require("./detachedFieldIndexFormatCommon.js");
// Return type is intentionally derived.
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function makeDetachedFieldIndexCodecFromMajorCodec(majorCodec, version, encodedRevisionTagSchema) {
    const formatSchema = (0, detachedFieldIndexFormatCommon_js_1.Format)(version, encodedRevisionTagSchema);
    return {
        schema: formatSchema,
        encode: (data) => {
            const rootsForRevisions = [];
            for (const [major, innerMap] of data.data) {
                const encodedRevision = majorCodec.encode(major);
                const rootRanges = [];
                for (const [minor, detachedField] of innerMap) {
                    rootRanges.push([minor, detachedField.root]);
                }
                if ((0, index_js_1.hasSingle)(rootRanges)) {
                    const firstRootRange = rootRanges[0];
                    const rootsForRevision = [
                        encodedRevision,
                        firstRootRange[0],
                        firstRootRange[1],
                    ];
                    rootsForRevisions.push(rootsForRevision);
                }
                else {
                    const rootsForRevision = [encodedRevision, rootRanges];
                    rootsForRevisions.push(rootsForRevision);
                }
            }
            const encoded = {
                version,
                data: rootsForRevisions,
                maxId: data.maxId,
            };
            return encoded;
        },
        decode: (parsed) => {
            const map = new Map();
            for (const rootsForRevision of parsed.data) {
                const innerMap = new Map();
                if (rootsForRevision.length === 2) {
                    for (const [minor, root] of rootsForRevision[1]) {
                        innerMap.set(minor, { root });
                    }
                }
                else {
                    innerMap.set(rootsForRevision[1], { root: rootsForRevision[2] });
                }
                const revision = rootsForRevision[0];
                map.set(majorCodec.decode(revision), innerMap);
            }
            return {
                data: map,
                maxId: parsed.maxId,
            };
        },
    };
}
exports.makeDetachedFieldIndexCodecFromMajorCodec = makeDetachedFieldIndexCodecFromMajorCodec;
//# sourceMappingURL=detachedFieldIndexCodecCommon.js.map