"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clustersReducer = exports.deleteCluster = exports.clustersSlice = exports.fetchClustersAsync = void 0;
const tslib_1 = require("tslib");
const toolkit_1 = require("@reduxjs/toolkit");
const resource_ui_state_1 = require("../../../../common/types/resource-ui-state");
const ClustersAPI_1 = tslib_1.__importDefault(require("../../../../common/api/assisted-service/ClustersAPI"));
const axiosClient_1 = require("../../../../common/api/axiosClient");
const utils_1 = require("../../../../common/api/utils");
exports.fetchClustersAsync = (0, toolkit_1.createAsyncThunk)('clusters/fetchClustersAsync', (value_1, _a) => tslib_1.__awaiter(void 0, [value_1, _a], void 0, function* (value, { rejectWithValue }) {
    try {
        const { data } = yield ClustersAPI_1.default.list();
        return data.filter((cluster) => (axiosClient_1.isInOcm ? cluster.kind === 'Cluster' : true));
    }
    catch (e) {
        return (0, utils_1.handleApiError)(e, () => rejectWithValue(value));
    }
}));
const initialState = { data: [], uiState: resource_ui_state_1.ResourceUIState.LOADING };
exports.clustersSlice = (0, toolkit_1.createSlice)({
    initialState,
    name: 'clusters',
    reducers: {
        deleteCluster: (state, action) => (Object.assign(Object.assign({}, state), { data: state.data.filter((item) => item.id !== action.payload) })),
    },
    extraReducers: (builder) => {
        const { LOADED, LOADING, RELOADING, POLLING_ERROR } = resource_ui_state_1.ResourceUIState;
        builder
            .addCase(exports.fetchClustersAsync.pending, (state) => {
            const uiState = state.uiState === LOADED ? RELOADING : LOADING;
            return Object.assign(Object.assign({}, state), { uiState });
        })
            .addCase(exports.fetchClustersAsync.fulfilled, (state, action) => (Object.assign(Object.assign({}, state), { data: [...action.payload], uiState: LOADED })))
            .addCase(exports.fetchClustersAsync.rejected, (state) => (Object.assign(Object.assign({}, state), { uiState: POLLING_ERROR })));
    },
});
const { actions, reducer } = exports.clustersSlice;
exports.deleteCluster = actions.deleteCluster;
exports.clustersReducer = reducer;
//# sourceMappingURL=slice.js.map