import { useHistory } from 'react-router-dom';
import { useSnackbar } from 'notistack';
import { useTranslation } from 'react-i18next';
import { ConfigService } from '../../configService';
import { NodeActionEnums, SplitScreenTypeEnums } from '../../enums/unitySystemEnums';
import { getSuccessAction } from '../../UI/SuccessAction';
import { useActionStore } from '../../stores/actionStore';
import { useInquiryStore } from '../../stores/inquiryStore';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { getPathParametersObj } from '../../utilities/maintenanceEngine/CrudBrowserUtilities';
function isValidURL(url) {
    // Regular expression for URL validation
    const urlPattern = /^(ftp|http|https):\/\/[^ "]+$/;
    return urlPattern.test(url);
}
export const useHandleAction = () => {
    const history = useHistory();
    const { t } = useTranslation();
    const { enqueueSnackbar, closeSnackbar } = useSnackbar();
    const successAction = getSuccessAction(closeSnackbar);
    const selectedNode = useActionStore((state) => state.selectedNode);
    const setWorkflowMap = useInquiryStore((state) => state.setWorkflowMap);
    const setWorkflowStarting = useInquiryStore((state) => state.setWorkflowStarting);
    const executeStartWorkflow = async (workflowId, payload) => apiMutate(ConfigService.builderV1ApiUrl, `workflow/${workflowId}/start`, {
        method: 'post'
    }, { data: payload });
    const getApiMethod = async (apiMethodId) => apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/${apiMethodId}`, {
        method: 'get'
    });
    const handleAction = async (dispatch, action, state, executeAction, apiCatalogId, entityAttributes, actionData, currentContainerId) => {
        var _a, _b;
        if (!action) {
            return;
        }
        const actionName = action.name;
        let actionValue = action.value;
        if ((_a = action === null || action === void 0 ? void 0 : action.parameters) === null || _a === void 0 ? void 0 : _a.entityName) {
            actionValue +=
                '?entityName=' +
                    action.parameters.entityName +
                    '&apiCatalogId=' +
                    apiCatalogId;
        }
        switch (action.actionTypeId) {
            case NodeActionEnums.Open_External_Link:
                window.open(actionValue, '_blank');
                break;
            case NodeActionEnums.Redirect:
                // if the url is valid, redirect to that url, if its not valid, assume its a path redirect on the same origin
                if (isValidURL(actionValue)) {
                    window.location.href = actionValue;
                }
                else {
                    history.push(actionValue);
                }
                break;
            case NodeActionEnums.Create:
                if (dispatch) {
                    dispatch({
                        type: 'OPEN_SIDESHEET',
                        sideSheet: { action: action, open: true }
                    });
                }
                break;
            case NodeActionEnums.Update:
                if (dispatch) {
                    dispatch({
                        type: 'OPEN_SIDESHEET',
                        sideSheet: { action: action, open: true }
                    });
                }
                break;
            case NodeActionEnums.Delete:
                if (dispatch) {
                    dispatch({
                        type: 'OPEN_MODAL',
                        modal: { action: action, open: true, title: 'Delete ' }
                    });
                }
                break;
            case NodeActionEnums.Retrieve:
                if (dispatch) {
                    if (currentContainerId) {
                        break;
                    }
                    else {
                        dispatch({
                            type: 'OPEN_SPLIT_SCREEN',
                            splitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Entity
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Open_Page_Split_Screen:
                if (dispatch) {
                    if (!!selectedNode) {
                        dispatch({
                            type: 'OPEN_PAGE_CONTAINER_SPLIT_SCREEN',
                            pageContainerSplitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Page
                            }
                        });
                    }
                    else {
                        dispatch({
                            type: 'OPEN_PAGE_SPLIT_SCREEN',
                            pageSplitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Page
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Open_Shell_Split_Screen:
                if (dispatch) {
                    if (currentContainerId) {
                        break;
                    }
                    else {
                        dispatch({
                            type: 'OPEN_SPLIT_SCREEN',
                            splitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Page
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Open_Notes:
                if (dispatch) {
                    if (currentContainerId) {
                        break;
                    }
                    else {
                        dispatch({
                            type: 'OPEN_SPLIT_SCREEN',
                            splitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Notes
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Open_Reminders:
                if (dispatch) {
                    if (currentContainerId) {
                        break;
                    }
                    else {
                        dispatch({
                            type: 'OPEN_SPLIT_SCREEN',
                            splitScreen: {
                                action: action,
                                open: true,
                                type: SplitScreenTypeEnums.Reminders
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Execute_Api:
                if (executeAction && (action === null || action === void 0 ? void 0 : action.value)) {
                    let data = {};
                    if (entityAttributes.length > 0 &&
                        ((selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.nodeObj) || actionData)) {
                        // actionData will be used as Request Data first as it is directly passed into function
                        if (actionData) {
                            data = Object.assign({}, actionData);
                        }
                        else {
                            data = Object.assign({}, selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.nodeObj);
                        }
                        const removeAttributes = entityAttributes.filter((p) => {
                            var _a;
                            return (_a = p === null || p === void 0 ? void 0 : p.extendedProperties) === null || _a === void 0 ? void 0 : _a.childEntity;
                        });
                        removeAttributes.forEach((att) => {
                            if (att['name'] in data || 'serializeFields' in data) {
                                delete data[att['name']];
                            }
                        });
                    }
                    const apiMethod = await getApiMethod(action === null || action === void 0 ? void 0 : action.value);
                    const pathParamValues = getPathParametersObj((_b = apiMethod === null || apiMethod === void 0 ? void 0 : apiMethod.data) === null || _b === void 0 ? void 0 : _b.pathParametersDefinition, data);
                    const response = executeAction({
                        data: Object.assign({ requestBody: data }, pathParamValues)
                    }, action.value)
                        .then((res) => {
                        enqueueSnackbar(t(`${action === null || action === void 0 ? void 0 : action.name} api has been executed successfully.`), {
                            anchorOrigin: {
                                vertical: 'top',
                                horizontal: 'center'
                            },
                            action: successAction
                        });
                    })
                        .catch((res) => {
                        enqueueSnackbar(res.message, {
                            variant: 'error',
                            anchorOrigin: {
                                vertical: 'top',
                                horizontal: 'center'
                            }
                        });
                    });
                }
                else {
                    enqueueSnackbar(t(`Unable to execute ${actionName} action.`), {
                        variant: 'error',
                        anchorOrigin: {
                            vertical: 'top',
                            horizontal: 'center'
                        }
                    });
                }
                break;
            case NodeActionEnums.Start_Workflow:
                setWorkflowStarting(true);
                // actionValue will be workflowId where we can call Start workflow
                // actionData is the selected nodeObj used as payload
                const response = await executeStartWorkflow(actionValue, actionData || {}).catch((e) => {
                    enqueueSnackbar(t(`Unable to Start Workflow`), {
                        variant: 'error',
                        anchorOrigin: {
                            vertical: 'top',
                            horizontal: 'center'
                        }
                    });
                });
                setWorkflowStarting(false);
                if (response.status === 200) {
                    const playId = response.data;
                    // if selectedNode it means we're in Inquiry
                    if (selectedNode) {
                        const workflow = {
                            inWorkflowMode: true,
                            currentWorkflowPlayId: playId
                        };
                        const containerId = currentContainerId || 0;
                        setWorkflowMap({ [containerId]: workflow });
                    }
                    else {
                        history.push({
                            pathname: `/workflowtask/${playId}?taskId=${''}`,
                            state: {
                                label: t('Workflow')
                            }
                        });
                    }
                }
                break;
            case NodeActionEnums.Execute_Function:
                !!(actionData === null || actionData === void 0 ? void 0 : actionData.execute) && actionData.execute();
                break;
            default:
                break;
        }
    };
    return { handleAction };
};
//# sourceMappingURL=actionUtils.js.map