"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PackagePoliciesTable = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _common = require("../../../../../../../../common");
var _constants = require("../../../../../../../constants");
var _components = require("../../../../../components");
var _hooks = require("../../../../../hooks");
var _services = require("../../../../../services");
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 stringSortAscending = (a, b) => a.localeCompare(b);
const toFilterOption = value => ({
  name: value,
  value
});
const PackagePoliciesTable = ({
  packagePolicies: originalPackagePolicies,
  agentPolicy,
  ...rest
}) => {
  var _permissionCheck$data, _permissionCheck$data2;
  const {
    application
  } = (0, _hooks.useStartServices)();
  const canWriteIntegrationPolicies = (0, _hooks.useAuthz)().integrations.writeIntegrationPolicies;
  const canReadIntegrationPolicies = (0, _hooks.useAuthz)().integrations.readIntegrationPolicies;
  const {
    isPackagePolicyUpgradable
  } = (0, _hooks.useIsPackagePolicyUpgradable)();
  const {
    getHref
  } = (0, _hooks.useLink)();
  const permissionCheck = (0, _hooks.usePermissionCheck)();
  const missingSecurityConfiguration = !((_permissionCheck$data = permissionCheck.data) !== null && _permissionCheck$data !== void 0 && _permissionCheck$data.success) && ((_permissionCheck$data2 = permissionCheck.data) === null || _permissionCheck$data2 === void 0 ? void 0 : _permissionCheck$data2.error) === 'MISSING_SECURITY';

  // With the package policies provided on input, generate the list of package policies
  // used in the InMemoryTable (flattens some values for search) as well as
  // the list of options that will be used in the filters dropdowns
  const [packagePolicies, namespaces] = (0, _react.useMemo)(() => {
    const namespacesValues = new Set();
    const mappedPackagePolicies = originalPackagePolicies.map(packagePolicy => {
      var _packagePolicy$packag, _packagePolicy$packag2, _packagePolicy$packag3, _packagePolicy$packag4, _packagePolicy$packag5, _packagePolicy$packag6;
      if (packagePolicy.namespace) {
        namespacesValues.add(packagePolicy.namespace);
      }
      const hasUpgrade = isPackagePolicyUpgradable(packagePolicy);
      return {
        ...packagePolicy,
        packageName: (_packagePolicy$packag = (_packagePolicy$packag2 = packagePolicy.package) === null || _packagePolicy$packag2 === void 0 ? void 0 : _packagePolicy$packag2.name) !== null && _packagePolicy$packag !== void 0 ? _packagePolicy$packag : '',
        packageTitle: (_packagePolicy$packag3 = (_packagePolicy$packag4 = packagePolicy.package) === null || _packagePolicy$packag4 === void 0 ? void 0 : _packagePolicy$packag4.title) !== null && _packagePolicy$packag3 !== void 0 ? _packagePolicy$packag3 : '',
        packageVersion: (_packagePolicy$packag5 = (_packagePolicy$packag6 = packagePolicy.package) === null || _packagePolicy$packag6 === void 0 ? void 0 : _packagePolicy$packag6.version) !== null && _packagePolicy$packag5 !== void 0 ? _packagePolicy$packag5 : '',
        hasUpgrade
      };
    });
    const namespaceFilterOptions = [...namespacesValues].sort(stringSortAscending).map(toFilterOption);
    return [mappedPackagePolicies, namespaceFilterOptions];
  }, [originalPackagePolicies, isPackagePolicyUpgradable]);
  const columns = (0, _react.useMemo)(() => [{
    field: 'name',
    sortable: true,
    truncateText: true,
    name: _i18n.i18n.translate('xpack.fleet.policyDetails.packagePoliciesTable.nameColumnTitle', {
      defaultMessage: 'Name'
    }),
    render: (value, packagePolicy) => /*#__PURE__*/_react.default.createElement(_eui.EuiLink, (0, _extends2.default)({
      title: value
    }, canReadIntegrationPolicies ? {
      href: getHref('edit_integration', {
        policyId: agentPolicy.id,
        packagePolicyId: packagePolicy.id
      })
    } : {
      disabled: true
    }), /*#__PURE__*/_react.default.createElement("span", {
      className: "eui-textTruncate",
      title: value
    }, value), packagePolicy.description ? /*#__PURE__*/_react.default.createElement("span", null, "\xA0", /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
      content: packagePolicy.description
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      type: "help"
    }))) : null)
  }, {
    field: 'packageTitle',
    sortable: true,
    name: _i18n.i18n.translate('xpack.fleet.policyDetails.packagePoliciesTable.packageNameColumnTitle', {
      defaultMessage: 'Integration'
    }),
    render(packageTitle, packagePolicy) {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
        gutterSize: "s",
        alignItems: "center"
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        "data-test-subj": "PackagePoliciesTableLink",
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
        href: packagePolicy.package && getHref('integration_details_overview', {
          pkgkey: (0, _services.pkgKeyFromPackageInfo)(packagePolicy.package)
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
        gutterSize: "s",
        alignItems: "center"
      }, packagePolicy.package && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_components.PackageIcon, {
        packageName: packagePolicy.package.name,
        version: packagePolicy.package.version,
        size: "m",
        tryApi: true
      })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, packageTitle), packagePolicy.package && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
        color: "subdued",
        size: "xs",
        className: "eui-textNoWrap"
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.fleet.policyDetails.packagePoliciesTable.packageVersion",
        defaultMessage: "v{version}",
        values: {
          version: packagePolicy.package.version
        }
      })))))), packagePolicy.hasUpgrade && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiToolTip, {
        content: _i18n.i18n.translate('xpack.fleet.policyDetails.packagePoliciesTable.upgradeAvailable', {
          defaultMessage: 'Upgrade Available'
        })
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "warning",
        color: "warning"
      }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
        "data-test-subj": "PackagePoliciesTableUpgradeButton",
        size: "s",
        minWidth: "0",
        isDisabled: !canWriteIntegrationPolicies,
        href: `${getHref('upgrade_package_policy', {
          policyId: agentPolicy.id,
          packagePolicyId: packagePolicy.id
        })}?from=fleet-policy-list`
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.fleet.policyDetails.packagePoliciesTable.upgradeButton",
        defaultMessage: "Upgrade"
      })))));
    }
  }, {
    field: 'namespace',
    name: _i18n.i18n.translate('xpack.fleet.policyDetails.packagePoliciesTable.namespaceColumnTitle', {
      defaultMessage: 'Namespace'
    }),
    render: namespace => {
      return namespace ? /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
        color: "hollow"
      }, namespace) : '';
    }
  }, {
    name: _i18n.i18n.translate('xpack.fleet.policyDetails.packagePoliciesTable.actionsColumnTitle', {
      defaultMessage: 'Actions'
    }),
    actions: [{
      render: packagePolicy => {
        return canWriteIntegrationPolicies ? /*#__PURE__*/_react.default.createElement(_components.PackagePolicyActionsMenu, {
          agentPolicy: agentPolicy,
          packagePolicy: packagePolicy,
          upgradePackagePolicyHref: `${getHref('upgrade_package_policy', {
            policyId: agentPolicy.id,
            packagePolicyId: packagePolicy.id
          })}?from=fleet-policy-list`
        }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);
      }
    }]
  }], [agentPolicy, getHref, canWriteIntegrationPolicies, canReadIntegrationPolicies]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, (0, _extends2.default)({
    itemId: "id",
    items: packagePolicies,
    columns: columns,
    sorting: {
      sort: {
        field: 'name',
        direction: 'asc'
      }
    }
  }, rest, {
    search: {
      toolsRight: agentPolicy.is_managed ? [] : [/*#__PURE__*/_react.default.createElement(_components.EuiButtonWithTooltip, {
        key: "addPackagePolicyButton",
        fill: true,
        isDisabled: !canWriteIntegrationPolicies,
        iconType: "plusInCircle",
        onClick: () => {
          application.navigateToApp(_common.INTEGRATIONS_PLUGIN_ID, {
            path: _constants.pagePathGetters.integrations_all({})[1],
            state: {
              forAgentPolicyId: agentPolicy.id
            }
          });
        },
        "data-test-subj": "addPackagePolicyButton",
        tooltip: !canWriteIntegrationPolicies ? {
          content: missingSecurityConfiguration ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.epm.addPackagePolicyButtonSecurityRequiredTooltip",
            defaultMessage: "To add Elastic Agent Integrations, you must have security enabled and have the All privilege for Fleet. Contact your administrator."
          }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.fleet.epm.addPackagePolicyButtonPrivilegesRequiredTooltip",
            defaultMessage: "Elastic Agent Integrations require the All privilege for Fleet and All privilege for Integrations. Contact your administrator."
          })
        } : undefined
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.fleet.policyDetails.addPackagePolicyButtonText",
        defaultMessage: "Add integration"
      }))],
      box: {
        incremental: true,
        schema: true
      },
      filters: [{
        type: 'field_value_selection',
        field: 'namespace',
        name: 'Namespace',
        options: namespaces,
        multiSelect: 'or',
        operator: 'exact'
      }]
    },
    isSelectable: false
  }));
};
exports.PackagePoliciesTable = PackagePoliciesTable;