"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setMetricAndDisplay = setMetricAndDisplay;
const get_with_default_1 = require("../../../../objects/get-with-default");
const util_1 = require("../../../../util");
/**
 * Sets a given metric and metricDisplayConfig on an entity's metric and view.metricDisplays props.
 *
 * @param entity - should have metric and metricDisplays implemented
 * @param metric - IMetric
 * @param displayConfig - IMetricDisplayConfig configuration to display the metric in the ui
 *
 * Right now, this just accepts a HubProject; in the future as more entities support metrics,
 * other entities can be allowed.
 */
function setMetricAndDisplay(entity, metric, displayConfig) {
    const entityCopy = (0, util_1.cloneObject)(entity);
    const metricId = metric.id;
    // get with default in case we have an undefined metrics array
    const metrics = (0, get_with_default_1.getWithDefault)(entityCopy, "metrics", []);
    const mIndex = metrics.findIndex((m) => m.id === metricId);
    // get array in case of undefined displays array
    const displays = (0, get_with_default_1.getWithDefault)(entityCopy, "view.metricDisplays", []);
    const dIndex = displays.findIndex((d) => d.metricId === metricId);
    // existing vs new metric
    if (mIndex > -1) {
        metrics[mIndex] = metric;
    }
    else {
        metrics.push(metric);
    }
    // existing vs new display
    if (dIndex > -1) {
        displays[dIndex] = displayConfig;
    }
    else {
        displays.push(displayConfig);
    }
    // reset the arrays
    entityCopy.view.metricDisplays = displays;
    entityCopy.metrics = metrics;
    return entityCopy;
}
//# sourceMappingURL=setMetricAndDisplay.js.map