import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { useAxiosGet } from '../../../utilities/useAxiosGet';
import { useAxiosMutate } from '../../../utilities/useAxiosMutate';
import { useAuthedUser } from '../../../utilities/auth/useAuthedUser';
import { getSanitizedName } from '../../../utilities/entities/entityUtilities';
import { useHistory } from 'react-router-dom';
import { PageLoading } from '../../../UI/feedback/PageLoading';
import { useTranslation } from 'react-i18next';
import { ClientSideUdpGrid } from '../../../UI/templates/newGrid/ClientSideUdpGrid';
import { ConfigService } from '../../../configService';
const UdpMaintenanceConfigPage = (props) => {
    const [apiCatalogId, setApiCatalogId] = useState(null);
    const user = useAuthedUser();
    const history = useHistory();
    const { t } = useTranslation();
    /* #region  API Methods */
    const [{ data: tpacb, loading: loadingTpacb, error: tpacbError }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `tenantProductApiCatalogBase/tenant/${user === null || user === void 0 ? void 0 : user.currentTenantId}/product/${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!user, false);
    const [{ data: promotedGetConfigApi, loading: loadingPromotedGetConfigApi, error: promotedGetConfigApiError }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `apicatalog/${apiCatalogId}/promotedConfigEntity/product/${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!apiCatalogId, false);
    const [{ data: tableConfigList, loading: tableConfigListLoading, error: tableConfigListError }, fetchTableConfigList] = useAxiosMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${promotedGetConfigApi === null || promotedGetConfigApi === void 0 ? void 0 : promotedGetConfigApi.apiMethodId}`, {
        method: 'post'
    });
    const [{ data: promotedMethods, loading, error }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `apicatalog/${apiCatalogId}/promotedMethodEntities?productId=${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!apiCatalogId, false);
    /* #endregion */
    const rowData = useMemo(() => {
        if (!promotedMethods || !tableConfigList) {
            return [];
        }
        let tmp = [];
        if (Array.isArray(tableConfigList)) {
            tmp = tableConfigList;
        }
        else {
            // eslint-disable-next-line no-unused-vars
            for (const [key, value] of Object.entries(tableConfigList)) {
                tmp.push(`${key}`);
            }
        }
        const result = tmp.reduce((mergedData, tableConfig) => {
            const matchingEntityRow = promotedMethods.find((promotedEntity) => promotedEntity.entityName === getSanitizedName(tableConfig));
            if (matchingEntityRow) {
                mergedData.push(matchingEntityRow);
            }
            else {
                const placeholderData = {
                    entityName: tableConfig,
                    productId: ConfigService.config.UNITY_PRODUCT_ID,
                    unityBaseGetAllMethod: null,
                    unityBaseGetMethod: null,
                    unityBaseCreateMethod: null,
                    unityBaseUpdateMethod: null,
                    unityBaseDeleteMethod: null
                };
                mergedData.push(placeholderData);
            }
            return mergedData;
        }, []);
        return result;
    }, [promotedMethods, tableConfigList]);
    const handleOpenEntityMaintenancePage = useCallback((selectedEntity) => {
        history.push(`/crudbrowser`, {
            entityName: getSanitizedName(selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.entityName),
            apiCatalogId: apiCatalogId,
            from: 'tablebrowser'
        });
    }, [history, apiCatalogId]);
    const actionList = useMemo(() => [
        {
            id: 0,
            title: t('View table data'),
            iconName: 'arrowRight16',
            handleOnClick: (e, params) => handleOpenEntityMaintenancePage(params === null || params === void 0 ? void 0 : params.data),
            disabled: false
        }
    ], [handleOpenEntityMaintenancePage, t]);
    const columnDefs = useMemo(() => {
        return [
            {
                headerName: 'Entity Name',
                field: 'entityName',
                valueGetter: (params) => {
                    var _a, _b, _c, _d;
                    return ((_b = (_a = params.data) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.displayName) ||
                        ((_c = params.data) === null || _c === void 0 ? void 0 : _c.sanitizedName) ||
                        getSanitizedName((_d = params.data) === null || _d === void 0 ? void 0 : _d.entityName);
                },
            },
            {
                headerName: 'Actions',
                field: 'actions',
                cellRenderer: 'actionsRenderer',
                cellRendererParams: {
                    actionList: actionList
                }
            }
        ];
    }, [actionList]);
    useEffect(() => {
        if (tpacb) {
            setApiCatalogId(tpacb.apiCatalogId);
        }
    }, [tpacb]);
    useEffect(() => {
        if (promotedGetConfigApi === null || promotedGetConfigApi === void 0 ? void 0 : promotedGetConfigApi.apiMethodId) {
            fetchTableConfigList({ data: {} });
        }
    }, [fetchTableConfigList, promotedGetConfigApi]);
    if (loadingTpacb || loadingPromotedGetConfigApi || tableConfigListLoading) {
        return React.createElement(PageLoading, null);
    }
    if (tpacbError) {
        return (React.createElement("div", null, t('There is no Api Catalog associated with your tenant and product')));
    }
    if (promotedGetConfigApiError) {
        return (React.createElement("div", null, t('Please promote your get configuration tables method before proceeding')));
    }
    if (tableConfigListError) {
        return React.createElement("div", null, t('No configuration tables could be found'));
    }
    return (React.createElement(ClientSideUdpGrid, { rowData: rowData, columnDefs: columnDefs, gridHeaderConfig: { title: 'Table Browser' } }));
};
export default UdpMaintenanceConfigPage;
//# sourceMappingURL=UdpMaintenanceConfigPage.js.map