"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enrichEntity = void 0;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const parseInclude_1 = require("../search/_internal/parseInclude");
const util_1 = require("../util");
const get_prop_1 = require("../objects/get-prop");
const set_prop_1 = require("../objects/set-prop");
const map_by_1 = require("../utils/map-by");
/**
 * Function to enrich an entity with information that
 * requires an additional XHR
 *
 * @param entity Hub entity
 * @param include Array of enrichment strings
 * @param requestOptions Hub request options
 */
const enrichEntity = async (entity, include, requestOptions) => {
    const specs = include.map(parseInclude_1.parseInclude);
    const enrichments = (0, map_by_1.mapBy)("enrichment", specs).filter(util_1.unique);
    // delegate to fetch enrichments if any have been defined
    let enrichmentResults = {};
    if (enrichments.length) {
        enrichmentResults = await fetchEntityEnrichments(entity, enrichments, requestOptions);
    }
    // add the enrichments back to the entity based on the enrichment spec
    specs.forEach((spec) => {
        (0, set_prop_1.setProp)(spec.prop, (0, get_prop_1.getProp)(enrichmentResults, spec.path), entity);
    });
    return entity;
};
exports.enrichEntity = enrichEntity;
/**
 * This function delegates out to other helper functions
 * to fetch the entity enrichments.
 */
const fetchEntityEnrichments = async (entity, enrichments, requestOptions) => {
    // Note: we chose to keep this simple for now and not create
    // an operation pipeline - if this becomes more widely used
    // or we run into issues debugging, we can implement
    const operations = enrichments.reduce((ops, enrichment) => {
        const operation = {
            followersGroup: fetchFollowersGroupEnrichment,
        }[enrichment];
        // if you are updating this file, remove this comment and address the lint error
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        operation && ops.push({ enrichment, operation });
        return ops;
    }, []);
    const enrichmentFns = operations.map(({ operation }) => operation(entity, requestOptions));
    const enrichmentResults = await Promise.all(enrichmentFns);
    return enrichmentResults.reduce((acc, result, idx) => {
        acc[operations[idx].enrichment] = result;
        return acc;
    }, {});
};
/**
 * fetch the entity's followers group
 */
const fetchFollowersGroupEnrichment = async (entity, requestOptions) => {
    let group = {};
    try {
        const followersGroupId = (0, get_prop_1.getProp)(entity, "followersGroupId");
        if (followersGroupId) {
            group = await (0, arcgis_rest_portal_1.getGroup)(followersGroupId, requestOptions);
        }
    }
    catch (_error) {
        return {};
    }
    return group;
};
//# sourceMappingURL=enrichEntity.js.map