"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFleetServerHostsForm = useFleetServerHostsForm;
exports.validateFleetServerHosts = validateFleetServerHosts;
exports.validateName = validateName;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _hooks = require("../../../../hooks");
var _services = require("../../../../../../../common/services");
var _use_confirm_modal = require("../../hooks/use_confirm_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.
 */
// copy this one

const URL_REGEX = /^(https):\/\/[^\s$.?#].[^\s]*$/gm;
const ConfirmTitle = () => /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
  id: "xpack.fleet.settings.fleetServerHostsFlyout.confirmModalTitle",
  defaultMessage: "Save and deploy changes?"
});
const ConfirmDescription = ({}) => /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
  id: "xpack.fleet.settings.fleetServerHostsFlyout.confirmModalText",
  defaultMessage: "This action will update agent policies enrolled in this Fleet Server. This action can not be undone. Are you sure you wish to continue?"
});
function validateFleetServerHosts(value) {
  if (value.length === 0) {
    return [{
      message: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsEmptyError', {
        defaultMessage: 'At least one URL is required'
      })
    }];
  }
  const res = [];
  const hostIndexes = {};
  value.forEach((val, idx) => {
    if (!val) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsRequiredError', {
          defaultMessage: 'Host URL is required'
        }),
        index: idx
      });
    } else if (!val.match(URL_REGEX)) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsError', {
          defaultMessage: 'Invalid URL (must be an https URL)'
        }),
        index: idx
      });
    }
    const curIndexes = hostIndexes[val] || [];
    hostIndexes[val] = [...curIndexes, idx];
  });
  Object.values(hostIndexes).filter(({
    length
  }) => length > 1).forEach(indexes => {
    indexes.forEach(index => res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsDuplicateError', {
        defaultMessage: 'Duplicate URL'
      }),
      index
    }));
  });
  if (res.length) {
    return res;
  }
  if (value.length && (0, _services.isDiffPathProtocol)(value)) {
    return [{
      message: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsDifferentPathOrProtocolError', {
        defaultMessage: 'Protocol and path must be the same for each URL'
      })
    }];
  }
}
function validateName(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.fleetServerHost.nameIsRequiredErrorMessage', {
      defaultMessage: 'Name is required'
    })];
  }
}
function useFleetServerHostsForm(fleetServerHost, onSuccess) {
  var _fleetServerHost$is_p, _fleetServerHost$name, _fleetServerHost$is_d, _fleetServerHost$prox;
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const {
    confirm
  } = (0, _use_confirm_modal.useConfirmModal)();
  const isPreconfigured = (_fleetServerHost$is_p = fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.is_preconfigured) !== null && _fleetServerHost$is_p !== void 0 ? _fleetServerHost$is_p : false;
  const nameInput = (0, _hooks.useInput)((_fleetServerHost$name = fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.name) !== null && _fleetServerHost$name !== void 0 ? _fleetServerHost$name : '', validateName, isPreconfigured);
  const isDefaultInput = (0, _hooks.useSwitchInput)((_fleetServerHost$is_d = fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.is_default) !== null && _fleetServerHost$is_d !== void 0 ? _fleetServerHost$is_d : false, isPreconfigured || (fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.is_default));
  const hostUrlsInput = (0, _hooks.useComboInput)('hostUrls', (fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.host_urls) || [], validateFleetServerHosts, isPreconfigured);
  const proxyIdInput = (0, _hooks.useInput)((_fleetServerHost$prox = fleetServerHost === null || fleetServerHost === void 0 ? void 0 : fleetServerHost.proxy_id) !== null && _fleetServerHost$prox !== void 0 ? _fleetServerHost$prox : '', () => undefined, isPreconfigured);
  const inputs = (0, _react.useMemo)(() => ({
    nameInput,
    isDefaultInput,
    hostUrlsInput,
    proxyIdInput
  }), [nameInput, isDefaultInput, hostUrlsInput, proxyIdInput]);
  const validate = (0, _react.useCallback)(() => (0, _hooks.validateInputs)(inputs), [inputs]);
  const submit = (0, _react.useCallback)(async () => {
    try {
      if (!validate()) {
        return;
      }
      if (!(await confirm( /*#__PURE__*/_react.default.createElement(ConfirmTitle, null), /*#__PURE__*/_react.default.createElement(ConfirmDescription, null)))) {
        return;
      }
      setIsLoading(true);
      const data = {
        name: nameInput.value,
        host_urls: hostUrlsInput.value,
        is_default: isDefaultInput.value,
        proxy_id: proxyIdInput.value !== '' ? proxyIdInput.value : null
      };
      if (fleetServerHost) {
        const res = await (0, _hooks.sendPutFleetServerHost)(fleetServerHost.id, data);
        if (res.error) {
          throw res.error;
        }
      } else {
        const res = await (0, _hooks.sendPostFleetServerHost)(data);
        if (res.error) {
          throw res.error;
        }
      }
      notifications.toasts.addSuccess(_i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsFlyout.successToastTitle', {
        defaultMessage: 'Fleet Server host saved'
      }));
      setIsLoading(false);
      await onSuccess();
    } catch (error) {
      setIsLoading(false);
      notifications.toasts.addError(error, {
        title: _i18n.i18n.translate('xpack.fleet.settings.fleetServerHostsFlyout.errorToastTitle', {
          defaultMessage: 'An error happened while saving Fleet Server host'
        })
      });
    }
  }, [fleetServerHost, nameInput.value, hostUrlsInput.value, isDefaultInput.value, proxyIdInput.value, validate, notifications, confirm, onSuccess]);
  const isDisabled = isLoading || !hostUrlsInput.hasChanged && !isDefaultInput.hasChanged && !nameInput.hasChanged && !proxyIdInput.hasChanged || hostUrlsInput.props.isInvalid || nameInput.props.isInvalid;
  return {
    isLoading,
    isDisabled,
    submit,
    inputs
  };
}