"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeDetachedNodeToFieldCodec = void 0;
const core_utils_1 = require("@fluidframework/core-utils");
const util_1 = require("../../util");
const detachedFieldIndexFormat_1 = require("./detachedFieldIndexFormat");
function makeDetachedNodeToFieldCodec({ jsonValidator: validator, }) {
    const versionedValidator = validator.compile(detachedFieldIndexFormat_1.Versioned);
    const formatValidator = validator.compile(detachedFieldIndexFormat_1.Format);
    return {
        encode: (data) => {
            const detachedNodeToFieldData = [];
            (0, util_1.forEachInNestedMap)(data.data, (root, key1, key2) => {
                detachedNodeToFieldData.push([key1, key2, root]);
            });
            const encoded = {
                version: detachedFieldIndexFormat_1.version,
                data: detachedNodeToFieldData,
                maxId: data.maxId,
            };
            (0, core_utils_1.assert)(versionedValidator.check(encoded), 0x7ff /* Encoded detachedNodeToField data should be versioned */);
            (0, core_utils_1.assert)(formatValidator.check(encoded), 0x800 /* Encoded schema should validate */);
            return JSON.stringify(encoded);
        },
        decode: (data) => {
            const parsed = JSON.parse(data);
            if (!versionedValidator.check(parsed)) {
                (0, util_1.fail)("invalid serialized data: did not have a version");
            }
            // When more versions exist, we can switch on the version here.
            if (parsed.version !== detachedFieldIndexFormat_1.version) {
                (0, util_1.fail)("Unexpected version for serialized data");
            }
            if (!formatValidator.check(parsed)) {
                (0, util_1.fail)("Serialized data failed validation");
            }
            const map = new Map();
            for (const [major, minor, root] of parsed.data) {
                (0, util_1.setInNestedMap)(map, major, minor, root);
            }
            return {
                data: map,
                maxId: parsed.maxId,
            };
        },
    };
}
exports.makeDetachedNodeToFieldCodec = makeDetachedNodeToFieldCodec;
//# sourceMappingURL=detachedFieldIndexCodec.js.map