"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SAVED_OBJECTS_PER_PAGE_SETTING = exports.SAVED_OBJECTS_LIMIT_SETTING = exports.EventAnnotationGroupTableList = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _contentManagementTableListViewTable = require("@kbn/content-management-table-list-view-table");
var _i18n = require("@kbn/i18n");
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _public = require("@kbn/data-plugin/public");
var _react2 = require("@emotion/react");
var _group_editor_flyout = require("./group_editor_flyout");
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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const SAVED_OBJECTS_LIMIT_SETTING = 'savedObjects:listingLimit';
exports.SAVED_OBJECTS_LIMIT_SETTING = SAVED_OBJECTS_LIMIT_SETTING;
const SAVED_OBJECTS_PER_PAGE_SETTING = 'savedObjects:perPage';
exports.SAVED_OBJECTS_PER_PAGE_SETTING = SAVED_OBJECTS_PER_PAGE_SETTING;
const getCustomColumn = dataViews => {
  const dataViewNameMap = Object.fromEntries(dataViews.map(dataView => {
    var _dataView$name;
    return [dataView.id, (_dataView$name = dataView.name) !== null && _dataView$name !== void 0 ? _dataView$name : dataView.title];
  }));
  return {
    field: 'dataView',
    name: _i18n.i18n.translate('eventAnnotationListing.tableList.dataView', {
      defaultMessage: 'Data view'
    }),
    sortable: false,
    width: '150px',
    render: (_field, record) => {
      var _dataViewNameMap$reco;
      return /*#__PURE__*/_react.default.createElement("div", null, record.attributes.dataViewSpec ? record.attributes.dataViewSpec.name : (_dataViewNameMap$reco = dataViewNameMap[record.attributes.indexPatternId]) !== null && _dataViewNameMap$reco !== void 0 ? _dataViewNameMap$reco : /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
        size: "s",
        color: 'danger'
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "eventAnnotationListing.tableList.dataView.missing",
        defaultMessage: "{errorIcon} No longer exists",
        values: {
          errorIcon: /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
            type: "error",
            css: (0, _react2.css)`
                          margin-top: -3px;
                        `
          })
        }
      })));
    }
  };
};
const EventAnnotationGroupTableList = ({
  uiSettings,
  eventAnnotationService,
  sessionService,
  visualizeCapabilities,
  savedObjectsTagging,
  parentProps,
  dataViews,
  createDataView,
  queryInputServices,
  toasts,
  navigateToLens,
  LensEmbeddableComponent
}) => {
  const listingLimit = uiSettings.get(SAVED_OBJECTS_LIMIT_SETTING);
  const initialPageSize = uiSettings.get(SAVED_OBJECTS_PER_PAGE_SETTING);
  const [searchSessionId, setSearchSessionId] = (0, _react.useState)(sessionService.start());
  const refreshSearchSession = (0, _react.useCallback)(() => {
    setSearchSessionId(sessionService.start());
  }, [sessionService]);
  (0, _react.useEffect)(() => {
    return () => {
      sessionService.clear();
    };
  }, [sessionService]);
  const [refreshListBouncer, setRefreshListBouncer] = (0, _react.useState)(false);
  const refreshList = (0, _react.useCallback)(() => {
    setRefreshListBouncer(prev => !prev);
  }, []);
  const fetchItems = (0, _react.useCallback)((searchTerm, {
    references,
    referencesToExclude
  } = {}) => {
    // todo - allow page size changes
    return eventAnnotationService.findAnnotationGroupContent(searchTerm, listingLimit, // TODO is this right?
    references === null || references === void 0 ? void 0 : references.map(({
      id
    }) => id), referencesToExclude === null || referencesToExclude === void 0 ? void 0 : referencesToExclude.map(({
      id
    }) => id));
  }, [eventAnnotationService, listingLimit]);
  const editItem = (0, _react.useCallback)(({
    id
  }) => {
    if (visualizeCapabilities.save) {
      eventAnnotationService.loadAnnotationGroup(id).then(group => setGroupToEditInfo({
        group,
        id
      }));
    }
  }, [eventAnnotationService, visualizeCapabilities.save]);
  const [groupToEditInfo, setGroupToEditInfo] = (0, _react.useState)();
  const flyout = groupToEditInfo ? /*#__PURE__*/_react.default.createElement(_group_editor_flyout.GroupEditorFlyout, {
    group: groupToEditInfo.group,
    updateGroup: newGroup => setGroupToEditInfo({
      group: newGroup,
      id: groupToEditInfo.id
    }),
    onClose: () => setGroupToEditInfo(undefined),
    onSave: () => (groupToEditInfo.id ? eventAnnotationService.updateAnnotationGroup(groupToEditInfo.group, groupToEditInfo.id) : eventAnnotationService.createAnnotationGroup(groupToEditInfo.group)).then(() => {
      setGroupToEditInfo(undefined);
      toasts.addSuccess(`Saved "${groupToEditInfo.group.title}"`);
      refreshList();
    }),
    savedObjectsTagging: savedObjectsTagging,
    dataViews: dataViews,
    createDataView: createDataView,
    LensEmbeddableComponent: LensEmbeddableComponent,
    queryInputServices: queryInputServices,
    searchSessionId: searchSessionId,
    refreshSearchSession: refreshSearchSession,
    timePickerQuickRanges: uiSettings.get(_public.UI_SETTINGS.TIMEPICKER_QUICK_RANGES)
  }) : undefined;
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_contentManagementTableListViewTable.TableListViewTable, (0, _extends2.default)({
    id: "eventAnnotation",
    refreshListBouncer: refreshListBouncer,
    tableCaption: _i18n.i18n.translate('eventAnnotationListing.tableList.listTitle', {
      defaultMessage: 'Annotation Library'
    }),
    findItems: fetchItems,
    deleteItems: visualizeCapabilities.delete ? items => eventAnnotationService.deleteAnnotationGroups(items.map(({
      id
    }) => id)) : undefined,
    editItem: editItem,
    listingLimit: listingLimit,
    initialPageSize: initialPageSize,
    initialFilter: '',
    customTableColumn: getCustomColumn(dataViews),
    emptyPrompt: /*#__PURE__*/_react.default.createElement(_eui.EuiEmptyPrompt, {
      color: "transparent",
      title: /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, null, /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "eventAnnotationListing.tableList.emptyPrompt.title",
        defaultMessage: "Create your first annotation in Lens"
      }))),
      body: /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "eventAnnotationListing.tableList.emptyPrompt.body",
        defaultMessage: "You can create and save annotations for use across multiple visualizations in the Lens editor."
      })),
      actions: /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
        onClick: navigateToLens
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "eventAnnotationListing.tableList.emptyPrompt.cta",
        defaultMessage: "Create annotation in Lens"
      })),
      iconType: "flag"
    }),
    entityName: _i18n.i18n.translate('eventAnnotationListing.tableList.entityName', {
      defaultMessage: 'annotation group'
    }),
    entityNamePlural: _i18n.i18n.translate('eventAnnotationListing.tableList.entityNamePlural', {
      defaultMessage: 'annotation groups'
    }),
    onClickTitle: editItem
  }, parentProps)), flyout);
};
exports.EventAnnotationGroupTableList = EventAnnotationGroupTableList;