"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UrlComboBox = void 0;
var _react = _interopRequireDefault(require("react"));
var _kea = require("kea");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _url_combo_box_logic = require("./url_combo_box_logic");
require("./url_combo_box.scss");
/*
 * 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 isUrl = value => {
  let url;
  try {
    url = new URL(value);
  } catch (_) {
    return false;
  }
  return url.protocol === 'http:' || url.protocol === 'https:';
};
const UrlComboBox = ({
  label,
  selectedUrls,
  onChange
}) => {
  const id = (0, _eui.useGeneratedHtmlId)();
  const urlComboBoxLogic = (0, _url_combo_box_logic.UrlComboBoxLogic)({
    id
  });
  const {
    isInvalid
  } = (0, _kea.useValues)(urlComboBoxLogic);
  const {
    setIsInvalid
  } = (0, _kea.useActions)(urlComboBoxLogic);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    className: "urlComboBox",
    fullWidth: true,
    label: label,
    isInvalid: isInvalid,
    error: isInvalid ? _i18n.i18n.translate('xpack.enterpriseSearch.crawler.urlComboBox.invalidUrlErrorMessage', {
      defaultMessage: 'Please enter a valid URL'
    }) : undefined
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiComboBox, {
    fullWidth: true,
    noSuggestions: true,
    selectedOptions: selectedUrls.map(selectedUrl => ({
      label: selectedUrl
    })),
    onCreateOption: newUrl => {
      if (!isUrl(newUrl)) {
        setIsInvalid(true);
        // Return false to explicitly reject the user's input.
        return false;
      }
      setIsInvalid(false);
      onChange([...selectedUrls, newUrl]);
    },
    onSearchChange: () => {
      setIsInvalid(false);
    },
    onChange: newOptions => {
      onChange(newOptions.map(newOption => newOption.label));
    },
    isInvalid: isInvalid
  }));
};
exports.UrlComboBox = UrlComboBox;