"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InfraEnvFormPage = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const Yup = tslib_1.__importStar(require("yup"));
const react_core_1 = require("@patternfly/react-core");
const formik_1 = require("formik");
const external_link_alt_icon_1 = require("@patternfly/react-icons/dist/js/icons/external-link-alt-icon");
const common_1 = require("../../../common");
require("./infra-env.css");
const utils_1 = require("../../../common/utils");
const use_translation_wrapper_1 = require("../../../common/hooks/use-translation-wrapper");
const CpuArchitectureDropdown_1 = tslib_1.__importDefault(require("../common/CpuArchitectureDropdown"));
const InfraEnvOpenShiftVersionDropdown_1 = tslib_1.__importDefault(require("./InfraEnvOpenShiftVersionDropdown"));
const validationSchema = (usedNames, t) => Yup.lazy((values) => Yup.object().shape({
    name: (0, common_1.richNameValidationSchema)(t, usedNames),
    location: (0, common_1.locationValidationSchema)(t),
    pullSecret: (0, common_1.pullSecretValidationSchema)(t).required(t('ai:Required field')),
    sshPublicKey: (0, common_1.sshPublicKeyValidationSchema)(t),
    httpProxy: (0, common_1.httpProxyValidationSchema)({
        values,
        pairValueName: 'httpsProxy',
        allowEmpty: true,
        t,
    }),
    httpsProxy: (0, common_1.httpProxyValidationSchema)({
        values,
        pairValueName: 'httpProxy',
        allowEmpty: true,
        t,
    }), // share the schema, httpS is currently not supported
    noProxy: (0, common_1.noProxyValidationSchema)(t),
    labels: Yup.array()
        .of(Yup.string())
        .test('label-equals-validation', t('ai:Label needs to be in a `key=value` form'), (values) => values.every((value) => {
        const parts = value.split('=');
        return parts.length === 2;
    })),
    additionalNtpSources: (0, common_1.ntpSourceValidationSchema)(t),
}));
const initialValues = {
    name: '',
    location: '',
    pullSecret: '',
    sshPublicKey: '',
    httpProxy: '',
    httpsProxy: '',
    noProxy: '',
    enableProxy: false,
    labels: [],
    networkType: 'dhcp',
    cpuArchitecture: common_1.CpuArchitecture.x86,
    enableNtpSources: false,
    additionalNtpSources: '',
    osImageVersion: '',
};
const InfraEnvForm = ({ onValuesChanged, children, pullSecret, sshPublicKey, docVersion, osImages, }) => {
    const { values, setFieldValue } = (0, formik_1.useFormikContext)();
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    React.useEffect(() => onValuesChanged === null || onValuesChanged === void 0 ? void 0 : onValuesChanged(values), [onValuesChanged, values]);
    React.useEffect(() => {
        setFieldValue('pullSecret', pullSecret);
        setFieldValue('sshPublicKey', sshPublicKey);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pullSecret, sshPublicKey]);
    return (React.createElement(react_core_1.Stack, { hasGutter: true },
        React.createElement(react_core_1.StackItem, null, t('ai:Infrastructure environments are used by clusters. Create an infrastructure environment to add resources to your cluster.')),
        React.createElement(react_core_1.StackItem, null,
            React.createElement(react_core_1.Form, null,
                React.createElement(common_1.RichInputField, { label: t('ai:Name'), name: "name", isRequired: true, richValidationMessages: (0, common_1.nameValidationMessages)(t), placeholder: t('ai:Enter infrastructure environment name') }),
                React.createElement(react_core_1.FormGroup, { fieldId: "network-type", label: t('ai:Network type'), labelHelp: React.createElement(common_1.PopoverIcon, { noVerticalAlign: true, bodyContent: React.createElement(React.Fragment, null, t('ai:This will determine for the infrastructure environment which kind of hosts would be able to be added. If the hosts that you want to add are using DHCP server, select this option, else, select the static IP.')) }) },
                    React.createElement(react_core_1.Flex, { justifyContent: { default: 'justifyContentFlexStart' } },
                        React.createElement(react_core_1.FlexItem, null,
                            React.createElement(common_1.RadioField, { name: "networkType", id: "dhcp", value: "dhcp", label: t('ai:DHCP only') })),
                        React.createElement(react_core_1.FlexItem, { spacer: { default: 'spacer4xl' } }),
                        React.createElement(react_core_1.FlexItem, null,
                            React.createElement(common_1.RadioField, { name: "networkType", id: "static-ip", value: "static", label: React.createElement(React.Fragment, null,
                                    t('ai:Static IP, bridges and bonds'),
                                    "\u00A0",
                                    React.createElement(common_1.PopoverIcon, { noVerticalAlign: true, bodyContent: React.createElement(react_core_1.Stack, { hasGutter: true },
                                            React.createElement(react_core_1.StackItem, null, t('ai:To use static network configuration, follow the steps listed in the documentation.')),
                                            React.createElement(react_core_1.StackItem, null,
                                                React.createElement(react_core_1.Button, { variant: "link", icon: React.createElement(external_link_alt_icon_1.ExternalLinkAltIcon, null), iconPosition: "right", isInline: true, onClick: () => window.open((0, common_1.getOCPStaticIPDocLink)(docVersion), '_blank', 'noopener') }, t('ai:View documentation')))) })) })))),
                React.createElement(CpuArchitectureDropdown_1.default, null),
                !!osImages && React.createElement(InfraEnvOpenShiftVersionDropdown_1.default, { osImages: osImages }),
                React.createElement(common_1.RichInputField, { label: t('ai:Location'), name: "location", isRequired: true, richValidationMessages: (0, common_1.locationValidationMessages)(t), placeholder: t('ai:Enter geographic location for the environment'), helperText: t("ai:Used to describe hosts' physical location. Helps for quicker host selection during cluster creation.") }),
                React.createElement(common_1.LabelField, { label: t('ai:Labels'), name: "labels" }),
                children,
                React.createElement(common_1.PullSecretField, { isOcm: false }),
                React.createElement(common_1.UploadSSH, null),
                React.createElement(common_1.ProxyFields, null),
                React.createElement(common_1.CheckboxField, { label: t('ai:Add your own NTP (Network Time Protocol) sources'), name: "enableNtpSources", helperText: React.createElement("p", null, t('ai:Configure your own NTP sources to synchronize the time between the hosts that will be added to this infrastructure environment.')), body: values.enableNtpSources && (React.createElement(react_core_1.Grid, { hasGutter: true },
                        React.createElement(common_1.AdditionalNTPSourcesField, { name: "additionalNtpSources", helperText: t('ai:A comma separated list of IP or domain names of the NTP pools or servers.') }))) })))));
};
const InfraEnvFormPage = (_a) => {
    var { usedNames, onSubmit, onClose, onFinish, formRef, children } = _a, rest = tslib_1.__rest(_a, ["usedNames", "onSubmit", "onClose", "onFinish", "formRef", "children"]);
    const [error, setError] = React.useState();
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    return (React.createElement(formik_1.Formik, { initialValues: initialValues, initialStatus: { error: null }, validate: (0, common_1.getRichTextValidation)(validationSchema(usedNames, t)), onSubmit: (values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            try {
                yield (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(values));
                onFinish === null || onFinish === void 0 ? void 0 : onFinish(values);
            }
            catch (e) {
                setError((0, utils_1.getErrorMessage)(e));
            }
        }), innerRef: formRef }, ({ isValid, isSubmitting, submitForm }) => (React.createElement(react_core_1.Stack, { hasGutter: true },
        React.createElement(react_core_1.StackItem, null, onSubmit && onClose ? (React.createElement(react_core_1.Grid, { hasGutter: true, span: 8 },
            React.createElement(react_core_1.GridItem, null,
                React.createElement(react_core_1.Title, { headingLevel: "h1", size: react_core_1.TitleSizes.xl }, t('ai:Configure environment'))),
            React.createElement(react_core_1.GridItem, null,
                React.createElement(InfraEnvForm, Object.assign({}, rest), children)))) : (React.createElement("div", { className: "infra-env__form" },
            React.createElement(InfraEnvForm, Object.assign({}, rest), children)))),
        error && (React.createElement(react_core_1.StackItem, null,
            React.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, actionClose: React.createElement(react_core_1.AlertActionCloseButton, { onClose: () => setError(undefined) }), title: t('ai:Error creating InfraEnv') }, error))),
        onSubmit && onClose && (React.createElement(react_core_1.StackItem, null,
            React.createElement(React.Fragment, null,
                React.createElement(react_core_1.Button, { variant: "primary", type: "submit", isDisabled: !isValid || isSubmitting, 
                    // eslint-disable-next-line @typescript-eslint/no-misused-promises
                    onClick: submitForm },
                    t('ai:Create'),
                    " ",
                    isSubmitting && React.createElement(react_core_1.Spinner, { size: "md" })),
                React.createElement(react_core_1.Button, { variant: "link", onClick: onClose, isDisabled: isSubmitting }, t('ai:Cancel')))))))));
};
exports.InfraEnvFormPage = InfraEnvFormPage;
//# sourceMappingURL=InfraEnvFormPage.js.map