"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClusterDeploymentHostsDiscoveryStep = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const uniq_js_1 = tslib_1.__importDefault(require("lodash-es/uniq.js"));
const react_core_1 = require("@patternfly/react-core");
const common_1 = require("../../../../common");
const ClusterDeploymentHostsDiscovery_1 = tslib_1.__importDefault(require("./ClusterDeploymentHostsDiscovery"));
const helpers_1 = require("../helpers");
const helpers_2 = require("../../helpers");
const wizardTransition_1 = require("../wizardTransition");
const use_translation_wrapper_1 = require("../../../../common/hooks/use-translation-wrapper");
const ValidationSection_1 = require("../components/ValidationSection");
const ClusterDeploymentWizardContext_1 = require("../ClusterDeploymentWizardContext");
const ClusterDeploymentHostsDiscoveryStep = (_a) => {
    var { agentClusterInstall, agents: allAgents, infraEnv, onSaveHostsDiscovery } = _a, rest = tslib_1.__rest(_a, ["agentClusterInstall", "agents", "infraEnv", "onSaveHostsDiscovery"]);
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const { syncError } = react_1.default.useContext(ClusterDeploymentWizardContext_1.ClusterDeploymentWizardContext);
    const { activeStep, goToNextStep, goToPrevStep, close } = (0, react_core_1.useWizardContext)();
    const [showClusterErrors, setShowClusterErrors] = react_1.default.useState(false);
    const [nextRequested, setNextRequested] = react_1.default.useState(false);
    const [showFormErrors, setShowFormErrors] = react_1.default.useState(false);
    const infraEnvAgents = react_1.default.useMemo(() => allAgents.filter((a) => (0, helpers_1.isAgentOfInfraEnv)(infraEnv, a)), [allAgents, infraEnv]);
    const usedHostnames = react_1.default.useMemo(() => (0, helpers_1.getAgentsHostsNames)(infraEnvAgents), [infraEnvAgents]);
    const errors = [];
    if ((0, helpers_2.getIsSNOCluster)(agentClusterInstall)) {
        infraEnvAgents.length > 1 &&
            errors.push(t('ai:Single node cluster cannot contain more than 1 host.'));
    }
    else {
        infraEnvAgents.length < 3 && errors.push(t('ai:Cluster must have at least 3 hosts.'));
    }
    if (infraEnvAgents.some((a) => !a.spec.approved)) {
        errors.push(t('ai:All hosts must be approved.'));
    }
    if (usedHostnames.some((h) => h === 'localhost')) {
        errors.push(t('ai:Hostname localhost is forbidden.'));
    }
    if ((0, uniq_js_1.default)(usedHostnames).length !== usedHostnames.length) {
        errors.push(t('ai:Hostnames must be unique.'));
    }
    const agentsNotHealthy = infraEnvAgents
        .map((agent) => (0, helpers_2.getWizardStepAgentStatus)(agent, 'hosts-discovery', t).status.key)
        .some((status) => ['disconnected', 'disabled', 'error', 'insufficient', 'cancelled'].includes(status));
    if (agentsNotHealthy) {
        errors.push(t('ai:Some hosts are not ready.'));
    }
    const onNext = react_1.default.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if (!showFormErrors) {
            setShowFormErrors(true);
            if (errors.length) {
                return;
            }
        }
        yield onSaveHostsDiscovery();
        setNextRequested(true);
    }), [errors.length, onSaveHostsDiscovery, showFormErrors]);
    react_1.default.useEffect(() => {
        setNextRequested(false);
        setShowClusterErrors(false);
    }, [infraEnvAgents.length]);
    react_1.default.useEffect(() => {
        if (nextRequested) {
            if (agentsNotHealthy) {
                setNextRequested(false);
            }
            else {
                setShowClusterErrors(true);
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                if ((0, wizardTransition_1.canNextFromHostDiscoveryStep)(agentClusterInstall, infraEnvAgents)) {
                    void goToNextStep();
                }
            }
        }
    }, [nextRequested, infraEnvAgents, agentClusterInstall, agentsNotHealthy, goToNextStep]);
    const submittingText = react_1.default.useMemo(() => (nextRequested && !showClusterErrors ? t('ai:Saving changes...') : undefined), [nextRequested, showClusterErrors, t]);
    react_1.default.useEffect(() => {
        if (syncError) {
            setNextRequested(false);
        }
    }, [syncError]);
    const footer = react_1.default.useMemo(() => (react_1.default.createElement(react_core_1.WizardFooter, { activeStep: activeStep, onNext: onNext, isNextDisabled: nextRequested || (showFormErrors ? !!errors.length : false), nextButtonText: submittingText || t('ai:Next'), nextButtonProps: { isLoading: !!submittingText }, onBack: goToPrevStep, onClose: close })), [
        activeStep,
        close,
        errors.length,
        goToPrevStep,
        nextRequested,
        onNext,
        showFormErrors,
        submittingText,
        t,
    ]);
    (0, react_core_1.useWizardFooter)(footer);
    return (react_1.default.createElement(react_core_1.Grid, { hasGutter: true },
        react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(common_1.ClusterWizardStepHeader, null, t('ai:Cluster hosts'))),
        react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(ClusterDeploymentHostsDiscovery_1.default, Object.assign({ agentClusterInstall: agentClusterInstall, agents: infraEnvAgents, infraEnv: infraEnv, usedHostnames: usedHostnames }, rest))),
        showClusterErrors && !!errors.length && (react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(common_1.Alerts, null))),
        showFormErrors && !!errors.length && (react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:Provided cluster configuration is not valid'), isInline: true },
            react_1.default.createElement(react_core_1.List, null, errors.map((error) => (react_1.default.createElement(react_core_1.ListItem, { key: error }, error)))))),
        !!syncError && (react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(ValidationSection_1.ValidationSection, { currentStepId: 'hosts-selection', hosts: [] },
                react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:An error occurred'), isInline: true }, syncError))))));
};
exports.ClusterDeploymentHostsDiscoveryStep = ClusterDeploymentHostsDiscoveryStep;
//# sourceMappingURL=ClusterDeploymentHostsDiscoveryStep.js.map