"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CimConfigurationModal = 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 parse_url_1 = tslib_1.__importDefault(require("parse-url"));
const use_translation_wrapper_1 = require("../../../../common/hooks/use-translation-wrapper");
const helpers_1 = require("../../helpers");
const utils_1 = require("../../../../common/utils");
const persist_1 = require("./persist");
const CimConfigDisconnectedAlert_1 = require("./CimConfigDisconnectedAlert");
const constants_1 = require("./constants");
const utils_2 = require("./utils");
const CimConfigProgressAlert_1 = require("./CimConfigProgressAlert");
const CimConfigurationFormFields_1 = require("./CimConfigurationFormFields");
const CimConfigurationModal = ({ isOpen, onClose, agentServiceConfig, platform, docDisconnectedUrl, docConfigUrl, docConfigAwsUrl, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const [error, setError] = React.useState();
    const [configureLoadBalancerInitial, setConfigureLoadBalancerInitial] = React.useState(true);
    const isEdit = !!agentServiceConfig;
    const onConfigure = (values, helpers) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        setError(undefined);
        helpers.setSubmitting(true);
        (0, CimConfigProgressAlert_1.resetCimConfigProgressAlertSuccessStatus)();
        try {
            if (['none', 'baremetal', 'openstack', 'vsphere'].includes(platform.toLocaleLowerCase())) {
                try {
                    yield (0, persist_1.patchProvisioning)();
                }
                catch (e) {
                    setError({
                        title: t('ai:Failed to configure provisioning to enable registering hosts via BMC.'),
                        message: (0, utils_1.getErrorMessage)(e),
                        variant: react_core_1.AlertVariant.warning,
                    });
                    setConfigureLoadBalancerInitial(values.configureLoadBalancer);
                    return;
                }
            }
            if (isEdit && agentServiceConfig) {
                yield (0, persist_1.editAgentServiceConfig)({
                    t,
                    agentServiceConfig,
                    values,
                });
            }
            else {
                yield (0, persist_1.createAgentServiceConfig)({ t, values });
            }
            window.localStorage.setItem(utils_2.LOCAL_STORAGE_ID_LAST_UPDATE_TIMESTAMP, new Date().toISOString());
            if (values.configureLoadBalancer) {
                yield (0, persist_1.configureIngressLoadBalancer)({ t });
            }
            onClose();
        }
        catch (err) {
            setError({
                title: t('ai:Failed to save configuration'),
                message: (0, utils_1.getErrorMessage)(err),
            });
            setConfigureLoadBalancerInitial(values.configureLoadBalancer);
        }
        finally {
            helpers.setSubmitting(false);
        }
    });
    const isError = !!(error === null || error === void 0 ? void 0 : error.title); // this is a communication error only (not the one from agentServiceConfig)
    const isConfigure = !isEdit || !configureLoadBalancerInitial; /* The only possible change for the Edit flow */
    const isInProgressPeriod = (0, utils_2.isCIMConfigProgressing)({ agentServiceConfig });
    const initialValues = {
        dbVolSize: (0, helpers_1.getStorageSizeGiB)(10, (_d = (_c = (_b = (_a = agentServiceConfig === null || agentServiceConfig === void 0 ? void 0 : agentServiceConfig.spec) === null || _a === void 0 ? void 0 : _a.databaseStorage) === null || _b === void 0 ? void 0 : _b.resources) === null || _c === void 0 ? void 0 : _c.requests) === null || _d === void 0 ? void 0 : _d.storage),
        fsVolSize: (0, helpers_1.getStorageSizeGiB)(100, (_h = (_g = (_f = (_e = agentServiceConfig === null || agentServiceConfig === void 0 ? void 0 : agentServiceConfig.spec) === null || _e === void 0 ? void 0 : _e.filesystemStorage) === null || _f === void 0 ? void 0 : _f.resources) === null || _g === void 0 ? void 0 : _g.requests) === null || _h === void 0 ? void 0 : _h.storage),
        imgVolSize: (0, helpers_1.getStorageSizeGiB)(50, (_m = (_l = (_k = (_j = agentServiceConfig === null || agentServiceConfig === void 0 ? void 0 : agentServiceConfig.spec) === null || _j === void 0 ? void 0 : _j.imageStorage) === null || _k === void 0 ? void 0 : _k.resources) === null || _l === void 0 ? void 0 : _l.requests) === null || _m === void 0 ? void 0 : _m.storage),
        configureLoadBalancer: platform === 'AWS',
        addCiscoIntersightURL: !!((_p = (_o = agentServiceConfig === null || agentServiceConfig === void 0 ? void 0 : agentServiceConfig.metadata) === null || _o === void 0 ? void 0 : _o.annotations) === null || _p === void 0 ? void 0 : _p['ciscoIntersightURL']),
        ciscoIntersightURL: ((_r = (_q = agentServiceConfig === null || agentServiceConfig === void 0 ? void 0 : agentServiceConfig.metadata) === null || _q === void 0 ? void 0 : _q.annotations) === null || _r === void 0 ? void 0 : _r['ciscoIntersightURL']) || '',
    };
    const validationSchema = Yup.object({
        dbVolSize: Yup.number()
            .min(constants_1.MIN_DB_VOL_SIZE, t('ai:Minimal value is 1Gi'))
            .required(t('ai:Required field')),
        fsVolSize: Yup.number()
            .min(constants_1.MIN_FS_VOL_SIZE, t('ai:Minimal value is 1Gi'))
            .required(t('ai:Required field')),
        imgVolSize: Yup.number()
            .min(constants_1.MIN_IMG_VOL_SIZE, t('ai:Minimal value is 10Gi'))
            .required(t('ai:Required field')),
        configureLoadBalancer: Yup.boolean(),
        addCiscoIntersightURL: Yup.boolean(),
        ciscoIntersightURL: Yup.string().when('addCiscoIntersightURL', {
            is: true,
            then: (schema) => schema
                .required(t('ai:Cisco Intersight URL is required'))
                .test('url-valid', t('ai:Cisco Intersight URL must be a valid URL starting with "http://" or "https://"'), (val) => {
                try {
                    const url = (0, parse_url_1.default)(val);
                    return url.protocol === 'http' || url.protocol === 'https';
                }
                catch (error) {
                    return false;
                }
            }),
        }),
    });
    return (React.createElement(formik_1.Formik, { initialValues: initialValues, validationSchema: validationSchema, onSubmit: onConfigure }, ({ handleSubmit, isValid, isSubmitting }) => (React.createElement(react_core_1.Modal, { "aria-label": t('ai:Configure host inventory settings'), isOpen: isOpen, onClose: onClose, variant: react_core_1.ModalVariant.medium, id: "cim-config-modal" },
        React.createElement(react_core_1.ModalHeader, { title: t('ai:Configure host inventory settings') }),
        React.createElement(react_core_1.ModalBody, null,
            React.createElement(react_core_1.Stack, { hasGutter: true },
                React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.Content, null, t('ai:Configuring the host inventory settings will enable the Central Infrastructure Management.'))),
                isError && (React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.Alert, { title: error.title, variant: error.variant || react_core_1.AlertVariant.danger, isInline: true }, error.message))),
                React.createElement(react_core_1.StackItem, null,
                    React.createElement(CimConfigDisconnectedAlert_1.CimConfigDisconnectedAlert, { docDisconnectedUrl: docDisconnectedUrl })),
                React.createElement(react_core_1.StackItem, null,
                    React.createElement(CimConfigurationFormFields_1.CimConfigurationFormFields, { isEdit: isEdit, platform: platform, isInProgressPeriod: isInProgressPeriod, docConfigUrl: docConfigUrl, docConfigAwsUrl: docConfigAwsUrl, configureLoadBalancerInitial: configureLoadBalancerInitial, setConfigureLoadBalancerInitial: setConfigureLoadBalancerInitial })),
                isConfigure && (React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.warning, title: t('ai:Storage sizes cannot be changed once you configure.'), isInline: true }))))),
        React.createElement(react_core_1.ModalFooter, null, isConfigure ? (React.createElement(React.Fragment, null,
            React.createElement(react_core_1.Button, { key: "configure", variant: react_core_1.ButtonVariant.primary, isDisabled: !!(isSubmitting || !isValid), onClick: () => void handleSubmit() }, t('ai:Configure')),
            React.createElement(react_core_1.Button, { key: "cancel", variant: react_core_1.ButtonVariant.link, onClick: onClose }, t('ai:Cancel')))) : (React.createElement(react_core_1.Button, { key: "close", variant: react_core_1.ButtonVariant.primary, onClick: onClose }, t('ai:Close'))))))));
};
exports.CimConfigurationModal = CimConfigurationModal;
//# sourceMappingURL=CimConfigurationModal.js.map