import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useAxiosGet } from '../utilities/useAxiosGet';
import { apiMutate } from '../utilities/useAxiosMutate';
import { useAuthedUser } from '../utilities/auth/useAuthedUser';
import { InquiryContainer } from './InquiryContainer';
import { useActions } from '../hooks/useActions';
import { useShellStore } from '../stores/shellStore';
import { ConfigService } from '../configService';
import { useCatalogStore } from '../stores/catalogStore';
import { CircularProgress, makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
    loadingContent: {
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: (props) => props.loadingHeight ? props.loadingHeight : 'calc(100vh - 160px)'
    }
}));
/**
 * Required Props:
 * user - current unity user
 * productId - current product id of application
 * litnHistory (loaded inquiry tree node history) - array of tree node objects to be used in the recently loaded nodes
 * litnHistoryLoading - request status of the litnHistory request
 * tree - tree object which contains the tree structure and its properties
 * treeLoading - request status of tree request
 * treeError - error status of tree request
 * treeId - id of the tree that's being loaded (retreived from URL)
 * catalogObjects - array of catalog items and it's relationship and properties
 * executeQueryAdHoc - search callback
 * executeQueryWithParameters - search callback with extra parameters
 * executeGetDetailedTree - callback to get detailed tree information for the associated tree
 * executeAddRecentlyLoadedNodes - callback to add loaded nodes to history
 * pageData - data for the page to be displayed in inquiry
 * pageLoading - boolean value for if a page is loading
 * pageError - error status of page request
 * setPageId - setter for setting pageId when it changes
 * pageId - id of page
 * initialSearchValue - query parameter representing a value to search upon loading of this inquiry page
 * promotedEntities - promoted entities for the catalog used in the inquiry tree
 * promotedMethods - promoted methods for the catalog used in the inquiry tree
 *
 * @param {*} props
 * @returns Inquiry
 */
export const Inquiry = (props) => {
    var _a;
    const { treeId, searchValue, autoCollapseNav = true, useNewUdpTab = true, containerId = '' } = props;
    const classes = useStyles(props);
    const user = useAuthedUser();
    const { location } = props;
    const udpTreeId = treeId || ((_a = location === null || location === void 0 ? void 0 : location.pathname) === null || _a === void 0 ? void 0 : _a.replace('/inquiry/', ''));
    let searchParamStr = location === null || location === void 0 ? void 0 : location.search;
    let searchParams = new URLSearchParams(searchParamStr);
    const initialSearchValue = searchValue ||
        (searchParams.has('searchValue') === true
            ? searchParams.get('searchValue')
            : '');
    const [pageId, setPageId] = useState(null);
    const { setCatalogEntities, setCatalogPromotedEntities, setActionPanels, setInquiryParams } = useActions();
    const currentApiCatalogId = useCatalogStore((state) => state.currentApiCatalogId);
    const promotedMethodEntitiesMap = useCatalogStore((state) => state.promotedMethodEntitiesMap);
    const setCurrentContainerId = useShellStore((state) => state.setCurrentContainerId);
    const [{ data: litnHistory, loading: litnHistoryLoading }, refetchLitnHistory] = useAxiosGet(ConfigService.integrationV1ApiUrl, `inquirytree/loadedInquiryTreeNodes?inquiryTreeId=${udpTreeId}&userId=${user.id}&productId=${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!udpTreeId, false);
    const [{ data: tree, loading: treeLoading, error: treeError }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `inquirytree/${udpTreeId}/detailed`, {}, !!!udpTreeId, false);
    const executeQueryAdHoc = useCallback(async (data, apiMethodId) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryAdHoc/${apiMethodId}`, {
        method: 'post'
    }, data), []);
    const executeQueryWithParameters = useCallback(async (data, apiMethodId) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${apiMethodId}`, {
        method: 'post'
    }, data), []);
    const executeGetDetailedTree = useCallback(async (treeId) => apiMutate(ConfigService.integrationV1ApiUrl, `inquirytree/${treeId}/detailed`, {
        method: 'get'
    }), []);
    const executeAddRecentlyLoadedNodes = useCallback(async (data) => {
        await apiMutate(ConfigService.integrationV1ApiUrl, `inquirytree/${udpTreeId}/loadedInquiryTreeNodes/user/${user.id}/product/${ConfigService.config.UNITY_PRODUCT_ID}`, {
            method: 'post'
        }, data);
        refetchLitnHistory();
    }, [user, udpTreeId, refetchLitnHistory]);
    const [{ data: page, loading: pageLoading, error: pageError }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `page/${pageId}`, {}, !!!pageId, false);
    const [{ data: catalogObjects }] = useAxiosGet(ConfigService.integrationV2ApiUrl, `apiCatalog/${currentApiCatalogId}/inquiryTree/${treeId}/withDescendants?modelsOnly=true`, {}, !currentApiCatalogId || !treeId, true);
    const promotedEntities = useMemo(() => {
        if (!currentApiCatalogId || !promotedMethodEntitiesMap) {
            return null;
        }
        return promotedMethodEntitiesMap[currentApiCatalogId] || [];
    }, [promotedMethodEntitiesMap, currentApiCatalogId]);
    useEffect(() => {
        if (catalogObjects) {
            setCatalogEntities(catalogObjects);
        }
    }, [setCatalogEntities, catalogObjects]);
    useEffect(() => {
        if (promotedEntities) {
            setCatalogPromotedEntities(promotedEntities);
        }
    }, [setCatalogPromotedEntities, promotedEntities]);
    useEffect(() => {
        if (containerId) {
            setCurrentContainerId(containerId);
        }
        // unmount function
        return () => {
            if (containerId) {
                setCurrentContainerId(null);
                setActionPanels(null, containerId);
                setInquiryParams(null, containerId);
            }
        };
    }, [setActionPanels, setCurrentContainerId, containerId, setInquiryParams]);
    if (treeLoading && !treeError) {
        return (React.createElement("div", { className: classes.loadingContent }, React.createElement(CircularProgress, { size: 64 })));
    }
    return (React.createElement(InquiryContainer, { user: user, productId: ConfigService.config.UNITY_PRODUCT_ID, litnHistory: litnHistory, litnHistoryLoading: litnHistoryLoading, tree: tree, treeLoading: treeLoading, treeError: treeError, treeId: udpTreeId, catalogObjects: catalogObjects, executeQueryAdHoc: executeQueryAdHoc, executeQueryWithParameters: executeQueryWithParameters, executeGetDetailedTree: executeGetDetailedTree, executeAddRecentlyLoadedNodes: executeAddRecentlyLoadedNodes, pageData: page, pageLoading: pageLoading, pageError: pageError, setPageId: setPageId, pageId: pageId, initialSearchValue: initialSearchValue, promotedEntities: promotedEntities, apiCatalogId: currentApiCatalogId, autoCollapseNav: autoCollapseNav, useNewUdpTab: useNewUdpTab, containerId: containerId }));
};
//# sourceMappingURL=Inquiry.js.map