import React, { useCallback, useEffect, useState, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core';
import { useAgGridApi } from '../../../utilities/aggrid/AgTable';
import { LogicalSearchOperatorEnums, UdpEnums } from '../../../enums/unitySystemEnums';
import { LinearProgress } from '../../../UI/loading/LinearProgress';
import { getSearchObject } from '../../../utilities/search/SearchUtilities';
import { ViewIcon, RefreshIcon } from '@fluentui/react-icons';
import UdpAuditEventSidesheet from './UdpAuditEventSidesheet';
import { ActionsRenderer } from '../../../UI/templates/ui/renderers/ActionsRenderer';
import { useDateStringColumnDef } from '../../utilities/useDateStringColumnDef';
import { executeQueryAdHoc, getBaseMethod } from '../../utilities/methodUtils';
import { useCatalogStore } from '../../../stores/catalogStore';
import { useHandleAxiosSnackbar } from '../../../utilities/apiHelpers';
import { SearchMethodUdpGrid } from '../../../UI/templates/newGrid';
import { usePromotedMethodEntity } from '../../../hooks';
const PAGE_SIZE = 15;
const baseSearchPayload = {
    pageNumber: 1,
    pageSize: PAGE_SIZE,
    filterElements: [],
    filterGroups: [],
    orderElements: [],
    groupingType: '',
    groupProperty: [],
    groupOperationList: [],
    eagerLoad: false,
    logicalSearchOperator: 1,
};
const useStyles = makeStyles(theme => ({
    loadingBar: {
        bottom: theme.spacing(-0.5),
        marginLeft: theme.spacing(0.5),
        marginRight: theme.spacing(0.5),
    },
}));
const UdpAuditEventsPage = (props) => {
    const { params } = props;
    // Hooks
    const { gridApi, gridColumnApi, onGridReady } = useAgGridApi();
    const { t } = useTranslation();
    const classes = useStyles();
    const dateStringColumnDef = useDateStringColumnDef(true);
    const { handleErrorSnackbar } = useHandleAxiosSnackbar();
    const gridApiRef = useRef(null);
    // States
    const [searchQuery, setSearchQuery] = useState('');
    const [displayProgressBar, setDisplayProgressBar] = useState(false);
    const [selectedAuditEvent, setSelectedAuditEvent] = useState(null);
    const [viewSideSheetOpen, setViewSideSheetOpen] = useState(false);
    const [auditEventTypes, setAuditEventTypes] = useState([]);
    const [searchObject, setSearchObject] = useState(baseSearchPayload);
    const currentApiCatalogId = useCatalogStore((state) => state.currentApiCatalogId);
    const promotedMethodEntitiesMap = useCatalogStore((state) => state.promotedMethodEntitiesMap);
    const promotedEntities = useMemo(() => {
        if (!currentApiCatalogId || !promotedMethodEntitiesMap) {
            return null;
        }
        return promotedMethodEntitiesMap[currentApiCatalogId] || [];
    }, [promotedMethodEntitiesMap, currentApiCatalogId]);
    const auditEventTypeGetAllApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Audit_Event_Type, 'unityBaseGetAllMethod', promotedEntities);
    }, [promotedEntities]);
    const auditEventSearchApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Audit_Event, 'unityBaseSearchMethod', promotedEntities);
    }, [promotedEntities]);
    const getAuditEventTypeName = useCallback(auditEventTypeCode => {
        if (!auditEventTypes)
            return '';
        const matchingAuditEventType = auditEventTypes.find(auditEventType => auditEventType.code === auditEventTypeCode);
        return (matchingAuditEventType === null || matchingAuditEventType === void 0 ? void 0 : matchingAuditEventType.name) || '';
    }, [auditEventTypes]);
    const handleSideSheet = useCallback((isOpen, auditEvent) => {
        setViewSideSheetOpen(isOpen);
        setSelectedAuditEvent(auditEvent);
    }, []);
    const columnDefs = useMemo(() => {
        return [
            {
                headerName: t('Event Type'),
                field: 'UdpAuditEventUdpAuditEventType.Name',
                valueGetter: params => getAuditEventTypeName(params.data.typeCode),
                resizable: true,
                sortable: false,
            },
            {
                headerName: t('User'),
                field: 'userDisplayName',
                resizable: true,
                sortable: false,
            },
            {
                headerName: t('Description'),
                field: 'domain',
                resizable: true,
                sortable: false,
            },
            Object.assign({ headerName: t('Created On'), field: 'createdOn', resizable: true, sortable: true }, dateStringColumnDef),
            {
                field: 'actions',
                headerName: t('Details'),
                cellRenderer: 'actionsRenderer',
                cellRendererParams: {
                    actionList: [
                        {
                            id: 0,
                            title: t('View'),
                            iconName: 'view',
                            handleOnClick: (e, auditEvent) => {
                                var _a;
                                return handleSideSheet(true, Object.assign(Object.assign({}, auditEvent === null || auditEvent === void 0 ? void 0 : auditEvent.data), { auditEventTypeName: getAuditEventTypeName((_a = auditEvent === null || auditEvent === void 0 ? void 0 : auditEvent.data) === null || _a === void 0 ? void 0 : _a.typeCode) }));
                            },
                            disabled: false,
                        },
                    ],
                },
                suppressMenu: true,
                sortable: false,
                filter: false,
            },
        ];
    }, [getAuditEventTypeName]);
    const gridFunctions = [
        { name: 'chipFilter' },
        { name: 'agGridExport' },
        { name: 'agGridSizeColumnsToFit' },
        { name: 'agGridAutoSizeColumns' },
        { name: 'agGridResetColumns' },
        { name: 'agGridHideShowColumns' },
    ];
    const gridOptions = useMemo(() => {
        return {
            pagination: true,
        };
    }, []);
    useEffect(() => {
        const getAuditEventTypes = async () => {
            let types = [];
            if (auditEventTypeGetAllApiMethod) {
                const response = await executeQueryAdHoc({ data: {} }, auditEventTypeGetAllApiMethod.apiMethodId);
                if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                    types = response.data;
                }
            }
            setAuditEventTypes(types);
        };
        getAuditEventTypes();
    }, [auditEventTypeGetAllApiMethod]);
    const handleGridApiCallback = api => {
        gridApiRef.current = api;
    };
    const searchMethodConfig = useMemo(() => {
        return {
            apiMethodId: auditEventSearchApiMethod === null || auditEventSearchApiMethod === void 0 ? void 0 : auditEventSearchApiMethod.apiMethodId,
            customSearchObject: searchObject,
        };
    }, [auditEventSearchApiMethod]);
    return (React.createElement(React.Fragment, null, (displayProgressBar) && (React.createElement(LinearProgress, { className: classes.loadingBar, color: "secondary" })), React.createElement(SearchMethodUdpGrid, { searchMethodConfig: searchMethodConfig, columnDefs: columnDefs, gridHeaderConfig: {
            title: t('Audit Events'),
        }, gridOptions: gridOptions, gridApiCallback: handleGridApiCallback, gridFunctions: gridFunctions }), React.createElement(UdpAuditEventSidesheet, { auditEvent: selectedAuditEvent, isSideSheetOpen: viewSideSheetOpen, handleSideSheet: handleSideSheet, promotedEntities: promotedEntities })));
};
export default UdpAuditEventsPage;
//# sourceMappingURL=UdpAuditEventsPage.js.map