"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveServiceQueryValues = void 0;
const arcgis_rest_feature_service_1 = require("@esri/arcgis-rest-feature-service");
const set_prop_1 = require("../../objects/set-prop");
const get_prop_1 = require("../../objects/get-prop");
/**
 * @internal
 * Resolve a dynamic value that is derived from a service query
 * @param valueDef Service Query Definition that will be resolved by executing an aggregation querying on service and returning that value
 * @param context ArcGIS context of the current user.
 * @returns
 */
const resolveServiceQueryValues = async (valueDef, context) => {
    // If no where is provided, default to "1=1"
    valueDef.options.where = valueDef.options.where || "1=1";
    // construct the result object
    const result = {};
    // Construct the stats definition
    const statsDef = {
        onStatisticField: valueDef.options.field,
        statisticType: valueDef.options.statisticType,
        outStatisticFieldName: valueDef.options.field,
    };
    // Execute the query
    const response = await (0, arcgis_rest_feature_service_1.queryFeatures)({
        url: valueDef.options.url,
        where: valueDef.options.where,
        f: "json",
        outStatistics: [statsDef],
        authentication: context.requestOptions.authentication,
    });
    // Pull the aggreate value out of the response
    const features = (0, get_prop_1.getProp)(response, "features") || [];
    const firstEntry = features[0] || {};
    const aggregate = (0, get_prop_1.getProp)(firstEntry, `attributes.${valueDef.options.field}`) || 0;
    // set that on the result
    (0, set_prop_1.setProp)(valueDef.outPath, aggregate, result);
    return result;
};
exports.resolveServiceQueryValues = resolveServiceQueryValues;
//# sourceMappingURL=resolveServiceQueryValues.js.map