"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInitialClusterEventsFilters = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const capitalize_js_1 = tslib_1.__importDefault(require("lodash-es/capitalize.js"));
const react_core_1 = require("@patternfly/react-core");
const search_icon_1 = require("@patternfly/react-icons/dist/js/icons/search-icon");
const filter_icon_1 = require("@patternfly/react-icons/dist/js/icons/filter-icon");
const config_1 = require("../../config");
const use_translation_wrapper_1 = require("../../hooks/use-translation-wrapper");
const utils_1 = require("./utils");
const utils_2 = require("../../utils");
const CustomToolbarFilter_1 = require("./CustomToolbarFilter");
const CLUSTER_LEVEL = 'cluster-level-action';
const DELETED_HOSTS = 'deleted-hosts-action';
const Placeholder = ({ text }) => (react_1.default.createElement(react_1.default.Fragment, null,
    react_1.default.createElement(filter_icon_1.FilterIcon, null),
    " ",
    text));
const mapHosts = (hosts) => (hosts || []).map((host) => {
    const inventory = (0, utils_2.stringToJSON)(host.inventory) || {};
    let hostname = host.requestedHostname;
    if (inventory.hostname !== host.requestedHostname) {
        hostname += ` (${inventory.hostname || ''})`;
    }
    return {
        hostname,
        id: host.id,
    };
});
const getInitialClusterEventsFilters = (entityKind, hostId) => ({
    message: '',
    hostIds: entityKind === 'host' && hostId ? [hostId] : [],
    severities: [],
    clusterLevel: false,
    deletedHosts: false,
});
exports.getInitialClusterEventsFilters = getInitialClusterEventsFilters;
const mapHostsLabels = (t, filters, hosts) => {
    const labels = [
        filters.deletedHosts && { key: DELETED_HOSTS, node: t('ai:Deleted hosts') },
        filters.clusterLevel && { key: CLUSTER_LEVEL, node: t('ai:Cluster-level events') },
        ...(hosts || [])
            .filter((host) => { var _a; return (_a = filters.hostIds) === null || _a === void 0 ? void 0 : _a.includes(host.id); })
            .map((host) => ({ key: host.id, node: host.hostname })),
    ];
    return labels.filter(Boolean);
};
const ClusterEventsToolbar = ({ filters, setFilters, cluster, hostId, entityKind, severityCounts, }) => {
    var _a;
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const [isHostExpanded, setHostExpanded] = react_1.default.useState(false);
    const [isSeverityExpanded, setSeverityExpanded] = react_1.default.useState(false);
    const [timer, setTimer] = react_1.default.useState();
    const [messageValue, setMessageValue] = react_1.default.useState(filters.message);
    const allHosts = react_1.default.useMemo(() => mapHosts(cluster.hosts), [cluster.hosts]);
    const onClearAllFilters = () => {
        setFilters((0, exports.getInitialClusterEventsFilters)(entityKind, hostId));
        setMessageValue('');
    };
    const onSelect = (type, isChecked, value) => {
        const setNextSelectedValues = (type, isChecked, value, filters) => {
            var _a;
            return (Object.assign(Object.assign({}, filters), { [type]: isChecked
                    ? [...(filters[type] || []), value]
                    : (_a = filters[type]) === null || _a === void 0 ? void 0 : _a.filter((val) => val !== value) }));
        };
        const nextFilters = setNextSelectedValues(type, isChecked, value, filters);
        setFilters(nextFilters);
    };
    const onHostToggle = () => setHostExpanded(!isHostExpanded);
    const onHostSelect = (value, isChecked) => {
        switch (value) {
            case DELETED_HOSTS:
                setFilters(Object.assign(Object.assign({}, filters), { deletedHosts: isChecked }));
                break;
            case CLUSTER_LEVEL:
                setFilters(Object.assign(Object.assign({}, filters), { clusterLevel: isChecked }));
                break;
            default:
                onSelect('hostIds', isChecked, value);
        }
    };
    const onSeverityToggle = () => setSeverityExpanded(!isSeverityExpanded);
    const onSeveritySelect = (value, isChecked) => {
        onSelect('severities', isChecked, value);
    };
    const onMessageChange = (_event, message) => {
        setMessageValue(message);
        clearTimeout(timer);
        const newTimer = setTimeout(() => {
            setMessageValue(message);
            setFilters(Object.assign(Object.assign({}, filters), { message }));
        }, 500);
        setTimer(newTimer);
    };
    const onDeleteLabelGroup = (type) => {
        if (type === 'Severity') {
            setFilters(Object.assign(Object.assign({}, filters), { severities: [] }));
        }
        else {
            setFilters(Object.assign(Object.assign({}, filters), { deletedHosts: false, clusterLevel: false, hostIds: [] }));
        }
    };
    const getSelections = () => {
        const selections = [...(filters.hostIds || [])];
        if (filters.clusterLevel) {
            selections.push(CLUSTER_LEVEL);
        }
        if (filters.deletedHosts) {
            selections.push(DELETED_HOSTS);
        }
        return selections;
    };
    const sortedHosts = allHosts.sort((a, b) => a.hostname && b.hostname && a.hostname < b.hostname ? -1 : 1);
    const hostLabels = mapHostsLabels(t, filters, sortedHosts);
    return (react_1.default.createElement(react_core_1.Toolbar, { id: "clusters-events-toolbar", className: "pf-m-toggle-group-container", collapseListedFiltersBreakpoint: "xl", clearAllFilters: onClearAllFilters, numberOfFiltersText: (numberOfFilters) => t('ai:{{count}} filter applied', { count: numberOfFilters }) },
        react_1.default.createElement(react_core_1.ToolbarContent, null,
            entityKind === 'cluster' && (react_1.default.createElement(CustomToolbarFilter_1.CustomToolbarFilter, { categoryName: "Hosts", labels: hostLabels, deleteLabel: (_, label) => onHostSelect(typeof label === 'string' ? label : label.key, false), deleteLabelGroup: onDeleteLabelGroup },
                react_1.default.createElement(react_core_1.Dropdown, { isOpen: isHostExpanded, onSelect: (e, value) => onHostSelect(value, (0, utils_1.isSelectEventChecked)(e)), onOpenChange: onHostToggle, isScrollable: true, toggle: (toggleRef) => (react_1.default.createElement(react_core_1.MenuToggle, { id: "cluster-events-hosts-dropdown-button", ref: toggleRef, isFullWidth: true, onClick: onHostToggle, isExpanded: isHostExpanded, badge: hostLabels.length && react_1.default.createElement(react_core_1.Badge, { isRead: true }, hostLabels.length), "data-testid": "hosts-dropdown-toggle" },
                        react_1.default.createElement(Placeholder, { text: "Hosts" }))), shouldFocusToggleOnSelect: true },
                    react_1.default.createElement(react_core_1.DropdownList, null,
                        react_1.default.createElement(react_core_1.DropdownItem, { id: `checkbox-${CLUSTER_LEVEL}`, "data-testid": "cluster-level-events-filter-option", hasCheckbox: true, isSelected: getSelections().includes(CLUSTER_LEVEL), key: CLUSTER_LEVEL, value: CLUSTER_LEVEL }, t('ai:Cluster-level events')),
                        react_1.default.createElement(react_core_1.DropdownItem, { id: `checkbox-${DELETED_HOSTS}`, "data-testid": "deleted-hosts-filter-option", hasCheckbox: true, isSelected: getSelections().includes(DELETED_HOSTS), key: DELETED_HOSTS, value: DELETED_HOSTS }, t('ai:Deleted hosts')),
                        ...sortedHosts.map((host) => (react_1.default.createElement(react_core_1.DropdownItem, { id: `checkbox-${host.id}`, "data-testid": `host-${host.id}-filter-option`, hasCheckbox: true, isSelected: getSelections().includes(host.id), key: host.id, value: host.id }, host.hostname))))))),
            react_1.default.createElement(react_core_1.ToolbarFilter, { labels: (_a = filters.severities) === null || _a === void 0 ? void 0 : _a.map((severity) => ({
                    key: severity,
                    node: (0, capitalize_js_1.default)(severity),
                })), deleteLabel: (_, label) => onSeveritySelect(typeof label === 'string' ? label : label.key, false), deleteLabelGroup: onDeleteLabelGroup, categoryName: "Severity" },
                react_1.default.createElement(react_core_1.Dropdown, { isOpen: isSeverityExpanded, onSelect: (event, value) => onSeveritySelect(value, (0, utils_1.isSelectEventChecked)(event)), onOpenChange: onSeverityToggle, toggle: (toggleRef) => {
                        var _a;
                        return (react_1.default.createElement(react_core_1.MenuToggle, { id: "cluster-events-severity-dropdown-button", ref: toggleRef, isFullWidth: true, onClick: onSeverityToggle, isExpanded: isSeverityExpanded, badge: ((_a = filters.severities) === null || _a === void 0 ? void 0 : _a.length) && react_1.default.createElement(react_core_1.Badge, { isRead: true }, filters.severities.length), "data-testid": "severity-dropdown-toggle" },
                            react_1.default.createElement(Placeholder, { text: "Severity" })));
                    }, shouldFocusToggleOnSelect: true },
                    react_1.default.createElement(react_core_1.DropdownList, null, config_1.EVENT_SEVERITIES.map((severity) => {
                        var _a;
                        return (react_1.default.createElement(react_core_1.DropdownItem, { "data-testid": `${severity}-filter-option`, hasCheckbox: true, isSelected: (_a = filters.severities) === null || _a === void 0 ? void 0 : _a.includes(severity), key: severity, value: severity },
                            (0, capitalize_js_1.default)(severity),
                            " ",
                            react_1.default.createElement(react_core_1.Badge, { isRead: true }, severityCounts[severity])));
                    })))),
            react_1.default.createElement(react_core_1.ToolbarItem, null,
                react_1.default.createElement(react_core_1.InputGroup, null,
                    react_1.default.createElement(react_core_1.InputGroupItem, { isFill: true },
                        react_1.default.createElement(react_core_1.TextInput, { name: "search-text", id: "search-text", type: react_core_1.TextInputTypes.search, "aria-label": "text to be searched", onChange: onMessageChange, value: messageValue, placeholder: t('ai:Filter by text') })),
                    react_1.default.createElement(react_core_1.InputGroupItem, null,
                        react_1.default.createElement(react_core_1.Button, { icon: react_1.default.createElement(search_icon_1.SearchIcon, null), variant: react_core_1.ButtonVariant.control, "aria-label": "search text button" })))))));
};
exports.default = ClusterEventsToolbar;
//# sourceMappingURL=ClusterEventsToolbar.js.map