"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const Yup = tslib_1.__importStar(require("yup"));
const react_core_1 = require("@patternfly/react-core");
const formik_1 = require("formik");
const ScaleUpForm_1 = tslib_1.__importDefault(require("../ClusterDeployment/ScaleUpForm"));
const clusterDeployment_1 = require("../helpers/clusterDeployment");
const EditAgentModal_1 = tslib_1.__importDefault(require("./EditAgentModal"));
const helpers_1 = require("../ClusterDeployment/helpers");
const utils_1 = require("../../../common/utils");
const use_translation_wrapper_1 = require("../../../common/hooks/use-translation-wrapper");
const helpers_2 = require("../helpers");
const getAgentsToAdd = (selectedHostIds, agents) => agents.filter((agent) => {
    var _a, _b, _c, _d, _e;
    return selectedHostIds.includes(((_a = agent.metadata) === null || _a === void 0 ? void 0 : _a.uid) || '') &&
        !(((_c = (_b = agent.spec) === null || _b === void 0 ? void 0 : _b.clusterDeploymentName) === null || _c === void 0 ? void 0 : _c.name) || ((_e = (_d = agent.spec) === null || _d === void 0 ? void 0 : _d.clusterDeploymentName) === null || _e === void 0 ? void 0 : _e.namespace));
});
const getValidationSchema = (agentsCount) => {
    return Yup.lazy((values) => {
        return Yup.object().shape({
            hostCount: Yup.number().min(1).max(agentsCount),
            autoSelectedHostIds: values.autoSelectHosts
                ? Yup.array(Yup.string()).min(1).max(agentsCount)
                : Yup.array(Yup.string()),
            selectedHostIds: values.autoSelectHosts
                ? Yup.array(Yup.string())
                : Yup.array(Yup.string()).min(1).max(agentsCount),
        });
    });
};
const ScaleUpModal = ({ isOpen, onClose, addHostsToCluster, clusterDeployment, agents, bareMetalHosts, onChangeHostname, onChangeBMHHostname, onSetInstallationDiskId, isNutanix, onEditHostRole, }) => {
    const [editAgent, setEditAgent] = react_1.default.useState();
    const [error, setError] = react_1.default.useState();
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const getInitialValues = () => {
        var _a;
        const agentSelector = (0, clusterDeployment_1.getAgentSelectorFieldsFromAnnotations)((_a = clusterDeployment === null || clusterDeployment === void 0 ? void 0 : clusterDeployment.metadata) === null || _a === void 0 ? void 0 : _a.annotations);
        const autoSelectHosts = agentSelector.autoSelect;
        return {
            autoSelectHosts,
            hostCount: 1,
            agentLabels: agentSelector.labels,
            locations: agentSelector.locations,
            cpuArchitecture: (0, clusterDeployment_1.getClusterDeploymentCpuArchitecture)(clusterDeployment),
            selectedHostIds: [],
            autoSelectedHostIds: [],
        };
    };
    const validationSchema = react_1.default.useMemo(() => getValidationSchema(agents.length), [agents.length]);
    const handleSubmit = (values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        const { autoSelectHosts, autoSelectedHostIds, selectedHostIds } = values;
        try {
            setError(undefined);
            const agentsToAdd = getAgentsToAdd(autoSelectHosts ? autoSelectedHostIds : selectedHostIds, agents);
            yield addHostsToCluster(agentsToAdd);
            onClose();
        }
        catch (e) {
            setError((0, utils_1.getErrorMessage)(e));
        }
    });
    const clusterAgents = agents.filter((a) => {
        var _a, _b, _c, _d;
        return ((_a = a.spec.clusterDeploymentName) === null || _a === void 0 ? void 0 : _a.name) === ((_b = clusterDeployment.metadata) === null || _b === void 0 ? void 0 : _b.name) &&
            ((_c = a.spec.clusterDeploymentName) === null || _c === void 0 ? void 0 : _c.namespace) === ((_d = clusterDeployment.metadata) === null || _d === void 0 ? void 0 : _d.namespace);
    });
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(react_core_1.Modal, { "aria-label": t('ai:Add host dialog'), isOpen: isOpen, onClose: onClose, id: "scale-up-modal" },
            react_1.default.createElement(react_core_1.ModalHeader, { title: t('ai:Add hosts') }),
            react_1.default.createElement(formik_1.Formik, { initialValues: getInitialValues(), validationSchema: validationSchema, onSubmit: handleSubmit, validateOnMount: true }, ({ isSubmitting, isValid, submitForm }) => {
                return (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(react_core_1.ModalBody, null,
                        react_1.default.createElement(react_core_1.Stack, { hasGutter: true },
                            react_1.default.createElement(react_core_1.StackItem, null,
                                react_1.default.createElement(ScaleUpForm_1.default, { agents: agents, onEditHost: setEditAgent, onEditRole: onEditHostRole, onSetInstallationDiskId: onSetInstallationDiskId, isNutanix: isNutanix })),
                            error && (react_1.default.createElement(react_core_1.StackItem, null,
                                react_1.default.createElement(react_core_1.Alert, { title: t('ai:Failed to add hosts to the cluster'), variant: react_core_1.AlertVariant.danger, actionClose: react_1.default.createElement(react_core_1.AlertActionCloseButton, { onClose: () => setError(undefined) }), isInline: true }, error))))),
                    react_1.default.createElement(react_core_1.ModalFooter, null,
                        react_1.default.createElement(react_core_1.Button, { onClick: submitForm, isDisabled: isSubmitting || !isValid }, t('ai:Submit')),
                        react_1.default.createElement(react_core_1.Button, { onClick: onClose, variant: react_core_1.ButtonVariant.secondary }, t('ai:Cancel')))));
            })),
        editAgent && (react_1.default.createElement(EditAgentModal_1.default, { agent: editAgent, onClose: () => setEditAgent(undefined), onSave: (0, helpers_2.onAgentChangeHostname)(agents, bareMetalHosts, onChangeHostname, onChangeBMHHostname), usedHostnames: (0, helpers_1.getAgentsHostsNames)(clusterAgents) }))));
};
exports.default = ScaleUpModal;
//# sourceMappingURL=ScaleUpModal.js.map