/*!
 * 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 { initializeForest, mapCursorField, moveToDetachedField, } from "../core";
import { jsonableTreeFromCursor, singleTextCursor } from "./treeTextCursor";
/**
 * 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) {
        this.forest = forest;
        this.key = "Forest";
        this.cursor = this.forest.allocateCursor();
    }
    /**
     * 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) {
        // TODO: maybe assert there are no other roots
        // (since we don't save them, and they should not exist outside transactions).
        moveToDetachedField(this.forest, this.cursor);
        const roots = mapCursorField(this.cursor, jsonableTreeFromCursor);
        this.cursor.clear();
        return stringify(roots);
    }
    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");
            const jsonableTree = parse(treeBufferString);
            initializeForest(this.forest, jsonableTree.map(singleTextCursor));
        }
    }
}
//# sourceMappingURL=forestSummarizer.js.map