"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SettingsPage = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _i18nReact = require("@kbn/i18n-react");
var _lt = _interopRequireDefault(require("semver/functions/lt"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _transform_install_as_current_user_callout = require("../../../../../../../components/transform_install_as_current_user_callout");
var _types = require("../../../../../types");
var _hooks = require("../../../../../hooks");
var _constants = require("../../../../../constants");
var _components = require("../components");
var _install_button = require("./install_button");
var _reinstall_button = require("./reinstall_button");
var _update_button = require("./update_button");
var _uninstall_button = require("./uninstall_button");
var _changelog_modal = require("./changelog_modal");
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 SettingsTitleCell = _styledComponents.default.td`
  padding-right: ${props => props.theme.eui.euiSizeXL};
  padding-bottom: ${props => props.theme.eui.euiSizeM};
`;
const NoteLabel = () => /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
  id: "xpack.fleet.integrations.settings.packageUninstallNoteDescription.packageUninstallNoteLabel",
  defaultMessage: "Note:"
}));
const UpdatesAvailableMsg = ({
  latestVersion,
  toggleChangelogModal
}) => /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
  color: "warning",
  iconType: "warning",
  title: _i18n.i18n.translate('xpack.fleet.integrations.settings.versionInfo.updatesAvailable', {
    defaultMessage: 'New version available'
  })
}, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
  gutterSize: "xs"
}, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
  grow: false
}, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
  id: "xpack.fleet.integration.settings.versionInfo.updatesAvailableBody",
  defaultMessage: "Upgrade to version {latestVersion} to get the latest features.",
  values: {
    latestVersion
  }
})), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
  onClick: toggleChangelogModal
}, 'View changelog.')))));
const LatestVersionLink = ({
  name,
  version
}) => {
  const {
    getHref
  } = (0, _hooks.useLink)();
  const settingsPath = getHref('integration_details_settings', {
    pkgkey: `${name}-${version}`
  });
  return /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
    href: settingsPath
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageLatestVersionLink",
    defaultMessage: "latest version"
  }));
};
const SettingsPage = /*#__PURE__*/(0, _react.memo)(({
  packageInfo,
  theme$
}) => {
  var _packageInfo$installa;
  const {
    name,
    title,
    latestVersion,
    version,
    keepPoliciesUpToDate
  } = packageInfo;
  const [isUpgradingPackagePolicies, setIsUpgradingPackagePolicies] = (0, _react.useState)(false);
  const [isChangelogModalOpen, setIsChangelogModalOpen] = (0, _react.useState)(false);
  const toggleChangelogModal = (0, _react.useCallback)(() => {
    setIsChangelogModalOpen(!isChangelogModalOpen);
  }, [isChangelogModalOpen]);
  const getPackageInstallStatus = (0, _hooks.useGetPackageInstallStatus)();
  const {
    data: packagePoliciesData
  } = (0, _hooks.useGetPackagePoliciesQuery)({
    perPage: _constants.SO_SEARCH_LIMIT,
    page: 1,
    kuery: `${_constants.PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${name}`
  });
  const packagePolicyIds = (0, _react.useMemo)(() => packagePoliciesData === null || packagePoliciesData === void 0 ? void 0 : packagePoliciesData.items.map(({
    id
  }) => id), [packagePoliciesData]);
  const {
    data: dryRunData
  } = (0, _hooks.useUpgradePackagePolicyDryRunQuery)(packagePolicyIds !== null && packagePolicyIds !== void 0 ? packagePolicyIds : [], latestVersion, {
    enabled: packagePolicyIds && packagePolicyIds.length > 0
  });
  const updatePackageMutation = (0, _hooks.useUpdatePackageMutation)();
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const shouldShowKeepPoliciesUpToDateSwitch = (0, _react.useMemo)(() => {
    return _constants.KEEP_POLICIES_UP_TO_DATE_PACKAGES.some(pkg => pkg.name === name);
  }, [name]);
  const isShowKeepPoliciesUpToDateSwitchDisabled = (0, _react.useMemo)(() => {
    return _constants.AUTO_UPGRADE_POLICIES_PACKAGES.some(pkg => pkg.name === name);
  }, [name]);
  const [keepPoliciesUpToDateSwitchValue, setKeepPoliciesUpToDateSwitchValue] = (0, _react.useState)(keepPoliciesUpToDate !== null && keepPoliciesUpToDate !== void 0 ? keepPoliciesUpToDate : false);
  const handleKeepPoliciesUpToDateSwitchChange = (0, _react.useCallback)(() => {
    setKeepPoliciesUpToDateSwitchValue(prev => !prev);
    updatePackageMutation.mutate({
      pkgName: packageInfo.name,
      pkgVersion: packageInfo.version,
      body: {
        keepPoliciesUpToDate: !keepPoliciesUpToDateSwitchValue
      }
    }, {
      onSuccess: () => {
        notifications.toasts.addSuccess({
          title: _i18n.i18n.translate('xpack.fleet.integrations.integrationSaved', {
            defaultMessage: 'Integration settings saved'
          }),
          text: !keepPoliciesUpToDateSwitchValue ? _i18n.i18n.translate('xpack.fleet.integrations.keepPoliciesUpToDateEnabledSuccess', {
            defaultMessage: 'Fleet will automatically keep integration policies up to date for {title}',
            values: {
              title
            }
          }) : _i18n.i18n.translate('xpack.fleet.integrations.keepPoliciesUpToDateDisabledSuccess', {
            defaultMessage: 'Fleet will not automatically keep integration policies up to date for {title}',
            values: {
              title
            }
          })
        });
      },
      onError: error => {
        notifications.toasts.addError(error, {
          title: _i18n.i18n.translate('xpack.fleet.integrations.integrationSavedError', {
            defaultMessage: 'Error saving integration settings'
          }),
          toastMessage: _i18n.i18n.translate('xpack.fleet.integrations.keepPoliciesUpToDateError', {
            defaultMessage: 'Error saving integration settings for {title}',
            values: {
              title
            }
          })
        });
      }
    });
  }, [keepPoliciesUpToDateSwitchValue, notifications.toasts, packageInfo.name, packageInfo.version, title, updatePackageMutation]);
  const {
    status: installationStatus,
    version: installedVersion
  } = getPackageInstallStatus(name);
  const packageHasUsages = !!(packagePoliciesData !== null && packagePoliciesData !== void 0 && packagePoliciesData.total);
  const updateAvailable = installedVersion && (0, _lt.default)(installedVersion, latestVersion) ? true : false;
  const isViewingOldPackage = version < latestVersion;
  // hide install/remove options if the user has version of the package is installed
  // and this package is out of date or if they do have a version installed but it's not this one
  const hideInstallOptions = installationStatus === _types.InstallStatus.notInstalled && isViewingOldPackage || installationStatus === _types.InstallStatus.installed && installedVersion !== version;
  const isUpdating = installationStatus === _types.InstallStatus.installing && installedVersion;
  const {
    numOfAssets,
    numTransformAssets
  } = (0, _react.useMemo)(() => ({
    numTransformAssets: (0, _transform_install_as_current_user_callout.getNumTransformAssets)(packageInfo.assets),
    numOfAssets: Object.entries(packageInfo.assets).reduce((acc, [serviceName, serviceNameValue]) => acc + Object.entries(serviceNameValue).reduce((acc2, [assetName, assetNameValue]) => acc2 + assetNameValue.length, 0), 0)
  }), [packageInfo.assets]);
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "flexStart"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 1
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 6
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h3", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageSettingsTitle",
    defaultMessage: "Settings"
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), installedVersion !== null && /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageVersionTitle",
    defaultMessage: "{title} version",
    values: {
      title
    }
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement("table", null, /*#__PURE__*/_react.default.createElement("tbody", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement(SettingsTitleCell, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.versionInfo.installedVersion",
    defaultMessage: "Installed version"
  })), /*#__PURE__*/_react.default.createElement("td", null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xs",
    "data-test-subj": "epmSettings.installedVersionTitle"
  }, /*#__PURE__*/_react.default.createElement("span", null, installedVersion)))), /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement(SettingsTitleCell, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.versionInfo.latestVersion",
    defaultMessage: "Latest version"
  })), /*#__PURE__*/_react.default.createElement("td", null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "xs",
    "data-test-subj": "epmSettings.latestVersionTitle"
  }, /*#__PURE__*/_react.default.createElement("span", null, latestVersion)))))), shouldShowKeepPoliciesUpToDateSwitch && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_components.KeepPoliciesUpToDateSwitch, {
    checked: keepPoliciesUpToDateSwitchValue,
    onChange: handleKeepPoliciesUpToDateSwitchChange,
    disabled: isShowKeepPoliciesUpToDateSwitchDisabled
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "l"
  })), (updateAvailable || isUpgradingPackagePolicies) && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(UpdatesAvailableMsg, {
    latestVersion: latestVersion,
    toggleChangelogModal: toggleChangelogModal
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "l"
  }), /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_update_button.UpdateButton, (0, _extends2.default)({}, packageInfo, {
    version: latestVersion,
    packagePolicyIds: packagePolicyIds,
    dryRunData: dryRunData,
    isUpgradingPackagePolicies: isUpgradingPackagePolicies,
    setIsUpgradingPackagePolicies: setIsUpgradingPackagePolicies,
    theme$: theme$
  }))))), !hideInstallOptions && !isUpdating && /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), installationStatus === _types.InstallStatus.notInstalled || installationStatus === _types.InstallStatus.installing ? /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageInstallTitle",
    defaultMessage: "Install {title}",
    values: {
      title
    }
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), numTransformAssets > 0 ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_transform_install_as_current_user_callout.TransformInstallWithCurrentUserPermissionCallout, {
    count: numTransformAssets
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  })) : null, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageInstallDescription",
    defaultMessage: "Install this integration to setup Kibana and Elasticsearch assets designed for {title} data.",
    values: {
      title
    }
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_install_button.InstallButton, (0, _extends2.default)({}, packageInfo, {
    numOfAssets: numOfAssets,
    disabled: !packagePoliciesData || packageHasUsages
  })))))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    direction: "column",
    gutterSize: "m"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageUninstallTitle",
    defaultMessage: "Uninstall"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageUninstallDescription",
    defaultMessage: "Remove Kibana and Elasticsearch assets that were installed by this integration."
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_uninstall_button.UninstallButton, (0, _extends2.default)({}, packageInfo, {
    numOfAssets: numOfAssets,
    latestVersion: latestVersion,
    disabled: !packagePoliciesData || packageHasUsages
  })))), packageHasUsages && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    color: "subdued",
    size: "s"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageUninstallNoteDescription.packageUninstallNoteDetail",
    defaultMessage: "{strongNote} {title} cannot be uninstalled because there are active agents that use this integration. To uninstall, remove all {title} integrations from your agent policies.",
    values: {
      title,
      strongNote: /*#__PURE__*/_react.default.createElement(NoteLabel, null)
    }
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "l"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    direction: "column",
    gutterSize: "m"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageReinstallTitle",
    defaultMessage: "Reinstall"
  })))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageReinstallDescription",
    defaultMessage: "Reinstall Kibana and Elasticsearch assets for this integration."
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_reinstall_button.ReinstallButton, (0, _extends2.default)({}, packageInfo, {
    installSource: 'installationInfo' in packageInfo && (_packageInfo$installa = packageInfo.installationInfo) !== null && _packageInfo$installa !== void 0 && _packageInfo$installa.install_source ? packageInfo.installationInfo.install_source : ''
  }))))))), hideInstallOptions && isViewingOldPackage && !isUpdating && /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageInstallTitle",
    defaultMessage: "Install {title}",
    values: {
      title
    }
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "s"
  }), /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    color: "subdued"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.integrations.settings.packageSettingsOldVersionMessage",
    defaultMessage: "Version {version} is out of date. The {latestVersion} of this integration is available to be installed.",
    values: {
      version,
      latestVersion: /*#__PURE__*/_react.default.createElement(LatestVersionLink, {
        name: name,
        version: latestVersion
      })
    }
  })))))))), /*#__PURE__*/_react.default.createElement(_eui.EuiPortal, null, isChangelogModalOpen && /*#__PURE__*/_react.default.createElement(_changelog_modal.ChangelogModal, {
    currentVersion: version,
    latestVersion: latestVersion,
    packageName: name,
    onClose: toggleChangelogModal
  })));
});
exports.SettingsPage = SettingsPage;