import { useContext, useCallback } from 'react';
import { ActionDispatchContext } from '../contexts/ActionDispatchContext';
import { ActionContext } from '../contexts/ActionContext';
import { apiMutate } from '../utilities/useAxiosMutate';
import { useSnackbar } from 'notistack';
import { useTranslation } from 'react-i18next';
import { useHandleAction } from '../actions/utils/actionUtils';
import { ActionLoadingDispatchContext } from '../contexts/ActionLoadingDispatchContext';
import { useCatalogStore } from '../stores/catalogStore';
import { useShellStore } from '../stores/shellStore';
import { NodeActionEnums } from '../enums/unitySystemEnums';
import { ConfigService } from '../configService';
export const useActions = () => {
    const dispatch = useContext(ActionDispatchContext);
    const dispatchActionLoading = useContext(ActionLoadingDispatchContext);
    const actionState = useActionState();
    const { currentApiCatalogId } = useCatalogStore();
    const currentContainerId = useShellStore((state) => state.currentContainerId);
    const { enqueueSnackbar } = useSnackbar();
    const { t } = useTranslation();
    const { handleAction } = useHandleAction();
    const setActionLoading = useCallback((loading) => {
        dispatchActionLoading({
            type: 'SET_ACTION_LOADING',
            loading
        });
    }, [dispatchActionLoading]);
    const setActionWaitingToExecute = useCallback((actionId) => {
        dispatchActionLoading({
            type: 'SET_ACTION_WAITING_TO_EXECUTE',
            actionId
        });
    }, [dispatchActionLoading]);
    const executeGetAction = useCallback(async (actionId) => apiMutate(ConfigService.integrationV1ApiUrl, `action/${actionId}`, {
        method: 'get'
    }, {}), []);
    const executeAction = useCallback(async (data, id) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${id}`, {
        method: 'post'
    }, data), []);
    const setActionPanels = useCallback((actionPanels, containerId) => {
        dispatch({ type: 'SET_ACTION_PANELS', actionPanels, containerId });
    }, [dispatch]);
    const getActionPanelByAction = useCallback((act) => {
        if (act && actionState) {
            const actionPanels = actionState.actionPanels;
            const containerId = currentContainerId || 0;
            if (actionPanels && Array.isArray(actionPanels) && actionPanels[containerId]) {
                const actionPanel = actionPanels[containerId];
                if (Array.isArray(actionPanel.panelActions)) {
                    const foundPanel = actionPanel.find((ap) => {
                        return ap.panelActions.find((pa) => {
                            return pa.actionId === act.actionId;
                        });
                    });
                    return foundPanel;
                }
                else {
                    console.error('panelActions is not an array:', actionPanel.panelActions);
                }
            }
            else {
                console.error('actionPanels is not valid:', actionPanels);
            }
        }
        else {
            console.error('act or actionState is not defined:', act, actionState);
        }
        return null;
    }, [actionState, currentContainerId]);
    const setupAndExecuteAction = useCallback(async (actionId, actionData) => {
        var _a, _b, _c;
        var _d;
        const resp = await executeGetAction(actionId);
        const panel = getActionPanelByAction(resp.data);
        let entityName = panel === null || panel === void 0 ? void 0 : panel.entityName;
        if (!panel) {
            entityName = (_b = (_a = resp === null || resp === void 0 ? void 0 : resp.data) === null || _a === void 0 ? void 0 : _a.parameters) === null || _b === void 0 ? void 0 : _b.entityName;
        }
        if (entityName) {
            if (actionState === null || actionState === void 0 ? void 0 : actionState.setCurrentEntityName) {
                actionState.setCurrentEntityName(entityName);
            }
            const catalogObjectRes = await apiMutate(ConfigService.integrationV2ApiUrl, `apiCatalog/${currentApiCatalogId}/catalogObject/${entityName}`, { method: 'get' });
            const eAttributes = (_d = (_c = catalogObjectRes === null || catalogObjectRes === void 0 ? void 0 : catalogObjectRes.data) === null || _c === void 0 ? void 0 : _c.properties) !== null && _d !== void 0 ? _d : [];
            if (!(eAttributes === null || eAttributes === void 0 ? void 0 : eAttributes.length) &&
                resp.data.actionTypeId !== NodeActionEnums.Start_Workflow) {
                enqueueSnackbar(t(`Unable to retrieve entity attributes.`), {
                    variant: 'error',
                    anchorOrigin: {
                        vertical: 'top',
                        horizontal: 'center'
                    }
                });
            }
            else {
                handleAction(dispatch, resp.data, actionState, executeAction, currentApiCatalogId, eAttributes, actionData, currentContainerId);
            }
        }
        else {
            console.warn('Entity name does not exist');
            // global actions will not necessarily have an entity name
            handleAction(dispatch, resp.data, actionState, executeAction, currentApiCatalogId, {}, actionData, currentContainerId);
        }
    }, [
        actionState,
        enqueueSnackbar,
        executeAction,
        executeGetAction,
        getActionPanelByAction,
        handleAction,
        t,
        dispatch,
        currentContainerId,
        currentApiCatalogId
    ]);
    const executeTriggerAction = useCallback(async (actionId, actionData) => {
        setupAndExecuteAction(actionId, actionData);
    }, [
        setupAndExecuteAction,
    ]);
    const triggerAction = useCallback((actionId, actionData) => {
        executeTriggerAction(actionId, actionData);
    }, [executeTriggerAction]);
    const triggerMultipleActions = useCallback((actionIds) => {
        actionIds.forEach((id) => {
            executeTriggerAction(id);
        });
    }, [executeTriggerAction]);
    const setCatalogEntities = useCallback((catalogEntities) => {
        dispatch({ type: 'SET_CATALOG_ENTITIES', catalogEntities });
    }, [dispatch]);
    const setCatalogPromotedEntities = useCallback((catalogPromotedEntities) => {
        dispatch({
            type: 'SET_CATALOG_PROMOTED_ENTITIES',
            catalogPromotedEntities
        });
    }, [dispatch]);
    const setInquiryParams = useCallback((inquiryParams, containerId) => {
        dispatch({
            type: 'SET_INQUIRY_PARAMS',
            inquiryParams,
            containerId
        });
    }, [dispatch]);
    const setShowInquiryHeaderActions = useCallback((showInquiryHeaderActions) => {
        dispatch({
            type: 'SET_SHOW_INQUIRY_HEADER_ACTIONS',
            showInquiryHeaderActions
        });
    }, [dispatch]);
    const setMenuListState = useCallback((menuListState) => {
        dispatch({
            type: 'SET_MENU_LIST_STATE',
            menuListState
        });
    }, [dispatch]);
    const closeAllSplitScreens = useCallback(() => {
        dispatch({
            type: 'CLOSE_ALL_SPLIT_SCREENS'
        });
    }, [dispatch]);
    const openSplitScreen = useCallback((splitScreen) => {
        dispatch({
            type: 'OPEN_SPLIT_SCREEN',
            splitScreen
        });
    }, [dispatch]);
    const openPageSplitScreen = useCallback((pageSplitScreen) => {
        dispatch({
            type: 'OPEN_PAGE_SPLIT_SCREEN',
            pageSplitScreen
        });
    }, [dispatch]);
    const openPageContainerSplitScreen = useCallback((pageContainerSplitScreen) => {
        dispatch({
            type: 'OPEN_PAGE_CONTAINER_SPLIT_SCREEN',
            pageContainerSplitScreen
        });
    }, [dispatch]);
    return {
        setActionPanels,
        triggerAction,
        triggerMultipleActions,
        setCatalogEntities,
        setCatalogPromotedEntities,
        setInquiryParams,
        setShowInquiryHeaderActions,
        setMenuListState,
        closeAllSplitScreens,
        openSplitScreen,
        openPageSplitScreen,
        openPageContainerSplitScreen,
        setActionLoading
    };
};
export const useActionState = () => useContext(ActionContext);
//# sourceMappingURL=useActions.js.map