import { useMemo } from 'react';
import { SearchGroupingType } from '../../enums/unitySystemEnums';
import { useConvertFilterModelToSearchFilters } from '../search/SearchUtilities';
export const useServerSideDatasource = (refetchData, refetchGroupData, filterChanged, // a ref (from useRef()) for detecting when a grid's filters have been changed
setFilterChanged) => {
    const convertFilterModelToSearchFilters = useConvertFilterModelToSearchFilters();
    const dataSource = useMemo(() => {
        const ds = {
            async getRows(params) {
                var _a, _b, _c;
                var _d, _e;
                if (!params)
                    return;
                const { startRow, endRow, sortModel, filterModel, rowGroupCols, groupKeys } = (params === null || params === void 0 ? void 0 : params.request) || {};
                let refetch = refetchData;
                const pageSize = (_a = params === null || params === void 0 ? void 0 : params.api) === null || _a === void 0 ? void 0 : _a.paginationGetPageSize();
                let pageNumber = filterChanged.current === true ? 1 : endRow / pageSize;
                if (isNaN(pageNumber)) {
                    pageNumber = 1;
                }
                // Sorting
                let column = (_d = (_b = sortModel[0]) === null || _b === void 0 ? void 0 : _b.colId) !== null && _d !== void 0 ? _d : '';
                let sortDirection = (_e = (_c = sortModel[0]) === null || _c === void 0 ? void 0 : _c.sort) !== null && _e !== void 0 ? _e : '';
                let sortInfo = [];
                if (column && sortDirection) {
                    sortInfo.push({ sortColumn: column, sortDirection: sortDirection });
                }
                // Filtering
                let searchFilters = [];
                searchFilters = convertFilterModelToSearchFilters(filterModel);
                // Grouping
                const groupingColumns = rowGroupCols === null || rowGroupCols === void 0 ? void 0 : rowGroupCols.map((col) => col.id);
                let groupingType = '';
                // As we are attempting to mimic the grouping functionality of the unity-fluent-library component AmbientGridTemplate which allows
                // grouping on only one column/property at a time, the following logic is to ensure the appropriate grouping endpoint is hit
                // and that the grouping portion of the query in the back-end is added (setting groupingType = AGGREGATE or DISTINCT takes care of this)
                // only when selecting a column to group by. Then, expanding that group would hit a different endpoint to retrieve all rows using the grouping
                // value as a filter value.
                if (groupingColumns.length > 0 && groupKeys.length === 0) {
                    groupingType = SearchGroupingType.Distinct;
                    refetch = refetchGroupData ? refetchGroupData : refetchData;
                }
                // Create the filter for the grouped column
                if (groupKeys.length) {
                    if (groupKeys.length === rowGroupCols.length) {
                        groupKeys.forEach((key, index) => {
                            var _a;
                            const rowGroupCol = rowGroupCols[index];
                            const element = searchFilters.find((element) => element.searchField === rowGroupCol.field);
                            if (element) {
                                element.searchValue = key;
                                element.searchOperator = '=';
                            }
                            else {
                                searchFilters.push({
                                    searchField: (_a = rowGroupCol.field) !== null && _a !== void 0 ? _a : rowGroupCol.id,
                                    searchValue: key,
                                    searchOperator: '=',
                                    searchValueType: 0
                                });
                            }
                        });
                    }
                }
                let search;
                search = {
                    eagerLoad: groupingType ? false : true,
                    pageNumber: pageNumber,
                    pageSize: pageSize,
                    orderElements: sortInfo,
                    filterElements: searchFilters,
                    groupingType: groupingType,
                    groupProperty: groupingColumns
                };
                params.api.hideOverlay();
                const response = await refetch({ data: search }).catch(() => {
                    params.success({ rowData: [], rowCount: 0 });
                    params.api.showNoRowsOverlay();
                });
                if (response) {
                    const rowData = response.data;
                    if (rowData) {
                        // we are expecting response of type Univerus.Unity.Commons.Api.Model.Page, but need to maintain support for MDM
                        if (typeof rowData === 'object' && rowData.pageList) {
                            params.success({
                                rowData: rowData.pageList,
                                rowCount: parseInt(rowData.total)
                            });
                        }
                        else if (rowData.length > 0) {
                            params.success({
                                rowData: rowData,
                                rowCount: parseInt(response.headers['totalrows'])
                            });
                        }
                        else {
                            params.success({ rowData: [], rowCount: 0 });
                        }
                        if (filterChanged.current === true) {
                            params.api.paginationGoToFirstPage();
                            setFilterChanged(false);
                        }
                    }
                    else {
                        params.success({ rowData: [], rowCount: 0 });
                        params.api.showNoRowsOverlay();
                    }
                }
                else {
                    params.fail();
                }
            }
        };
        return ds;
    }, [
        convertFilterModelToSearchFilters,
        filterChanged,
        refetchData,
        refetchGroupData,
        setFilterChanged
    ]);
    return dataSource;
};
//# sourceMappingURL=aggridHelpers.js.map