"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getClusterIdQuery = exports.BenchmarksSection = void 0;
var _react = _interopRequireWildcard(require("react"));
var _useLocalStorage = _interopRequireDefault(require("react-use/lib/useLocalStorage"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _react2 = require("@emotion/react");
var _i18n = require("@kbn/i18n");
var _constants = require("../../../common/constants");
var _risks_table = require("../compliance_charts/risks_table");
var _constants2 = require("../../../../common/constants");
var _use_navigate_findings = require("../../../common/hooks/use_navigate_findings");
var _cluster_details_box = require("./cluster_details_box");
var _summary_section = require("./summary_section");
var _test_subjects = require("../test_subjects");
var _compliance_score_chart = require("../compliance_charts/compliance_score_chart");
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 CLUSTER_DEFAULT_SORT_ORDER = 'asc';
const getClusterIdQuery = cluster => {
  if (cluster.meta.benchmark.posture_type === _constants2.CSPM_POLICY_TEMPLATE) {
    // TODO: remove assertion after typing CspFinding as discriminating union
    return {
      'cloud.account.id': cluster.meta.cloud.account.id
    };
  }
  return {
    cluster_id: cluster.meta.assetIdentifierId
  };
};
exports.getClusterIdQuery = getClusterIdQuery;
const BenchmarksSection = ({
  complianceData,
  dashboardType
}) => {
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const navToFindings = (0, _use_navigate_findings.useNavigateFindings)();
  const [clusterSorting, setClusterSorting] = (0, _useLocalStorage.default)(_constants.LOCAL_STORAGE_DASHBOARD_CLUSTER_SORT_KEY, CLUSTER_DEFAULT_SORT_ORDER);
  const isClusterSortingAsc = clusterSorting === 'asc';
  const clusterSortingIcon = isClusterSortingAsc ? 'sortUp' : 'sortDown';
  const navToFindingsByClusterAndEvaluation = (cluster, evaluation) => {
    navToFindings({
      ...(0, _summary_section.getPolicyTemplateQuery)(dashboardType),
      ...getClusterIdQuery(cluster),
      'result.evaluation': evaluation
    });
  };
  const navToFailedFindingsByClusterAndSection = (cluster, ruleSection) => {
    navToFindings({
      ...(0, _summary_section.getPolicyTemplateQuery)(dashboardType),
      ...getClusterIdQuery(cluster),
      'rule.section': ruleSection,
      'result.evaluation': _constants2.RULE_FAILED
    });
  };
  const navToFailedFindingsByCluster = cluster => {
    navToFindingsByClusterAndEvaluation(cluster, _constants2.RULE_FAILED);
  };
  const toggleClustersSortingDirection = () => {
    setClusterSorting(isClusterSortingAsc ? 'desc' : 'asc');
  };
  const clusters = (0, _react.useMemo)(() => {
    return [...complianceData.clusters].sort((clusterA, clusterB) => isClusterSortingAsc ? clusterA.stats.postureScore - clusterB.stats.postureScore : clusterB.stats.postureScore - clusterA.stats.postureScore);
  }, [complianceData.clusters, isClusterSortingAsc]);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    css: (0, _react2.css)`
        border-bottom: ${euiTheme.border.thick};
        border-bottom-color: ${euiTheme.colors.text};
        padding-bottom: ${euiTheme.size.s};
        .euiTitle {
          font-weight: ${euiTheme.font.weight.semiBold};
        };
        button {
          text-align: left;
        },
      `
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.first
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xxs"
  }, /*#__PURE__*/_react.default.createElement("div", null, dashboardType === _constants2.KSPM_POLICY_TEMPLATE ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.csp.dashboard.benchmarkSection.columnsHeader.clusterNameTitle",
    defaultMessage: "Cluster Name"
  }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.csp.dashboard.benchmarkSection.columnsHeader.accountNameTitle",
    defaultMessage: "Account Name"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.second
  }, /*#__PURE__*/_react.default.createElement("button", {
    "data-test-subj": _test_subjects.DASHBOARD_TABLE_HEADER_SCORE_TEST_ID,
    onClick: toggleClustersSortingDirection
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xxs"
  }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.csp.dashboard.benchmarkSection.columnsHeader.postureScoreTitle",
    defaultMessage: "Posture Score"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    className: "euiTableSortIcon",
    type: clusterSortingIcon
  }))))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.third
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xxs"
  }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.csp.dashboard.benchmarkSection.columnsHeader.complianceByCisSectionTitle",
    defaultMessage: "Compliance by CIS Section"
  }))))), clusters.map(cluster => /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    key: cluster.meta.assetIdentifierId,
    css: (0, _react2.css)`
            // card height with 3 items in risk table
            height: 200px;
            border-bottom: ${euiTheme.border.thin};
            padding: ${euiTheme.size.base} 0 ${euiTheme.size.l};
          `
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.first
  }, /*#__PURE__*/_react.default.createElement(_cluster_details_box.ClusterDetailsBox, {
    cluster: cluster
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.second,
    css: (0, _react2.css)`
              margin-left: -${euiTheme.size.s};
            `,
    "data-test-subj": _test_subjects.DASHBOARD_TABLE_COLUMN_SCORE_TEST_ID
  }, /*#__PURE__*/_react.default.createElement(_compliance_score_chart.ComplianceScoreChart, {
    compact: true,
    id: `${cluster.meta.assetIdentifierId}_score_chart`,
    data: cluster.stats,
    trend: cluster.trend,
    onEvalCounterClick: evaluation => navToFindingsByClusterAndEvaluation(cluster, evaluation)
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: _summary_section.dashboardColumnsGrow.third
  }, /*#__PURE__*/_react.default.createElement("div", {
    style: {
      paddingRight: euiTheme.size.base
    }
  }, /*#__PURE__*/_react.default.createElement(_risks_table.RisksTable, {
    compact: true,
    data: cluster.groupedFindingsEvaluation,
    maxItems: 3,
    onCellClick: resourceTypeName => navToFailedFindingsByClusterAndSection(cluster, resourceTypeName),
    viewAllButtonTitle: _i18n.i18n.translate('xpack.csp.dashboard.risksTable.clusterCardViewAllButtonTitle', {
      defaultMessage: 'View all failed findings for this {postureAsset}',
      values: {
        postureAsset: dashboardType === _constants2.CSPM_POLICY_TEMPLATE ? 'cloud account' : 'cluster'
      }
    }),
    onViewAllClick: () => navToFailedFindingsByCluster(cluster)
  }))))));
};
exports.BenchmarksSection = BenchmarksSection;