"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_router_dom_v5_compat_1 = require("react-router-dom-v5-compat");
const ClusterWizardContext_1 = require("./ClusterWizardContext");
const wizardTransition_1 = require("./wizardTransition");
const services_1 = require("../../services");
const constants_1 = require("./constants");
const dataTypes_1 = require("../clusterConfiguration/staticIp/data/dataTypes");
const fromInfraEnv_1 = require("../clusterConfiguration/staticIp/data/fromInfraEnv");
const common_1 = require("../../../common");
const useSetClusterPermissions_1 = tslib_1.__importDefault(require("../../hooks/useSetClusterPermissions"));
const hooks_1 = require("../../hooks");
const react_core_1 = require("@patternfly/react-core");
const use_feature_1 = require("../../hooks/use-feature");
const networkType_1 = require("../../../common/types/networkType");
const utils_1 = require("../utils");
const addStepToClusterWizard = (wizardStepIds, addAfterStep, itemsToAdd) => {
    const stepsIds = [...wizardStepIds];
    const referencePosition = stepsIds.findIndex((step) => step === addAfterStep);
    const found = wizardStepIds.filter((step) => step === itemsToAdd[0]);
    if (referencePosition !== -1 && found.length === 0) {
        stepsIds.splice(referencePosition + 1, 0, ...itemsToAdd);
    }
    return stepsIds;
};
const removeStepFromClusterWizard = (wizardStepIds, itemToRemove, numberItemsToRemove) => {
    const stepsIds = [...wizardStepIds];
    const position = stepsIds.findIndex((step) => step === itemToRemove);
    if (position !== -1) {
        stepsIds.splice(position, numberItemsToRemove);
    }
    return stepsIds;
};
const getWizardStepIds = (wizardStepIds, staticIpView, isSingleClusterFeatureEnabled) => {
    let stepsCopy = wizardStepIds ? [...wizardStepIds] : [...constants_1.defaultWizardSteps];
    if (staticIpView === dataTypes_1.StaticIpView.YAML) {
        stepsCopy = removeStepFromClusterWizard(stepsCopy, 'static-ip-network-wide-configurations', 2);
        stepsCopy = addStepToClusterWizard(stepsCopy, 'cluster-details', ['static-ip-yaml-view']);
    }
    else if (staticIpView === dataTypes_1.StaticIpView.FORM) {
        stepsCopy = removeStepFromClusterWizard(stepsCopy, 'static-ip-yaml-view', 1);
        stepsCopy = addStepToClusterWizard(stepsCopy, 'cluster-details', constants_1.staticIpFormViewSubSteps);
    }
    else if (staticIpView === 'dhcp-selected') {
        stepsCopy = removeStepFromClusterWizard(stepsCopy, 'static-ip-network-wide-configurations', 2);
    }
    if (isSingleClusterFeatureEnabled) {
        stepsCopy = addStepToClusterWizard(stepsCopy, 'networking', ['credentials-download']);
    }
    return stepsCopy;
};
const ClusterWizardContextProvider = ({ children, cluster, infraEnv, permissions, }) => {
    const isSingleClusterFeatureEnabled = (0, use_feature_1.useFeature)('ASSISTED_INSTALLER_SINGLE_CLUSTER_FEATURE');
    const [currentStepId, setCurrentStepId] = react_1.default.useState();
    const [connectedWizardStepIds, setWizardStepIds] = react_1.default.useState();
    const [wizardPerPage, setWizardPerPage] = react_1.default.useState(10);
    const [installDisconnected, setInstallDisconnected] = react_1.default.useState(false);
    const location = (0, react_router_dom_v5_compat_1.useLocation)();
    const locationState = location.state;
    const { uiSettings, updateUISettings, loading: UISettingsLoading, error: UISettingsError, } = (0, hooks_1.useUISettings)(cluster === null || cluster === void 0 ? void 0 : cluster.id);
    const { clearAlerts, addAlert, alerts } = (0, common_1.useAlerts)();
    const setClusterPermissions = (0, useSetClusterPermissions_1.default)();
    const wizardStepIds = installDisconnected ? wizardTransition_1.disconnectedSteps : connectedWizardStepIds;
    react_1.default.useEffect(() => {
        if (!UISettingsLoading) {
            const staticIpInfo = infraEnv ? (0, fromInfraEnv_1.getStaticIpInfo)(infraEnv) : undefined;
            let customManifestsRequired = false;
            if (cluster) {
                customManifestsRequired =
                    (0, networkType_1.isThirdPartyCNI)(cluster.networkType) || (0, utils_1.isOciPlatformType)(cluster);
            }
            const customManifestsStepNeedsToBeFilled = customManifestsRequired && !(uiSettings === null || uiSettings === void 0 ? void 0 : uiSettings.customManifestsAdded);
            const requiredStepId = (0, wizardTransition_1.getClusterWizardFirstStep)(locationState, staticIpInfo, cluster === null || cluster === void 0 ? void 0 : cluster.status, cluster === null || cluster === void 0 ? void 0 : cluster.hosts, customManifestsStepNeedsToBeFilled);
            const firstStepIds = getWizardStepIds(wizardStepIds, staticIpInfo === null || staticIpInfo === void 0 ? void 0 : staticIpInfo.view, isSingleClusterFeatureEnabled);
            // Only move step if there is still none, or the user is at a forbidden step
            if (!currentStepId ||
                (customManifestsStepNeedsToBeFilled && (0, wizardTransition_1.isStepAfter)(currentStepId, requiredStepId))) {
                setCurrentStepId(requiredStepId);
            }
            setWizardStepIds(firstStepIds);
            setClusterPermissions(cluster, permissions);
        }
        if (!!UISettingsError &&
            !alerts.some((alert) => alert.title === "Couldn't retrieve UI settings")) {
            addAlert({
                title: "Couldn't retrieve UI settings",
                message: UISettingsError,
                variant: react_core_1.AlertVariant.warning,
            });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [uiSettings, UISettingsLoading, UISettingsError]);
    const contextValue = react_1.default.useMemo(() => {
        if (!wizardStepIds || !currentStepId) {
            return null;
        }
        const handleMoveFromStaticIp = () => {
            //if static ip view change wasn't persisted, moving from static ip step should change the wizard steps to match the view in the infra env
            const staticIpInfo = infraEnv ? (0, fromInfraEnv_1.getStaticIpInfo)(infraEnv) : undefined;
            if (!staticIpInfo) {
                throw `Wizard step is currently ${currentStepId}, but no static ip info is defined`;
            }
            const newStepIds = getWizardStepIds(wizardStepIds, staticIpInfo.view, isSingleClusterFeatureEnabled);
            setWizardStepIds(newStepIds);
        };
        const onSetCurrentStepId = (stepId) => {
            clearAlerts();
            if ((0, wizardTransition_1.isStaticIpStep)(currentStepId) && !(0, wizardTransition_1.isStaticIpStep)(stepId)) {
                handleMoveFromStaticIp();
            }
            setCurrentStepId(stepId);
        };
        return {
            moveBack() {
                clearAlerts();
                const currentStepIdx = wizardStepIds.indexOf(currentStepId);
                let nextStepId = wizardStepIds[currentStepIdx - 1];
                if (nextStepId === 'static-ip-host-configurations') {
                    //when moving back to static ip form view, it should go to network wide configurations
                    nextStepId = 'static-ip-network-wide-configurations';
                }
                onSetCurrentStepId(nextStepId);
            },
            moveNext() {
                const currentStepIdx = wizardStepIds.indexOf(currentStepId);
                onSetCurrentStepId(wizardStepIds[currentStepIdx + 1]);
            },
            onUpdateStaticIpView(view) {
                if (view === dataTypes_1.StaticIpView.YAML) {
                    setCurrentStepId('static-ip-yaml-view');
                }
                else {
                    setCurrentStepId('static-ip-network-wide-configurations');
                }
                setWizardStepIds(getWizardStepIds(wizardStepIds, view, isSingleClusterFeatureEnabled));
            },
            onUpdateHostNetworkConfigType(type) {
                if (type === services_1.HostsNetworkConfigurationType.STATIC) {
                    setWizardStepIds(getWizardStepIds(wizardStepIds, dataTypes_1.StaticIpView.FORM, isSingleClusterFeatureEnabled));
                }
                else {
                    setWizardStepIds(getWizardStepIds(wizardStepIds, 'dhcp-selected', isSingleClusterFeatureEnabled));
                }
            },
            wizardStepIds: wizardStepIds,
            currentStepId,
            setCurrentStepId: onSetCurrentStepId,
            wizardPerPage,
            setWizardPerPage,
            uiSettings,
            updateUISettings,
            installDisconnected,
            setInstallDisconnected: (enabled) => {
                setInstallDisconnected(enabled);
                if (enabled) {
                    onSetCurrentStepId(wizardTransition_1.disconnectedSteps[0]);
                }
                else {
                    (connectedWizardStepIds === null || connectedWizardStepIds === void 0 ? void 0 : connectedWizardStepIds.length) && onSetCurrentStepId(connectedWizardStepIds[0]);
                }
            },
        };
    }, [
        wizardStepIds,
        currentStepId,
        infraEnv,
        wizardPerPage,
        isSingleClusterFeatureEnabled,
        clearAlerts,
        uiSettings,
        updateUISettings,
        installDisconnected,
        connectedWizardStepIds,
    ]);
    if (!contextValue) {
        return null;
    }
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(ClusterWizardContext_1.ClusterWizardContext.Provider, { value: contextValue }, children)));
};
exports.default = ClusterWizardContextProvider;
//# sourceMappingURL=ClusterWizardContextProvider.js.map