"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TagsAddRemove = void 0;
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _i18n = require("@kbn/i18n");
var _hooks = require("../hooks");
var _utils = require("../utils");
var _tag_options = require("./tag_options");
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 TruncatedEuiHighlight = (0, _styledComponents.default)(_eui.EuiHighlight)`
  width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;
const TagsAddRemove = ({
  agentId,
  agents,
  allTags,
  selectedTags,
  button,
  onTagsUpdated,
  onClosePopover
}) => {
  const labelsFromTags = (0, _react.useCallback)((tags, selected) => tags.map(tag => ({
    label: tag,
    checked: selected.includes(tag) ? 'on' : undefined,
    onFocusBadge: false
  })), []);
  const [labels, setLabels] = (0, _react.useState)(labelsFromTags(allTags, selectedTags));
  const [searchValue, setSearchValue] = (0, _react.useState)(undefined);
  const [isPopoverOpen, setIsPopoverOpen] = (0, _react.useState)(true);
  const [isTagHovered, setIsTagHovered] = (0, _react.useState)({});
  const closePopover = () => {
    setIsPopoverOpen(false);
    onClosePopover();
  };
  const updateTagsHook = (0, _hooks.useUpdateTags)();

  // update labels after tags changing
  (0, _react.useEffect)(() => {
    setLabels(labelsFromTags(allTags, selectedTags));
  }, [allTags, labelsFromTags, selectedTags]);
  const isExactMatch = (0, _react.useMemo)(() => labels.some(label => label.label === searchValue), [labels, searchValue]);
  const handleTagsUpdated = (tagsToAdd, tagsToRemove, hasCompleted = true, isRenameOrDelete = false) => {
    if (hasCompleted) {
      return onTagsUpdated();
    }
    const selected = labels.filter(tag => tag.checked === 'on').map(tag => tag.label);
    const newSelectedTags = (0, _lodash.difference)(selected, tagsToRemove).concat(tagsToAdd);
    const allTagsWithNew = (0, _lodash.uniq)(allTags.concat(newSelectedTags));
    const allTagsWithRemove = isRenameOrDelete ? (0, _lodash.difference)(allTagsWithNew, tagsToRemove) : allTagsWithNew;
    setLabels(labelsFromTags(allTagsWithRemove, newSelectedTags));
  };
  const updateTags = async (tagsToAdd, tagsToRemove, successMessage, errorMessage) => {
    if (agentId) {
      const newSelectedTags = (0, _lodash.difference)(selectedTags, tagsToRemove).concat(tagsToAdd);
      updateTagsHook.updateTags(agentId, newSelectedTags, () => onTagsUpdated(), successMessage, errorMessage);
    } else {
      updateTagsHook.bulkUpdateTags(agents, tagsToAdd, tagsToRemove, hasCompleted => handleTagsUpdated(tagsToAdd, tagsToRemove, hasCompleted), successMessage, errorMessage);
    }
  };
  const renderOption = (option, search) => {
    return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      gutterSize: 's',
      onMouseEnter: () => setIsTagHovered({
        ...isTagHovered,
        [option.label]: true
      }),
      onMouseLeave: () => setIsTagHovered({
        ...isTagHovered,
        [option.label]: false
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(TruncatedEuiHighlight, {
      search: search,
      onClick: () => {
        const tagsToAdd = option.checked === 'on' ? [] : [option.label];
        const tagsToRemove = option.checked === 'on' ? [option.label] : [];
        updateTags(tagsToAdd, tagsToRemove);
      }
    }, option.label)), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_tag_options.TagOptions, {
      tagName: option.label,
      isTagHovered: isTagHovered[option.label],
      onTagsUpdated: (tagsToAdd, tagsToRemove, hasCompleted) => handleTagsUpdated(tagsToAdd, tagsToRemove, hasCompleted, true)
    })));
  };
  const createTagButton = /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    color: "text",
    "data-test-subj": "createTagBtn",
    onClick: () => {
      if (!searchValue) {
        return;
      }
      updateTags([searchValue], [], _i18n.i18n.translate('xpack.fleet.createAgentTags.successNotificationTitle', {
        defaultMessage: 'Tag created'
      }), _i18n.i18n.translate('xpack.fleet.createAgentTags.errorNotificationTitle', {
        defaultMessage: 'Tag creation failed'
      }));
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    gutterSize: "s"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: "plus"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.tagsAddRemove.createText",
    defaultMessage: "Create a new tag \"{name}\"",
    values: {
      name: searchValue
    }
  }))));
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiWrappingPopover, {
    isOpen: isPopoverOpen,
    button: button,
    closePopover: closePopover,
    anchorPosition: "leftUp"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelectable
  // workaround for auto-scroll to first element after clearing search
  , {
    onFocus: () => {},
    "aria-label": _i18n.i18n.translate('xpack.fleet.tagsAddRemove.selectableTagsLabel', {
      defaultMessage: 'Add / remove tags'
    }),
    searchable: true,
    searchProps: {
      'data-test-subj': 'addRemoveTags',
      placeholder: _i18n.i18n.translate('xpack.fleet.tagsAddRemove.findOrCreatePlaceholder', {
        defaultMessage: 'Find or create tag...'
      }),
      onChange: value => {
        setSearchValue((0, _utils.sanitizeTag)(value));
      },
      value: searchValue !== null && searchValue !== void 0 ? searchValue : ''
    },
    options: labels,
    renderOption: renderOption
  }, (list, search) => /*#__PURE__*/_react.default.createElement(_react.Fragment, null, search, list)), (!isExactMatch || labels.length === 0) && searchValue !== '' ? createTagButton : null));
};
exports.TagsAddRemove = TagsAddRemove;