"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SettingsView = void 0;
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _lodash = require("lodash");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _hooks = require("../../../../../hooks");
var _components = require("../../../components");
var _components2 = require("../../../../../components");
var _services = require("../../../../../services");
var _services2 = 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 pickAgentPolicyKeysToSend = agentPolicy => (0, _lodash.pick)(agentPolicy, ['name', 'description', 'namespace', 'monitoring_enabled', 'unenroll_timeout', 'inactivity_timeout', 'data_output_id', 'monitoring_output_id', 'download_source_id', 'fleet_server_host_id', 'agent_features', 'is_protected']);
const FormWrapper = _styledComponents.default.div`
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
`;
const SettingsView = /*#__PURE__*/(0, _react.memo)(({
  agentPolicy: originalAgentPolicy
}) => {
  (0, _hooks.useBreadcrumbs)('policy_details', {
    policyName: originalAgentPolicy.name
  });
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const {
    agents: {
      enabled: isFleetEnabled
    }
  } = (0, _hooks.useConfig)();
  const hasFleetAllPrivileges = (0, _hooks.useAuthz)().fleet.all;
  const refreshAgentPolicy = (0, _hooks.useAgentPolicyRefresh)();
  const [agentPolicy, setAgentPolicy] = (0, _react.useState)({
    ...originalAgentPolicy
  });
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [hasChanges, setHasChanges] = (0, _react.useState)(false);
  const [agentCount, setAgentCount] = (0, _react.useState)(0);
  const [withSysMonitoring, setWithSysMonitoring] = (0, _react.useState)(true);
  const validation = (0, _components.agentPolicyFormValidation)(agentPolicy);
  const updateAgentPolicy = updatedFields => {
    setAgentPolicy({
      ...agentPolicy,
      ...updatedFields
    });
    setHasChanges(true);
  };
  const submitUpdateAgentPolicy = async () => {
    setIsLoading(true);
    try {
      const {
        data,
        error
      } = await (0, _hooks.sendUpdateAgentPolicy)(agentPolicy.id, pickAgentPolicyKeysToSend(agentPolicy));
      if (data) {
        notifications.toasts.addSuccess(_i18n.i18n.translate('xpack.fleet.editAgentPolicy.successNotificationTitle', {
          defaultMessage: "Successfully updated '{name}' settings",
          values: {
            name: agentPolicy.name
          }
        }));
        refreshAgentPolicy();
        setHasChanges(false);
      } else {
        notifications.toasts.addDanger(error ? error.message : _i18n.i18n.translate('xpack.fleet.editAgentPolicy.errorNotificationTitle', {
          defaultMessage: 'Unable to update agent policy'
        }));
      }
    } catch (e) {
      notifications.toasts.addDanger(_i18n.i18n.translate('xpack.fleet.editAgentPolicy.errorNotificationTitle', {
        defaultMessage: 'Unable to update agent policy'
      }));
    }
    setIsLoading(false);
  };
  const {
    showDevtoolsRequest
  } = _services.ExperimentalFeaturesService.get();
  const devtoolRequest = (0, _react.useMemo)(() => (0, _services2.generateUpdateAgentPolicyDevToolsRequest)(agentPolicy.id, pickAgentPolicyKeysToSend(agentPolicy)), [agentPolicy]);
  const onSubmit = async () => {
    // Retrieve agent count if fleet is enabled
    if (isFleetEnabled) {
      setIsLoading(true);
      const {
        data
      } = await (0, _hooks.sendGetAgentStatus)({
        policyId: agentPolicy.id
      });
      if (data !== null && data !== void 0 && data.results.total) {
        setAgentCount(data.results.total);
      } else {
        await submitUpdateAgentPolicy();
      }
    } else {
      await submitUpdateAgentPolicy();
    }
  };
  return /*#__PURE__*/_react.default.createElement(FormWrapper, null, agentCount ? /*#__PURE__*/_react.default.createElement(_components.ConfirmDeployAgentPolicyModal, {
    agentCount: agentCount,
    agentPolicy: agentPolicy,
    onConfirm: () => {
      setAgentCount(0);
      submitUpdateAgentPolicy();
    },
    onCancel: () => {
      setAgentCount(0);
      setIsLoading(false);
    }
  }) : null, /*#__PURE__*/_react.default.createElement(_components.AgentPolicyForm, {
    agentPolicy: agentPolicy,
    updateAgentPolicy: updateAgentPolicy,
    withSysMonitoring: withSysMonitoring,
    updateSysMonitoring: newValue => setWithSysMonitoring(newValue),
    validation: validation,
    isEditing: true
  }), hasChanges ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xl"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xl"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiBottomBar, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    justifyContent: "spaceBetween",
    alignItems: "center"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.editAgentPolicy.unsavedChangesText",
    defaultMessage: "You have unsaved changes"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    gutterSize: "s",
    justifyContent: "flexEnd"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    color: "ghost",
    onClick: () => {
      setAgentPolicy({
        ...originalAgentPolicy
      });
      setHasChanges(false);
    }
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.editAgentPolicy.cancelButtonText",
    defaultMessage: "Cancel"
  }))), showDevtoolsRequest ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_components2.DevtoolsRequestFlyoutButton, {
    isDisabled: isLoading || Object.keys(validation).length > 0,
    btnProps: {
      color: 'ghost'
    },
    description: _i18n.i18n.translate('xpack.fleet.editAgentPolicy.devtoolsRequestDescription', {
      defaultMessage: 'This Kibana request updates an agent policy.'
    }),
    request: devtoolRequest
  })) : null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    onClick: onSubmit,
    isLoading: isLoading,
    isDisabled: !hasFleetAllPrivileges || isLoading || Object.keys(validation).length > 0,
    iconType: "save",
    color: "primary",
    fill: true
  }, isLoading ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.editAgentPolicy.savingButtonText",
    defaultMessage: "Saving\u2026"
  }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.editAgentPolicy.saveButtonText",
    defaultMessage: "Save changes"
  })))))))) : null);
});
exports.SettingsView = SettingsView;