"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ForestSummarizer = void 0;
const client_utils_1 = require("@fluid-internal/client-utils");
const shared_object_base_1 = require("@fluidframework/shared-object-base");
const core_1 = require("../core");
const treeTextCursor_1 = require("./treeTextCursor");
/**
 * The storage key for the blob in the summary containing tree data
 */
const treeBlobKey = "ForestTree";
/**
 * Provides methods for summarizing and loading a forest.
 */
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).
        (0, core_1.moveToDetachedField)(this.forest, this.cursor);
        const roots = (0, core_1.mapCursorField)(this.cursor, treeTextCursor_1.jsonableTreeFromCursor);
        this.cursor.clear();
        return stringify(roots);
    }
    getAttachSummary(stringify, fullTree, trackState, telemetryContext) {
        return (0, shared_object_base_1.createSingleBlobSummary)(treeBlobKey, this.getTreeString(stringify));
    }
    async summarize(stringify, fullTree, trackState, telemetryContext) {
        return (0, shared_object_base_1.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 = (0, client_utils_1.bufferToString)(treeBuffer, "utf8");
            const jsonableTree = parse(treeBufferString);
            (0, core_1.initializeForest)(this.forest, jsonableTree.map(treeTextCursor_1.singleTextCursor));
        }
    }
}
exports.ForestSummarizer = ForestSummarizer;
//# sourceMappingURL=forestSummarizer.js.map