import { useState, useEffect, useCallback } from 'react';
import { apiMutate } from '../utilities/useAxiosMutate';
import { useCatalogStore } from '../stores/catalogStore';
import { ConfigService } from '../configService';
export const useApiCatalog = (apiCatalogId) => {
    const [data, setData] = useState(undefined);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(undefined);
    const [promise, setPromise] = useState(undefined);
    const { setCatalogsMap, catalogsMap } = useCatalogStore();
    const setErrorState = (e) => {
        setLoading(false);
        setError(e);
    };
    const setSuccessState = useCallback((response) => {
        setError(undefined);
        setLoading(false);
        setData(response);
    }, []);
    useEffect(() => {
        let isMounted = true;
        if (!apiCatalogId)
            return;
        if (catalogsMap[apiCatalogId]) {
            setSuccessState(catalogsMap[apiCatalogId]);
            return () => {
                isMounted = false;
            };
        }
        const catalogPromise = apiMutate(ConfigService.integrationV1ApiUrl, `apiCatalog/${apiCatalogId}?includeCatalogObjectList=false`, {});
        const catalogObjectsPromise = apiMutate(ConfigService.integrationV1ApiUrl, `apiCatalog/${apiCatalogId}/catalogObjects`, {});
        const allPromises = Promise.all([catalogPromise, catalogObjectsPromise]);
        allPromises
            .then(([catalogRes, catalogObjectsRes]) => {
            if (isMounted) {
                const apiCatalog = catalogRes.data;
                apiCatalog.ctlg.catalogObjectList = catalogObjectsRes.data;
                setSuccessState(apiCatalog);
                setCatalogsMap({ [apiCatalogId]: apiCatalog });
            }
        })
            .catch(setErrorState);
        setPromise(allPromises);
        return () => {
            isMounted = false;
        };
    }, [apiCatalogId, catalogsMap, setCatalogsMap, setSuccessState]);
    return { data, loading, error, promise };
};
//# sourceMappingURL=useApiCatalog.js.map