"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useClusterPolling = exports.useFetchCluster = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const common_1 = require("../../../common");
const slice_1 = require("../../store/slices/current-cluster/slice");
const selectors_1 = require("../../store/slices/current-cluster/selectors");
const store_1 = require("../../store");
const shouldRefetch = (uiState, hasClusterData) => {
    if (uiState === common_1.ResourceUIState.POLLING_ERROR) {
        return hasClusterData;
    }
    return ![
        common_1.ResourceUIState.LOADING,
        common_1.ResourceUIState.RELOADING,
        common_1.ResourceUIState.UPDATE_ERROR,
    ].includes(uiState);
};
const useFetchCluster = (clusterId) => {
    const dispatch = (0, store_1.useDispatchDay1)();
    return react_1.default.useCallback(() => {
        if (clusterId) {
            void dispatch((0, slice_1.fetchClusterAsync)(clusterId));
        }
    }, [clusterId, dispatch]);
};
exports.useFetchCluster = useFetchCluster;
const useClusterPolling = (clusterId) => {
    const { isReloadScheduled, uiState, data, errorDetail } = (0, store_1.useSelectorDay1)(selectors_1.selectCurrentClusterState);
    const dispatch = (0, store_1.useDispatchDay1)();
    const fetchCluster = (0, exports.useFetchCluster)(clusterId);
    const hasClusterData = !!data;
    react_1.default.useEffect(() => {
        if (isReloadScheduled && shouldRefetch(uiState, hasClusterData)) {
            fetchCluster();
        }
        dispatch((0, slice_1.cancelForceReload)());
    }, [fetchCluster, dispatch, isReloadScheduled, hasClusterData, uiState]);
    react_1.default.useEffect(() => {
        fetchCluster();
        const timer = window.setInterval(() => dispatch((0, slice_1.forceReload)()), common_1.DEFAULT_POLLING_INTERVAL);
        return () => {
            clearInterval(timer);
            dispatch((0, slice_1.cancelForceReload)());
            dispatch((0, slice_1.cleanCluster)());
        };
    }, [dispatch, fetchCluster]);
    return { cluster: data, uiState, errorDetail };
};
exports.useClusterPolling = useClusterPolling;
//# sourceMappingURL=clusterPolling.js.map