var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { useCallback, useEffect, useState } from 'react';
import { makeStyles, LinearProgress, Grow } from '@material-ui/core';
import '../../../../style.css';
import { GridGroupingSidebar } from '../../ui/GridGroupingSidebar';
import { ServerSideRowModelModule } from '@ag-grid-enterprise/server-side-row-model';
import invariant from 'invariant';
import PropTypes from 'prop-types';
import { AgTable, useAgGridApi } from '../../../../utilities/aggrid/AgTable';
import { GridActionBar } from '../../../utilityDisplay/deprecated/grid/GridActionBar';
import { GridPrimaryBar } from '../../../utilityDisplay/deprecated/grid/GridPrimaryBar.jsx';
import { SaveViewFormDialog } from '../../../utilityDisplay/SaveViewFormDialog.jsx';
import { ChipSection } from '../../../utilityDisplay/ChipSection.jsx';
// import GridViewsSideSheet from '../../../utilityDisplay/deprecated/grid/GridViewsSideSheet.jsx';
import { useAxiosGet } from '../../../../utilities/useAxiosGet';
import { apiMutate } from '../../../../utilities/useAxiosMutate';
import { onFirstDataRendered } from '../../../../utilities/aggrid/GridFunctions';
import { BulkActionsGridButton } from '../../../utilityDisplay/BulkActionsGridButton';
import { useActions } from '../../../../hooks/useActions';
import { FilterOperators } from '../../../../models/SearchOperator';
import { ConfigService } from '../../../../configService';
const useStyles = makeStyles((theme) => ({
    root: {},
    pab: {
        display: 'flex',
        [theme.breakpoints.between('xs', 'sm')]: {
            position: 'fixed',
            bottom: theme.spacing(2),
            right: theme.spacing(2),
            zIndex: theme.zIndex.appBar
        }
    },
    groupSideBar: {
        width: 225
    },
    gridApi: {
        display: 'flex'
    }
}));
export const AmbientGridTemplate = (props) => {
    const { additionalFilters, api, apiMethod, applicationName, bulkActionFunctions, clearGridConfig, columnApi, columnDefs, data, defaultAutoSize, deleteGridConfig, disablePagination, disableDynamicSizing, disableRowSelection, entityName, filterChips = [], filters, frameworkComponents, gridReady, gridId, groupingData, height, hideFitGrid, hideExpandGrid, hideExportGrid, hideRemoveFilters, hideFilterTab, hideGroupTab, hideColumnTab, hideSearchBar, hiddenLabels, hiddenActionButtons = [], kpiValues = [], loading = false, onRowSelected, onSearch, onPrimaryActionClick, paginationPageSize = 20, primaryActionButton, primaryActionDisabled, primaryActionLabel, primaryActionIcon, rowModelType = 'clientSide', rowNodeIdName, saveGridConfig, scrollToTopOnStateChange, secondaryActionButtons, title, tenantName, hideHeader, useNewHeader, insightsClick, user, id, udprecordid, additionalGridOptions = {}, headerBackgroundColor, onSearchKeyDown } = props, otherGridProps = __rest(props, ["additionalFilters", "api", "apiMethod", "applicationName", "bulkActionFunctions", "clearGridConfig", "columnApi", "columnDefs", "data", "defaultAutoSize", "deleteGridConfig", "disablePagination", "disableDynamicSizing", "disableRowSelection", "entityName", "filterChips", "filters", "frameworkComponents", "gridReady", "gridId", "groupingData", "height", "hideFitGrid", "hideExpandGrid", "hideExportGrid", "hideRemoveFilters", "hideFilterTab", "hideGroupTab", "hideColumnTab", "hideSearchBar", "hiddenLabels", "hiddenActionButtons", "kpiValues", "loading", "onRowSelected", "onSearch", "onPrimaryActionClick", "paginationPageSize", "primaryActionButton", "primaryActionDisabled", "primaryActionLabel", "primaryActionIcon", "rowModelType", "rowNodeIdName", "saveGridConfig", "scrollToTopOnStateChange", "secondaryActionButtons", "title", "tenantName", "hideHeader", "useNewHeader", "insightsClick", "user", "id", "udprecordid", "additionalGridOptions", "headerBackgroundColor", "onSearchKeyDown"]);
    const classes = useStyles();
    const { gridApi, gridColumnApi, onGridReady } = useAgGridApi();
    const [isVisible, setIsVisible] = useState();
    const [sidebarIsVisible, setSidebarIsVisible] = useState(false);
    const [showGroupOptions, setShowGroupOptions] = useState(false);
    const [selectedRow, setSelectedRow] = useState(null);
    const [value, setValue] = useState(0);
    const [saveViewOpen, setSaveViewOpen] = useState(false);
    const [defaultViews, setDefaultViews] = useState([]);
    const [viewsOpen, setViewsOpen] = useState(false);
    const [agGridOptions, setAgGridOptions] = useState(Object.assign({ frameworkComponents: frameworkComponents, suppressScrollOnNewData: !scrollToTopOnStateChange }, additionalGridOptions));
    const gApi = api || gridApi;
    const gcApi = columnApi || gridColumnApi;
    const [viewChips, setViewChips] = useState([]);
    const [additionalFilterChips, setAdditionalFilterChips] = useState(additionalFilters);
    const [columnDefsValues, setColumnDefsValues] = useState(null);
    const [selectedView, setSelectedView] = useState(null);
    const [viewsRowData, setViewsRowData] = useState(null);
    const [nonDefaultViewsRowData, setNonDefaultViewsRowData] = useState();
    const [numSelectedRows, setNumSelectedRows] = useState(0);
    const [domain, setDomain] = useState(null);
    const [apiCatalogId, setApiCatalogId] = useState(null);
    const { triggerAction } = useActions();
    useEffect(() => {
        if (apiMethod) {
            setDomain(apiMethod.entityName);
            setApiCatalogId(apiMethod.apiCatalogId);
        }
    }, [apiMethod, setDomain, setApiCatalogId]);
    const defaultColActionsDef = {
        resizable: true,
        editable: false,
        sortable: true,
        filter: true,
        floatingFilter: false,
        enableRowGroup: true,
        filterParams: {
            filterOptions: rowModelType === 'serverSide' ? Object.keys(FilterOperators) : undefined
        }
    };
    const handleChange = (event, newValue) => {
        event.preventDefault();
        setValue((preValue) => {
            if (newValue === preValue && newValue !== 1) {
                gApi.setSideBarVisible(!gApi.isSideBarVisible());
            }
            else if (newValue === 0) {
                gApi.setSideBarVisible(true);
                gApi.openToolPanel('filters');
                setShowGroupOptions(false);
            }
            else if (newValue === 1) {
                showGrouping();
                gApi.setSideBarVisible(false);
            }
            else {
                gApi.setSideBarVisible(true);
                gApi.openToolPanel('columns');
                setShowGroupOptions(false);
            }
            return newValue;
        });
    };
    const onFilterClick = (event) => {
        event.preventDefault();
        gApi.setSideBarVisible(!gApi.isSideBarVisible());
        gApi.openToolPanel('filters');
        setShowGroupOptions(false);
        setValue(0);
        setSidebarIsVisible(!sidebarIsVisible);
    };
    const onGroupClick = (event) => {
        // event.preventDefault();
        // // gApi.setSideBarVisible(!gApi.isSideBarVisible());
        // showGrouping();
        // setValue(1);
        alert('Group button clicked');
    };
    const onColumnsClick = (event) => {
        event.preventDefault();
        gApi.setSideBarVisible(!gApi.isSideBarVisible());
        gApi.openToolPanel('columns');
        setShowGroupOptions(false);
        setValue(2);
        setSidebarIsVisible(!sidebarIsVisible);
    };
    const emptyArr = [];
    const handleRowSelected = useCallback((event) => {
        if (!gApi)
            return;
        const selectedRows = gApi.getSelectedRows();
        setNumSelectedRows(selectedRows.length); //for bulk actions ui
        const row = selectedRows.length && selectedRows[0];
        setSelectedRow(row);
        if (onRowSelected) {
            onRowSelected(event, row);
        }
    }, [gApi, onRowSelected]);
    const setSideBarInvisible = () => {
        if (gApi.isSideBarVisible()) {
            gApi.setSideBarVisible(false);
            setIsVisible(false);
        }
        else {
            gApi.setSideBarVisible(true);
            gApi.openToolPanel('filters');
            setShowGroupOptions(false);
            setIsVisible(true);
        }
    };
    const handleFilterChange = (event) => {
        gApi.setQuickFilter(event.target.value);
    };
    // Sets Grouping on grid based on passed filter string
    const groupGridItems = (groupItem) => {
        gcApi.setRowGroupColumns([groupItem]);
        gApi.expandAll();
        // setToggleFlag(groupItem)
    };
    const restoreGridDefault = () => {
        gApi.setQuickFilter('');
        gcApi.setRowGroupColumns([]);
        gApi.setFilterModel(null);
        gApi.setQuickFilter('');
        gcApi.resetColumnState();
    };
    const showGrouping = () => {
        setShowGroupOptions(!showGroupOptions);
        gApi.setSideBarVisible(false);
    };
    const expandGroupedGrid = () => {
        gApi.expandAll();
    };
    const collapseGroupedGrid = () => {
        gApi.collapseAll();
    };
    const fitToSpace = () => {
        gApi.sizeColumnsToFit();
    };
    const exportGrid = () => {
        gApi.exportDataAsCsv({
            allColumns: true,
            fileName: 'export'
        });
    };
    const openSaveView = () => {
        setColumnDefsValues(JSON.stringify(gcApi.getColumnState()));
        setSaveViewOpen(true);
    };
    const closeSaveView = () => {
        setSaveViewOpen(false);
    };
    const openViews = useCallback(() => {
        setViewsOpen(true);
    }, []);
    const closeViews = () => {
        setViewsOpen(false);
    };
    const handleTriggerAction = useCallback((actionId) => {
        if (triggerAction && gApi) {
            triggerAction(actionId, gApi.getSelectedRows());
        }
    }, [triggerAction, gApi]);
    const autoSizeAll = useCallback((skipHeader) => {
        invariant(gcApi, `gridColumnApi not ready`);
        const allColumnIds = [];
        gcApi.getAllColumns().forEach((column) => {
            allColumnIds.push(column.getColId());
        });
        gcApi.autoSizeColumns(allColumnIds, skipHeader);
    }, [gcApi]);
    const autoSizeAllWithoutHeader = useCallback(() => autoSizeAll(false), [autoSizeAll]);
    const firstDataRendered = useCallback((params) => {
        // Size columns to fit after the first data render
        !defaultAutoSize && (params === null || params === void 0 ? void 0 : params.api.sizeColumnsToFit());
        defaultAutoSize && autoSizeAllWithoutHeader();
    }, [defaultAutoSize, autoSizeAllWithoutHeader]);
    useEffect(() => {
        var _a;
        if (!gApi)
            return;
        setSelectedRow(((_a = gApi.getSelectedRows()) === null || _a === void 0 ? void 0 : _a.length) && gApi.getSelectedRows()[0]);
        selectedRow && gApi.ensureNodeVisible(selectedRow);
    }, [gApi, selectedRow]);
    const handleChipDelete = (chipType, chipIndex) => {
        switch (chipType) {
            case 'view':
                setViewChips((prevChips) => prevChips.filter((_, index) => index !== chipIndex));
                setSelectedView(null);
                gcApi.resetColumnState();
                gApi.sizeColumnsToFit();
                break;
            case 'additionalFilter':
                setAdditionalFilterChips((prevChips) => {
                    var _a, _b;
                    if ((_a = prevChips[chipIndex]) === null || _a === void 0 ? void 0 : _a.onUntoggle) {
                        (_b = prevChips[chipIndex]) === null || _b === void 0 ? void 0 : _b.onUntoggle();
                    }
                    return prevChips.filter((_, index) => index !== chipIndex);
                });
                break;
            default:
                break;
        }
    };
    useEffect(() => {
        if ((viewsRowData === null || viewsRowData === void 0 ? void 0 : viewsRowData.length) > 0) {
            const DefaultViews = viewsRowData.reduce((acc, row) => {
                if (row.isDefault) {
                    return [...acc, row];
                }
                return acc;
            }, []);
            const nonDefaultViews = viewsRowData.reduce((acc, row) => {
                if (!row.isDefault) {
                    return [...acc, row];
                }
                return acc;
            }, []);
            setDefaultViews(DefaultViews);
            setNonDefaultViewsRowData(nonDefaultViews);
        }
    }, [viewsRowData]);
    // Function to handle closing the side sheet
    // const handleSideSheetClose = () => {
    //   setIsSideSheetOpen(false);
    // };
    const setView = useCallback((value) => {
        const columnState = value === null || value === void 0 ? void 0 : value.gridViewGridViewGridConfiguration.map((ele) => ele.gridViewGridConfigurationGridConfiguration);
        setViewChips((prevChips) => [{ label: value === null || value === void 0 ? void 0 : value.name }]);
        onFirstDataRendered(gApi, gcApi, columnState);
    }, [setViewChips, gApi, gcApi]);
    const setFilter = (value) => {
        // todo: filter will come from the ApiMethodInstance endpoint
    };
    const [{ data: views }, refetch] = useAxiosGet(ConfigService.tenantV2ApiUrl, `GridView/getFromUser/${user === null || user === void 0 ? void 0 : user.id}/${gridId}`, {
        params: {
            domainName: domain,
            apiCatalogId: apiCatalogId
        }
    }, !!!ConfigService.tenantV2ApiUrl || !!!gridId || !!!user);
    const [{ data: bulkActions }] = useAxiosGet(ConfigService.integrationV2ApiUrl, `action/grid/${gridId}`, {}, !!!ConfigService.integrationV2ApiUrl || !!!gridId);
    useEffect(() => {
        setViewsRowData(views);
    }, [openViews, views]);
    const getView = useCallback(async () => {
        await apiMutate(ConfigService.tenantV2ApiUrl, `GridView/${selectedView === null || selectedView === void 0 ? void 0 : selectedView.gridViewId}/PartiallyFull`, {
            method: 'get'
        })
            .then((response) => {
            setView(response.data);
        })
            .catch((error) => {
            console.log(error);
        });
    }, [selectedView, setView]);
    useEffect(() => {
        if (!(selectedView === null || selectedView === void 0 ? void 0 : selectedView.gridViewId)) {
            gcApi === null || gcApi === void 0 ? void 0 : gcApi.resetColumnState();
            gApi === null || gApi === void 0 ? void 0 : gApi.sizeColumnsToFit();
            return undefined;
        }
        getView();
        // No cleanup function needed, so return undefined
        return undefined;
    }, [setSelectedView, selectedView, gcApi, gApi, getView]);
    useEffect(() => {
        if (additionalFilters) {
            setAdditionalFilterChips(additionalFilters);
        }
    }, [additionalFilters]);
    return (React.createElement(React.Fragment, null, !hideHeader && useNewHeader && gApi && (React.createElement(GridPrimaryBar, { title: title, showFilter: setSideBarInvisible, selected: isVisible, onChange: onSearch || handleFilterChange, showGroup: showGrouping, value: value, saveViewClick: openSaveView, viewsClick: openViews, handleChange: handleChange, fitClick: fitToSpace, expandClick: autoSizeAllWithoutHeader, exportClick: exportGrid, insightsClick: insightsClick, clearClick: restoreGridDefault, filterClick: onFilterClick, columnsClick: onColumnsClick, 
        // groupClick={onGroupClick}
        hideSearchBar: hideSearchBar, secondaryActionButtons: secondaryActionButtons || [], onPrimaryActionClick: onPrimaryActionClick, primaryActionDisabled: primaryActionDisabled, primaryActionLabel: primaryActionLabel, primaryActionIcon: primaryActionIcon, hiddenActionButtons: hiddenActionButtons || [], hiddenLabels: hiddenLabels || [], background: headerBackgroundColor, onSearchKeyDown: onSearchKeyDown })), useNewHeader &&
        ((kpiValues === null || kpiValues === void 0 ? void 0 : kpiValues.length) > 0 ||
            (filterChips === null || filterChips === void 0 ? void 0 : filterChips.length) > 0 ||
            (filters === null || filters === void 0 ? void 0 : filters.length) > 0 ||
            (viewChips === null || viewChips === void 0 ? void 0 : viewChips.length) > 0 ||
            (additionalFilterChips === null || additionalFilterChips === void 0 ? void 0 : additionalFilterChips.length) > 0) && (React.createElement("div", { style: { display: 'flex', flexDirection: 'row', height: 40 } }, React.createElement(Grow, { in: bulkActions && numSelectedRows > 0, unmountOnExit: true }, React.createElement(BulkActionsGridButton, { bulkActions: bulkActions, numSelectedRows: numSelectedRows, triggerAction: handleTriggerAction, domain: domain })), React.createElement(ChipSection, { filterChips: filterChips, viewChips: viewChips, additionalFilterChips: additionalFilterChips, kpiValues: kpiValues, handleDelete: handleChipDelete, setAdditionalFilterChips: setAdditionalFilterChips, setViewChips: setViewChips, setFilter: setFilter }))), !hideHeader && !useNewHeader && (React.createElement(GridActionBar, { title: title, showFilter: setSideBarInvisible, selected: isVisible, onChange: onSearch || handleFilterChange, showGroup: showGrouping, value: value, handleChange: handleChange, fitClick: fitToSpace, expandClick: autoSizeAllWithoutHeader, exportClick: exportGrid, clearClick: restoreGridDefault, saveGridConfig: saveGridConfig, deleteGridConfig: deleteGridConfig, clearGridConfig: clearGridConfig, hideFitGrid: hideFitGrid, hideExpandGrid: hideExpandGrid, hideExportGrid: hideExportGrid, hideRemoveFilters: hideRemoveFilters, hideFilterTab: hideFilterTab, hideGroupTab: hideGroupTab, hideColumnTab: hideColumnTab, hideSearchBar: hideSearchBar }, primaryActionButton && (React.createElement("div", { className: classes.pab }, primaryActionButton)))), loading && React.createElement(LinearProgress, null), React.createElement("div", { style: { display: 'flex' } }, React.createElement("div", { style: { width: '100%' } }, React.createElement(AgTable, Object.assign({}, agGridOptions, { columnDefs: columnDefs, dynamicSizing: !disableDynamicSizing, rowData: data || emptyArr, onGridReady: gridReady || onGridReady, onRowSelected: handleRowSelected, suppressCellSelection: true, suppressRowClickSelection: false, defaultColDef: defaultColActionsDef, enableRangeSelection: true, enableColResize: true, sideBar: sidebarIsVisible, pivotMode: false, pivotPanelShow: "never", groupSelectsChildren: true, animateRows: false, pagination: !disablePagination, showOpenedGroup: true, paginateChildRows: true, paginationPageSize: paginationPageSize, modules: rowModelType === 'serverSide' ? [ServerSideRowModelModule] : [], onFirstDataRendered: firstDataRendered, rowModelType: rowModelType, rowClassRules: {
            'first-row-in-group': (params) => params.node.rowIndex !== 0 && params.node.firstChild
        }, height: height, api: gApi, rowSelection: !disableRowSelection && (bulkActions ? 'multiple' : 'single'), hideHeader: hideHeader }, otherGridProps))), showGroupOptions && (React.createElement("div", { className: classes.groupSideBar }, React.createElement(GridGroupingSidebar, { groupItem: (item) => groupGridItems(item), closeClick: () => groupGridItems(''), expandClick: expandGroupedGrid, collapseClick: collapseGroupedGrid, groupingData: groupingData, height: height }))), !(hiddenActionButtons === null || hiddenActionButtons === void 0 ? void 0 : hiddenActionButtons.includes('saveView')) && (React.createElement(SaveViewFormDialog, { open: saveViewOpen, handleClose: closeSaveView, application: applicationName, tenant: tenantName, user: user, columnDefsValues: columnDefsValues, refetchViews: refetch, gApi: gApi, gcApi: gcApi, setSelectedView: setView, gridId: gridId, domain: domain, apiCatalogId: apiCatalogId })))));
};
AmbientGridTemplate.propTypes = {
    /**
     * Column Definitions for Ag Grid
     */
    columnDefs: PropTypes.array,
    /**
     * AG Grid function for onRowSelected
     */
    handleRowSelected: PropTypes.func,
    /**
     * Data array for AG Grid
     */
    data: PropTypes.array,
    /**
     * Title of the grid
     */
    title: PropTypes.string,
    /**
     * Array of data to allow for custom grouping, example: {groupItem: 'instructors', label: 'Instructors', value: 'instructors'}
     */
    groupingData: PropTypes.array,
    /**
     * Grid Options
     */
    frameworkComponents: PropTypes.object,
    /**
     * Handle loading status with progress animation
     */
    loading: PropTypes.bool,
    /**
     * Primary Action Button Component
     */
    primaryActionButton: PropTypes.object,
    /**
     * name of the property for the id
     */
    rowNodeIdName: PropTypes.string,
    /**
     * Sets the grid default to expaned size if true. The default is 'size to fit'.
     */
    defaultAutoSize: PropTypes.bool,
    /**
     * Scrolls the grid back to the top on state change if true, otherwise maintains scroll position. The default is false.
     */
    scrollToTopOnStateChange: PropTypes.bool,
    /**
     * Disable dynamicSizing so that the grid size stays the same regardless of the window size if true. The default is false.
     */
    disableDynamicSizing: PropTypes.bool,
    /**
     * An array of filter chips.
     */
    filters: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string.isRequired,
        value: PropTypes.string.isRequired
    })),
    /**
     * An array of view chips.
     */
    views: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string.isRequired
    })),
    /**
     * An array of additional filter chips.
     */
    additionalFilters: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string.isRequired
    })),
    /**
     * An array of KPI values.
     */
    kpis: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string.isRequired,
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
            .isRequired
    })),
    /**
     * Enable the new header for data grids v2 if true. The default is false.
     */
    useNewHeader: PropTypes.bool,
    /**
     * Passes function that executes on the insights button click
     */
    insightsClick: PropTypes.func,
    /*
     * Specifies which action buttons to hide
     */
    hiddenActionButtons: PropTypes.arrayOf(PropTypes.oneOf([
        'saveView',
        'views',
        'insights',
        'importExport',
        'group',
        'filter',
        'columns',
        'fitGrid',
        'expandGrid',
        'clearFilters'
    ])),
    /*
     * Specifies which action button labels to hide
     */
    hiddenLabels: PropTypes.arrayOf(PropTypes.oneOf([
        'saveView',
        'views',
        'insights',
        'importExport',
        'group',
        'filter',
        'columns',
        'fitGrid',
        'expandGrid',
        'clearFilters'
    ])),
    /**
     * Passes function that executes on the primary action button click
     */
    onPrimaryActionClick: PropTypes.func,
    /**
     * Specifies the label for the primary action button
     */
    primaryActionLabel: PropTypes.string,
    /**
     * Specifies the icon for the primary action button
     */
    primaryActionIcon: PropTypes.elementType,
    /**
     * An array of objects that will be used to create the secondary action buttons. The default is an empty array.
     */
    secondaryActionButtons: PropTypes.array,
    /**
     * The name of the application that the grid is being used in
     */
    applicationName: PropTypes.string,
    /**
     * The name of the entity that the data in the grid is associated with
     */
    entityName: PropTypes.string,
    /**
     * The name of the tenant that is currently logged in
     */
    tenantName: PropTypes.string,
    /**
     * User object (optional)
     */
    user: PropTypes.object,
    /**
     * Array of KPI values (optional)
     */
    kpiValues: PropTypes.array
};
//# sourceMappingURL=AmbientGridTemplate.js.map