"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_table_1 = require("@patternfly/react-table");
const selectors_1 = require("../../store/slices/clusters/selectors");
const ClustersListToolbar_1 = tslib_1.__importDefault(require("./ClustersListToolbar"));
const common_1 = require("../../../common");
const use_translation_wrapper_1 = require("../../../common/hooks/use-translation-wrapper");
const DeleteClusterModal_1 = tslib_1.__importDefault(require("./DeleteClusterModal"));
const STORAGE_KEY_CLUSTERS_FILTER = 'assisted-installer-cluster-list-filters';
const columns = [
    { title: 'Name', cellWidth: 20 },
    { title: 'Base domain', cellWidth: 40 },
    { title: 'Version' },
    { title: 'Status' },
    { title: 'Hosts' },
    { title: 'Created at' },
];
const getStatusCell = (row) => { var _a; return (_a = row.cells) === null || _a === void 0 ? void 0 : _a[3]; };
const getRowProps = (props) => {
    const name = (props === null || props === void 0 ? void 0 : props.name) || '';
    return Object.assign(Object.assign({}, props), { id: `cluster-row-${name}`, 'data-testid': `cluster-row-${name}` });
};
const ClustersTable = ({ rows, deleteCluster }) => {
    const [sortBy, setSortBy] = react_1.default.useState({
        index: 0, // Name-column
        direction: react_table_1.SortByDirection.asc,
    });
    const [deleteClusterID, setDeleteClusterID] = react_1.default.useState();
    const [isDeleteInProgress, setDeleteInProgress] = react_1.default.useState(false);
    const [isDeleteModalOpen, setDeleteModalOpen] = react_1.default.useState(false);
    const [searchString, setSearchString] = react_1.default.useState('');
    const [filters, setFilters] = react_1.default.useState({
        status: [],
    });
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const getSortParams = (columnIndex) => ({
        sortBy,
        onSort: (_event, index, direction) => {
            setSortBy({ index, direction });
        },
        columnIndex,
    });
    react_1.default.useEffect(() => {
        const marshalled = window.sessionStorage.getItem(STORAGE_KEY_CLUSTERS_FILTER);
        if (marshalled) {
            try {
                const parsed = JSON.parse(marshalled);
                parsed.filters && setFilters(parsed.filters);
                parsed.sortBy && setSortBy(parsed.sortBy);
                parsed.searchString && setSearchString(parsed.searchString);
            }
            catch (e) {
                // console.info('Failed to restore clusters filter: ', e);
            }
        }
    }, []);
    react_1.default.useEffect(() => {
        window.sessionStorage.setItem(STORAGE_KEY_CLUSTERS_FILTER, JSON.stringify({ filters, sortBy, searchString }));
    }, [filters, sortBy, searchString]);
    const rowFilter = react_1.default.useCallback((row) => {
        var _a;
        const props = row.props;
        const searchableProps = [props.name, props.id, props.baseDnsDomain].map((prop) => (prop || '').toLowerCase());
        if (searchString &&
            !searchableProps.find((prop) => prop.includes(searchString.toLowerCase()))) {
            return false;
        }
        const value = (_a = getStatusCell(row)) === null || _a === void 0 ? void 0 : _a.sortableValue;
        if (filters.status.length > 0 && value && !filters.status.includes(value)) {
            return false;
        }
        return true;
    }, [searchString, filters]);
    const sortedRows = react_1.default.useMemo(() => {
        return rows
            .filter(rowFilter)
            .sort((0, common_1.rowSorter)(sortBy, (row, index = 0) => { var _a; return (_a = row.cells) === null || _a === void 0 ? void 0 : _a[index]; }));
    }, [rows, sortBy, rowFilter]);
    const closeModal = () => {
        setDeleteClusterID(undefined);
        setDeleteModalOpen(false);
    };
    const handleDelete = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        setDeleteInProgress(true);
        yield deleteCluster((deleteClusterID === null || deleteClusterID === void 0 ? void 0 : deleteClusterID.id) || '');
        setDeleteInProgress(false);
        closeModal();
    });
    const hasActiveFilters = searchString.length > 0 || filters.status.length > 0;
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(ClustersListToolbar_1.default, { searchString: searchString, setSearchString: (_event, value) => setSearchString(value), filters: filters, setFilters: setFilters }),
        sortedRows.length === 0 && hasActiveFilters ? (react_1.default.createElement(common_1.EmptyState, { title: "No matching clusters", content: "No clusters match the current filter criteria. Try adjusting your filters." })) : (react_1.default.createElement(react_table_1.Table, { "aria-label": "Clusters table", "data-testid": 'clusters-table' },
            react_1.default.createElement(react_table_1.Thead, null,
                react_1.default.createElement(react_table_1.Tr, null,
                    columns.map((col, i) => (react_1.default.createElement(react_table_1.Th, { key: `col-${i}`, width: col.cellWidth, sort: getSortParams(i) },
                        react_1.default.createElement(react_table_1.TableText, null, col.title)))),
                    react_1.default.createElement(react_table_1.Th, { key: "col-action" }))),
            react_1.default.createElement(react_table_1.Tbody, null, sortedRows.map((row, i) => {
                var _a;
                return (react_1.default.createElement(react_table_1.Tr, Object.assign({}, getRowProps(row.props), { key: `row-${i}` }), (_a = row.cells) === null || _a === void 0 ? void 0 :
                    _a.map((cell, j) => {
                        const humanized = cell;
                        return (react_1.default.createElement(react_table_1.Td, Object.assign({ dataLabel: columns[j].title, key: `cell-${i}-${j}` }, humanized.props),
                            react_1.default.createElement(react_table_1.TableText, { wrapModifier: "breakWord" }, humanized === null || humanized === void 0 ? void 0 : humanized.title)));
                    }),
                    react_1.default.createElement(react_table_1.Td, { isActionCell: true },
                        react_1.default.createElement(react_table_1.ActionsColumn, { items: [
                                {
                                    title: 'Delete',
                                    id: `button-delete-${row.props.name}`,
                                    isDisabled: (0, selectors_1.getClusterTableStatusCell)(row).sortableValue ===
                                        (0, common_1.clusterStatusLabels)(t).installing,
                                    onClick: () => {
                                        setDeleteClusterID({
                                            id: row.props.id,
                                            name: row.props.name,
                                        });
                                        setDeleteModalOpen(true);
                                    },
                                },
                            ] }))));
            })))),
        react_1.default.createElement(DeleteClusterModal_1.default, { name: (deleteClusterID === null || deleteClusterID === void 0 ? void 0 : deleteClusterID.name) || '', onClose: closeModal, onDelete: () => void handleDelete(), isDeleteInProgress: isDeleteInProgress, isOpen: isDeleteModalOpen })));
};
exports.default = ClustersTable;
//# sourceMappingURL=ClustersTable.js.map