"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.detachedFieldSlot = exports.treeStatusFromAnchorCache = exports.treeStatusFromDetachedField = void 0;
const core_1 = require("../../core");
const flexTreeTypes_1 = require("./flexTreeTypes");
/**
 * Checks the detached field and returns the TreeStatus based on whether or not the detached field is a root field.
 * @param detachedField - the detached field you want to check.
 * @returns the {@link TreeStatus} from the detached field provided.
 */
function treeStatusFromDetachedField(detachedField) {
    return detachedField === core_1.rootField ? flexTreeTypes_1.TreeStatus.InDocument : flexTreeTypes_1.TreeStatus.Removed;
}
exports.treeStatusFromDetachedField = treeStatusFromDetachedField;
/**
 * Determines the tree status based on the anchor cache.
 *
 * Checks the anchorNode's cache to get the tree status.
 * If the cache is undefined or stale, it is updated and the treeStatus based on its detachedField is returned.
 *
 * @param anchors - the {@link AnchorSet} to compare your anchorNode cache to.
 * @param anchorNode - the {@link AnchorNode} to get the {@link TreeStatus} of.
 * @returns - the {@link TreeStatus} of the anchorNode provided.
 */
function treeStatusFromAnchorCache(anchors, anchorNode) {
    const cache = anchorNode.slots.get(exports.detachedFieldSlot);
    if (cache === undefined) {
        // If the cache is undefined, set the cache and return the treeStatus based on the detached field.
        return treeStatusFromDetachedField(getCachedUpdatedDetachedField(anchorNode, anchors.generationNumber));
    }
    else {
        // If the cache is up to date, return the treeStatus based on the cached detached field.
        const currentGenerationNumber = anchors.generationNumber;
        if (cache.generationNumber === currentGenerationNumber) {
            return treeStatusFromDetachedField(cache.detachedField);
        }
        // If the cache is not up to date, update the cache and return the treeStatus based on the updated detached field.
        return treeStatusFromDetachedField(getCachedUpdatedDetachedField(anchorNode, currentGenerationNumber));
    }
}
exports.treeStatusFromAnchorCache = treeStatusFromAnchorCache;
/**
 * Updates the anchorNode cache with the provided generation number, and returns its detachedField.
 */
function getCachedUpdatedDetachedField(anchorNode, generationNumber) {
    const detachedField = (0, core_1.getDetachedFieldContainingPath)(anchorNode);
    anchorNode.slots.set(exports.detachedFieldSlot, {
        generationNumber,
        detachedField,
    });
    return detachedField;
}
exports.detachedFieldSlot = (0, core_1.anchorSlot)();
//# sourceMappingURL=utilities.js.map