"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VulnerabilitiesByResource = void 0;
var _eui = require("@elastic/eui");
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _reactRouterDom = require("react-router-dom");
var _constants = require("../../../common/constants");
var _constants2 = require("../../../common/navigation/constants");
var _use_cloud_posture_table = require("../../../common/hooks/use_cloud_posture_table");
var _error_callout = require("../../configurations/layout/error_callout");
var _findings_search_bar = require("../../configurations/layout/findings_search_bar");
var _get_limit_properties = require("../../../common/utils/get_limit_properties");
var _findings_layout = require("../../configurations/layout/findings_layout");
var _vulnerabilities_by_resource_table_columns = require("./vulnerabilities_by_resource_table_columns");
var _cloud_posture_page = require("../../../components/cloud_posture_page");
var _translations = require("../translations");
var _use_styles = require("../hooks/use_styles");
var _findings_group_by_selector = require("../../configurations/layout/findings_group_by_selector");
var _vulnerabilities_pathname_handler = require("../utils/vulnerabilities_pathname_handler");
var _use_latest_vulnerabilities_by_resource = require("../hooks/use_latest_vulnerabilities_by_resource");
var _empty_state = require("../../../components/empty_state");
var _severity_map = require("./severity_map");
var _test_subjects = require("./test_subjects");
var _get_vulnerabilities_grid_cell_actions = require("../utils/get_vulnerabilities_grid_cell_actions");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const getDefaultQuery = ({
  query,
  filters
}) => ({
  query,
  filters,
  sort: [{
    id: _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.vulnerabilities_count,
    direction: 'desc'
  }],
  pageIndex: 0
});
const VulnerabilitiesByResourceDataGrid = ({
  dataView,
  data,
  isFetching,
  pageIndex,
  sort,
  pageSize,
  onChangeItemsPerPage,
  onChangePage,
  onSort,
  urlQuery,
  setUrlQuery,
  onResetFilters
}) => {
  const styles = (0, _use_styles.useStyles)();
  const {
    isLastLimitedPage,
    limitedTotalItemCount
  } = (0, _get_limit_properties.useLimitProperties)({
    total: data === null || data === void 0 ? void 0 : data.total,
    pageIndex,
    pageSize
  });
  const columns = (0, _react.useMemo)(() => {
    if (!(data !== null && data !== void 0 && data.page)) {
      return [];
    }
    return (0, _get_vulnerabilities_grid_cell_actions.getVulnerabilitiesGridCellActions)({
      columnGridFn: _vulnerabilities_by_resource_table_columns.getVulnerabilitiesByResourceColumnsGrid,
      columns: _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns,
      dataView,
      pageSize,
      data: data.page,
      setUrlQuery,
      filters: urlQuery.filters
    });
  }, [data, dataView, pageSize, setUrlQuery, urlQuery.filters]);
  const renderCellValue = (0, _react.useMemo)(() => {
    const Cell = ({
      columnId,
      rowIndex
    }) => {
      var _resourceVulnerabilit;
      const rowIndexFromPage = rowIndex > pageSize - 1 ? rowIndex % pageSize : rowIndex;
      const resourceVulnerabilityRow = data === null || data === void 0 ? void 0 : data.page[rowIndexFromPage];
      if (isFetching) return null;
      if (!(resourceVulnerabilityRow !== null && resourceVulnerabilityRow !== void 0 && (_resourceVulnerabilit = resourceVulnerabilityRow.resource) !== null && _resourceVulnerabilit !== void 0 && _resourceVulnerabilit.id)) return null;
      if (columnId === _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.resourceId) {
        var _resourceVulnerabilit2, _resourceVulnerabilit3, _resourceVulnerabilit4;
        return /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
          to: (0, _reactRouterDom.generatePath)(_constants2.findingsNavigation.resource_vulnerabilities.path, {
            resourceId: encodeURIComponent(resourceVulnerabilityRow === null || resourceVulnerabilityRow === void 0 ? void 0 : (_resourceVulnerabilit2 = resourceVulnerabilityRow.resource) === null || _resourceVulnerabilit2 === void 0 ? void 0 : _resourceVulnerabilit2.id)
          }),
          className: "eui-textTruncate",
          title: resourceVulnerabilityRow === null || resourceVulnerabilityRow === void 0 ? void 0 : (_resourceVulnerabilit3 = resourceVulnerabilityRow.resource) === null || _resourceVulnerabilit3 === void 0 ? void 0 : _resourceVulnerabilit3.id
        }, resourceVulnerabilityRow === null || resourceVulnerabilityRow === void 0 ? void 0 : (_resourceVulnerabilit4 = resourceVulnerabilityRow.resource) === null || _resourceVulnerabilit4 === void 0 ? void 0 : _resourceVulnerabilit4.id);
      }
      if (columnId === _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.resourceName) {
        var _resourceVulnerabilit5;
        return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, resourceVulnerabilityRow === null || resourceVulnerabilityRow === void 0 ? void 0 : (_resourceVulnerabilit5 = resourceVulnerabilityRow.resource) === null || _resourceVulnerabilit5 === void 0 ? void 0 : _resourceVulnerabilit5.name);
      }
      if (columnId === _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.region) {
        var _resourceVulnerabilit6;
        return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, resourceVulnerabilityRow === null || resourceVulnerabilityRow === void 0 ? void 0 : (_resourceVulnerabilit6 = resourceVulnerabilityRow.cloud) === null || _resourceVulnerabilit6 === void 0 ? void 0 : _resourceVulnerabilit6.region);
      }
      if (columnId === _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.vulnerabilities_count) {
        return /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
          color: "hollow",
          "data-test-subj": _test_subjects.VULNERABILITY_RESOURCE_COUNT
        }, resourceVulnerabilityRow.vulnerabilities_count);
      }
      if (columnId === _vulnerabilities_by_resource_table_columns.vulnerabilitiesByResourceColumns.severity_map) {
        return /*#__PURE__*/_react.default.createElement(_severity_map.SeverityMap, {
          total: resourceVulnerabilityRow.vulnerabilities_count,
          severityMap: resourceVulnerabilityRow.severity_map
        });
      }
      return null;
    };
    return Cell;
  }, [data === null || data === void 0 ? void 0 : data.page, pageSize, isFetching]);
  if ((data === null || data === void 0 ? void 0 : data.page.length) === 0) {
    return /*#__PURE__*/_react.default.createElement(_empty_state.EmptyState, {
      onResetFilters: onResetFilters
    });
  }
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiProgress, {
    size: "xs",
    color: "accent",
    style: {
      opacity: isFetching ? 1 : 0
    }
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiDataGrid, {
    className: styles.gridStyle,
    "aria-label": _translations.VULNERABILITIES,
    columns: columns,
    columnVisibility: {
      visibleColumns: columns.map(({
        id
      }) => id),
      setVisibleColumns: () => {}
    },
    rowCount: limitedTotalItemCount,
    toolbarVisibility: {
      showColumnSelector: false,
      showDisplaySelector: false,
      showKeyboardShortcuts: false,
      showSortSelector: false,
      showFullScreenSelector: false,
      additionalControls: {
        left: {
          prepend: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
            size: "xs",
            color: "text"
          }, _i18n.i18n.translate('xpack.csp.vulnerabilitiesByResource.totalResources', {
            defaultMessage: '{total, plural, one {# Resource} other {# Resources}}',
            values: {
              total: data === null || data === void 0 ? void 0 : data.total
            }
          })), /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
            size: "xs",
            color: "text"
          }, _i18n.i18n.translate('xpack.csp.vulnerabilitiesByResource.totalVulnerabilities', {
            defaultMessage: '{total, plural, one {# Vulnerability} other {# Vulnerabilities}}',
            values: {
              total: data === null || data === void 0 ? void 0 : data.total_vulnerabilities
            }
          })))
        },
        right: /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
          grow: false,
          className: styles.groupBySelector
        }, /*#__PURE__*/_react.default.createElement(_findings_group_by_selector.FindingsGroupBySelector, {
          type: "resource",
          pathnameHandler: _vulnerabilities_pathname_handler.vulnerabilitiesPathnameHandler
        }))
      }
    },
    gridStyle: {
      border: 'horizontal',
      cellPadding: 'l',
      stripes: false,
      rowHover: 'none',
      header: 'underline'
    },
    renderCellValue: renderCellValue,
    inMemory: {
      level: 'enhancements'
    },
    sorting: {
      columns: sort,
      onSort
    },
    pagination: {
      pageIndex,
      pageSize,
      pageSizeOptions: [10, 25, 100],
      onChangeItemsPerPage,
      onChangePage
    }
  }), isLastLimitedPage && /*#__PURE__*/_react.default.createElement(_findings_layout.LimitedResultsBar, null));
};
const VulnerabilitiesByResource = ({
  dataView
}) => {
  var _sort$;
  const {
    pageIndex,
    onChangeItemsPerPage,
    onChangePage,
    pageSize,
    query,
    sort,
    onSort,
    queryError,
    urlQuery,
    setUrlQuery,
    onResetFilters
  } = (0, _use_cloud_posture_table.useCloudPostureTable)({
    dataView,
    defaultQuery: getDefaultQuery,
    paginationLocalStorageKey: _constants.LOCAL_STORAGE_PAGE_SIZE_FINDINGS_KEY
  });
  const {
    data,
    isLoading,
    isFetching
  } = (0, _use_latest_vulnerabilities_by_resource.useLatestVulnerabilitiesByResource)({
    query,
    sortOrder: (_sort$ = sort[0]) === null || _sort$ === void 0 ? void 0 : _sort$.direction,
    enabled: !queryError,
    pageIndex,
    pageSize
  });
  const error = queryError || null;
  if (isLoading && !error) {
    return (0, _cloud_posture_page.defaultLoadingRenderer)();
  }
  if (!(data !== null && data !== void 0 && data.page) && !error) {
    return (0, _cloud_posture_page.defaultNoDataRenderer)();
  }
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_findings_search_bar.FindingsSearchBar, {
    dataView: dataView,
    setQuery: newQuery => {
      setUrlQuery({
        ...newQuery,
        pageIndex: 0
      });
    },
    loading: isFetching,
    placeholder: _translations.SEARCH_BAR_PLACEHOLDER
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), error && /*#__PURE__*/_react.default.createElement(_error_callout.ErrorCallout, {
    error: error
  }), !error && /*#__PURE__*/_react.default.createElement(VulnerabilitiesByResourceDataGrid, {
    dataView: dataView,
    data: data,
    isFetching: isFetching,
    pageIndex: pageIndex,
    sort: sort,
    pageSize: pageSize,
    onChangeItemsPerPage: onChangeItemsPerPage,
    onChangePage: onChangePage,
    onSort: onSort,
    urlQuery: urlQuery,
    setUrlQuery: setUrlQuery,
    onResetFilters: onResetFilters
  }));
};
exports.VulnerabilitiesByResource = VulnerabilitiesByResource;