"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAgentsAutoSelection = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const formik_1 = require("formik");
const isEqual_js_1 = tslib_1.__importDefault(require("lodash-es/isEqual.js"));
const constants_1 = require("../common/constants");
const useAgentsAutoSelection = (availableAgents) => {
    const { setFieldValue, values } = (0, formik_1.useFormikContext)();
    const { hostCount, locations, autoSelectedHostIds } = values;
    const [matchingAgents, selectedAgents] = react_1.default.useMemo(() => {
        const mAgents = availableAgents.filter((agent) => {
            var _a, _b;
            const agentLocation = ((_b = (_a = agent.metadata) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b[constants_1.AGENT_LOCATION_LABEL_KEY]) || constants_1.AGENT_NOLOCATION_VALUE;
            return locations.length ? locations.includes(agentLocation) : true;
        });
        const sAgents = mAgents.filter((a) => { var _a; return autoSelectedHostIds.includes(((_a = a.metadata) === null || _a === void 0 ? void 0 : _a.uid) || ''); });
        return [mAgents, sAgents];
    }, [availableAgents, locations, autoSelectedHostIds]);
    react_1.default.useEffect(() => {
        const ids = matchingAgents.map((a) => { var _a; return (_a = a.metadata) === null || _a === void 0 ? void 0 : _a.uid; }).splice(0, hostCount);
        if (!(0, isEqual_js_1.default)(ids, autoSelectedHostIds)) {
            setTimeout(() => setFieldValue('autoSelectedHostIds', ids, true));
        }
    }, [matchingAgents, setFieldValue, autoSelectedHostIds, hostCount]);
    return { matchingAgents, selectedAgents, hostCount };
};
exports.useAgentsAutoSelection = useAgentsAutoSelection;
//# sourceMappingURL=AgentsSelectionUtils.js.map