"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const ConfigProvider_1 = require("../../ConfigProvider");
const useFirstMountState_1 = require("../../useFirstMountState");
const prop_1 = require("../../utils/prop");
const uniqueBy_1 = require("../../utils/uniqueBy");
const constants_1 = require("../constants");
const enums_1 = require("../enums");
const utils_1 = require("../utils");
const hooks_1 = require("./hooks");
const utils_2 = require("./utils");
const useLogic = ({ keyId, columns, rows = [], variant, tree, subrows, selectedRows = [], isLoading, isDisabled, onSelectRow, isError, onRetry, errorMsg, isHideSelectAll, isHideHeaderIfNoData = false, sorting, className, onSort, maxHeight, gridViewMode: gridViewModeProp = 'standard', }) => {
    const isFirstRender = (0, useFirstMountState_1.useFirstMountState)();
    const isSelectable = Boolean(onSelectRow);
    const isDataGridDisabled = isLoading || isDisabled;
    const { imagesMap } = (0, react_1.useContext)(ConfigProvider_1.ConfigContext);
    // Реф добавлен для избежания замыкания selectedRows в handleSelectRow (иначе в handleSelectRow приходят некорректные значения selectedRows).
    const selectedRowsRef = (0, react_1.useRef)(selectedRows);
    (0, react_1.useEffect)(() => {
        selectedRowsRef.current = selectedRows;
    }, [selectedRows]);
    const prevRowsRef = (0, react_1.useRef)([]);
    (0, react_1.useEffect)(() => {
        if (!isLoading) {
            prevRowsRef.current = rows;
        }
    }, [rows, isLoading]);
    const processedColumns = (0, react_1.useCallback)(() => {
        if (rows.length <= 1) {
            return columns.map((column) => ({ ...column, sortable: false }));
        }
        return columns;
    }, [columns, rows]);
    const renderRows = isLoading ? prevRowsRef.current : rows;
    const isNoData = !renderRows.length;
    const { containerRef, rowHoverProps, sections, hasPinnedColumns } = (0, hooks_1.usePinnedColumns)({
        isLoading,
        columns: processedColumns(),
    });
    const { isMobile, mobileSkeletonProps } = (0, hooks_1.useDataGridMobileLogic)({
        containerRef,
        isLoading,
        columns: (0, utils_1.getFlattenColumns)(processedColumns()),
        rows,
        isNoScrollToTop: isLoading && isNoData,
    });
    const treeRenderConfig = Object.is(variant, enums_1.Variant.Subrows)
        ? { ...subrows, isInitialExpanded: true }
        : tree;
    const availableRows = rows.filter((row) => !(row.options?.isDisabled || row.options?.isNotSelectable));
    const gridColumns = (0, react_1.useMemo)(() => (0, utils_1.getGridTemplateColumns)((0, utils_1.getFlattenColumns)(columns)), [columns]);
    const isAllowHorizontalScroll = (0, utils_2.getIsAllowHorizontalScroll)((0, utils_1.getFlattenColumns)(columns));
    const uncheckedRowsCount = (0, react_1.useMemo)(() => {
        return availableRows.filter((row) => !selectedRows.find((selectedRow) => selectedRow[keyId] === row[keyId])).length;
    }, [availableRows, selectedRows, keyId]);
    const handleSelectAllRows = (event) => {
        if (!onSelectRow) {
            return;
        }
        if (event.target.checked) {
            const mergedSelectedRows = (0, uniqueBy_1.uniqueBy)([...selectedRows, ...availableRows], (0, prop_1.prop)(keyId));
            return onSelectRow(mergedSelectedRows);
        }
        const filteredRows = selectedRows.filter((selectedRow) => !rows.find((row) => row[keyId] === selectedRow[keyId]));
        onSelectRow(filteredRows);
    };
    const handleSelectRow = (row) => (event) => {
        if (!onSelectRow) {
            return;
        }
        if (event.target.checked) {
            return onSelectRow([...selectedRowsRef.current, row]);
        }
        onSelectRow(selectedRowsRef.current.filter((selectedRow) => selectedRow[keyId] !== row[keyId]));
    };
    const hasGroupedColumns = columns.some(utils_1.isGroupColumns);
    const gridViewMode = hasGroupedColumns ? 'full' : gridViewModeProp;
    const isHideHead = (isHideHeaderIfNoData && isNoData) || (hasGroupedColumns && isNoData);
    const contentStateProps = (0, react_1.useMemo)(() => {
        return {
            isLoading: (isLoading && isNoData) || (isMobile && isLoading),
            isError: isError && isNoData,
            loadingTitle: 'Загрузка данных',
            errorState: {
                imgAlt: 'Что-то пошло не так',
                errorList: [errorMsg || ''],
                imgSrc: imagesMap.defaultErrorImgSrc,
                onRetry,
            },
            isSmoothLoading: false,
            loadingPlaceholderClassname: constants_1.dataGridClassnames.loadingPlaceholder,
        };
    }, [isLoading, isError, isNoData, errorMsg, onRetry, imagesMap]);
    const containerCssVars = (0, utils_1.getDataGridCssVars)(maxHeight);
    return {
        dataGridClassName: className,
        containerCssVars,
        isDataGridDisabled,
        treeRenderConfig,
        renderRows,
        isAllowHorizontalScroll,
        isHideHead,
        hasPinnedColumns,
        contentStateProps,
        rowHoverProps,
        isMobile,
        containerRef,
        gridColumns,
        isNoData,
        gridViewMode,
        headColumns: processedColumns(),
        isLoading,
        mobileSkeletonProps,
        hasGroupedColumns,
        headProps: {
            rowsCount: availableRows.length,
            uncheckedRowsCount,
            isSelectable,
            onSelectAllRows: handleSelectAllRows,
            isHideSelectAll,
            sorting,
            onSort,
        },
        bodyProps: {
            isSelectable,
            onSelectRow: handleSelectRow,
        },
        sections,
        loaderProps: {
            isLoading: !isFirstRender && isLoading,
            isVisibleDivider: Boolean(rows.length),
            isDisabled,
        },
    };
};
exports.useLogic = useLogic;
