/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { bufferToString } from "@fluid-internal/client-utils";
import { createSingleBlobSummary } from "@fluidframework/shared-object-base";
import { assert, unreachableCase } from "@fluidframework/core-utils";
import { applyDelta, makeDetachedFieldIndex, mapCursorField, mapCursorFields, } from "../core";
import { idAllocatorFromMaxId } from "../util";
import { noopValidator } from "../codec";
import { decode, schemaCompressedEncode, uncompressedEncode } from "./chunked-forest";
import { TreeCompressionStrategy } from "./treeCompressionUtils";
import { makeForestSummarizerCodec } from "./forestSummarizerCodec";
/**
 * The storage key for the blob in the summary containing tree data
 */
const treeBlobKey = "ForestTree";
/**
 * Provides methods for summarizing and loading a forest.
 */
export class ForestSummarizer {
    constructor(forest, schema, policy, encodeType = TreeCompressionStrategy.Compressed, options) {
        this.forest = forest;
        this.key = "Forest";
        this.schema = schema;
        this.policy = policy;
        this.encodeType = encodeType;
        this.options = options ?? { jsonValidator: noopValidator };
        this.codec = makeForestSummarizerCodec(this.options);
    }
    /**
     * Synchronous monolithic summarization of tree content.
     *
     * TODO: when perf matters, this should be replaced with a chunked async version using a binary format.
     *
     * @returns a snapshot of the forest's tree as a string.
     */
    getTreeString(stringify) {
        const rootCursor = this.forest.getCursorAboveDetachedFields();
        // TODO: Encode all detached fields in one operation for better performance and compression
        const fields = mapCursorFields(rootCursor, (cursor) => [
            rootCursor.getFieldKey(),
            encodeSummary(cursor, this.schema, this.policy, this.encodeType),
        ]);
        return stringify(this.codec.encode(fields));
    }
    getAttachSummary(stringify, fullTree, trackState, telemetryContext) {
        return createSingleBlobSummary(treeBlobKey, this.getTreeString(stringify));
    }
    async summarize(stringify, fullTree, trackState, telemetryContext) {
        return createSingleBlobSummary(treeBlobKey, this.getTreeString(stringify));
    }
    getGCData(fullGC) {
        // TODO: Properly implement garbage collection. Right now, garbage collection is performed automatically
        // by the code in SharedObject (from which SharedTreeCore extends). The `runtime.uploadBlob` API delegates
        // to the `BlobManager`, which automatically populates the summary with ISummaryAttachment entries for each
        // blob.
        return {
            gcNodes: {},
        };
    }
    async load(services, parse) {
        if (await services.contains(treeBlobKey)) {
            const treeBuffer = await services.readBlob(treeBlobKey);
            const treeBufferString = bufferToString(treeBuffer, "utf8");
            // TODO: this code is parsing data without an optional validator, this should be defined in a typebox schema as part of the
            // forest summary format.
            const fields = this.codec.decode(parse(treeBufferString));
            const allocator = idAllocatorFromMaxId();
            const fieldChanges = fields.map(([fieldKey, content]) => {
                const nodeCursors = mapCursorField(decode(content).cursor(), (cursor) => cursor.fork());
                const buildId = { minor: allocator.allocate(nodeCursors.length) };
                return [
                    fieldKey,
                    {
                        build: [
                            {
                                id: buildId,
                                trees: nodeCursors,
                            },
                        ],
                        local: [{ count: nodeCursors.length, attach: buildId }],
                    },
                ];
            });
            assert(this.forest.isEmpty, 0x797 /* forest must be empty */);
            applyDelta({ fields: new Map(fieldChanges) }, this.forest, makeDetachedFieldIndex("init"));
        }
    }
}
function encodeSummary(cursor, schema, policy, encodeType) {
    switch (encodeType) {
        case TreeCompressionStrategy.Compressed:
            return schemaCompressedEncode(schema, policy, cursor);
        case TreeCompressionStrategy.Uncompressed:
            return uncompressedEncode(cursor);
        default:
            unreachableCase(encodeType);
    }
}
//# sourceMappingURL=forestSummarizer.js.map