"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IndexPatternTableWithRouter = exports.IndexPatternTable = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _reactRouterDom = require("react-router-dom");
var _useObservable = _interopRequireDefault(require("react-use/lib/useObservable"));
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/kibana-react-plugin/public");
var _sharedUxPromptNoDataViews = require("@kbn/shared-ux-prompt-no-data-views");
var _empty_index_list_prompt = require("../empty_index_list_prompt");
var _breadcrumbs = require("../breadcrumbs");
var _spaces_list = require("./spaces_list");
var _edit_index_pattern = require("../edit_index_pattern");
var _delete_modal_msg = require("./delete_modal_msg");
var _data_view_table_controller = require("./data_view_table_controller");
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 pagination = {
  initialPageSize: 10,
  pageSizeOptions: [5, 10, 25, 50]
};
const sorting = {
  sort: {
    field: 'title',
    direction: 'asc'
  }
};
const title = _i18n.i18n.translate('indexPatternManagement.dataViewTable.title', {
  defaultMessage: 'Data Views'
});
const securityDataView = _i18n.i18n.translate('indexPatternManagement.indexPatternTable.badge.securityDataViewTitle', {
  defaultMessage: 'Security Data View'
});
const securitySolution = 'security-solution';
const getEmptyFunctionComponent = ({
  children
}) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, children);
const IndexPatternTable = ({
  history,
  canSave,
  showCreateDialog: showCreateDialogProp = false
}) => {
  const {
    setBreadcrumbs,
    uiSettings,
    application,
    chrome,
    dataViews,
    IndexPatternEditor,
    spaces,
    overlays,
    docLinks
  } = (0, _public.useKibana)().services;
  const [query, setQuery] = (0, _react.useState)('');
  const [showCreateDialog, setShowCreateDialog] = (0, _react.useState)(showCreateDialogProp);
  const [selectedItems, setSelectedItems] = (0, _react.useState)([]);
  const [dataViewController] = (0, _react.useState)(() => new _data_view_table_controller.DataViewTableController({
    services: {
      dataViews
    },
    config: {
      defaultDataView: uiSettings.get('defaultIndex')
    }
  }));
  const isLoadingIndexPatterns = (0, _useObservable.default)(dataViewController.isLoadingIndexPatterns$, _data_view_table_controller.dataViewTableControllerStateDefaults.isLoadingDataViews);
  const indexPatterns = (0, _useObservable.default)(dataViewController.indexPatterns$, _data_view_table_controller.dataViewTableControllerStateDefaults.dataViews);
  const isLoadingDataState = (0, _useObservable.default)(dataViewController.isLoadingDataState$, _data_view_table_controller.dataViewTableControllerStateDefaults.isLoadingHasData);
  const hasDataView = (0, _useObservable.default)(dataViewController.hasDataView$, _data_view_table_controller.dataViewTableControllerStateDefaults.hasDataView);
  const hasESData = (0, _useObservable.default)(dataViewController.hasESData$, _data_view_table_controller.dataViewTableControllerStateDefaults.hasEsData);
  const handleOnChange = ({
    queryText,
    error
  }) => {
    if (!error) {
      setQuery(queryText);
    }
  };
  const renderDeleteButton = () => {
    const clickHandler = (0, _edit_index_pattern.removeDataView)({
      dataViews,
      overlays,
      uiSettings,
      onDelete: () => {
        setSelectedItems([]);
        dataViewController.loadDataViews();
      }
    });
    if (selectedItems.length === 0) {
      return;
    }
    return /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
      color: "danger",
      iconType: "trash",
      "data-test-subj": "delete-data-views-button",
      onClick: () => clickHandler(selectedItems, (0, _delete_modal_msg.deleteModalMsg)(selectedItems, !!spaces))
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.dataViewTable.deleteButtonLabel",
      defaultMessage: "Delete {selectedItems, number} {selectedItems, plural, one {Data View} other {Data Views}\n}",
      values: {
        selectedItems: selectedItems.length
      }
    }));
  };
  const deleteButton = renderDeleteButton();
  const search = {
    toolsLeft: deleteButton && [deleteButton],
    query,
    onChange: handleOnChange,
    box: {
      incremental: true,
      schema: {
        fields: {
          title: {
            type: 'string'
          }
        }
      }
    }
  };
  setBreadcrumbs((0, _breadcrumbs.getListBreadcrumbs)());
  chrome.docTitle.change(title);
  const isRollup = new URLSearchParams((0, _reactRouterDom.useLocation)().search).get('type') === 'rollup' && dataViews.getRollupsEnabled();
  const ContextWrapper = (0, _react.useMemo)(() => spaces ? spaces.ui.components.getSpacesContextProvider : getEmptyFunctionComponent, [spaces]);
  const removeHandler = (0, _edit_index_pattern.removeDataView)({
    dataViews,
    uiSettings,
    overlays,
    onDelete: () => dataViewController.loadDataViews()
  });
  const alertColumn = {
    name: 'Actions',
    field: 'id',
    width: '10%',
    actions: [{
      name: _i18n.i18n.translate('indexPatternManagement.dataViewTable.columnDelete', {
        defaultMessage: 'Delete'
      }),
      description: _i18n.i18n.translate('indexPatternManagement.dataViewTable.columnDeleteDescription', {
        defaultMessage: 'Delete this data view'
      }),
      icon: 'trash',
      color: 'danger',
      type: 'icon',
      onClick: dataView => removeHandler([dataView], (0, _delete_modal_msg.deleteModalMsg)([dataView], !!spaces)),
      isPrimary: true,
      'data-test-subj': 'action-delete'
    }]
  };
  const columns = [{
    field: 'title',
    name: _i18n.i18n.translate('indexPatternManagement.dataViewTable.nameColumn', {
      defaultMessage: 'Name'
    }),
    width: spaces ? '70%' : '90%',
    render: (name, dataView) => {
      var _dataView$id, _dataView$tags;
      return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, (0, _extends2.default)({}, (0, _public.reactRouterNavigate)(history, `patterns/${dataView.id}`), {
        "data-test-subj": `detail-link-${dataView.name}`
      }), dataView.getName(), dataView.name ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "\xA0", /*#__PURE__*/_react.default.createElement(_eui.EuiIconTip, {
        type: "iInCircle",
        color: "text",
        "aria-label": dataView.title,
        content: dataView.title
      })) : null), (dataView === null || dataView === void 0 ? void 0 : (_dataView$id = dataView.id) === null || _dataView$id === void 0 ? void 0 : _dataView$id.indexOf(securitySolution)) === 0 && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "\u2003", /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, null, securityDataView)), dataView === null || dataView === void 0 ? void 0 : (_dataView$tags = dataView.tags) === null || _dataView$tags === void 0 ? void 0 : _dataView$tags.map(({
        key: tagKey,
        name: tagName
      }) => /*#__PURE__*/_react.default.createElement("span", {
        key: tagKey
      }, "\u2003", /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, null, tagName))));
    },
    dataType: 'string',
    sortable: ({
      sort
    }) => sort
  }];
  if (spaces) {
    columns.push({
      field: 'namespaces',
      name: _i18n.i18n.translate('indexPatternManagement.dataViewTable.spacesColumn', {
        defaultMessage: 'Spaces'
      }),
      width: '20%',
      render: (name, dataView) => {
        return spaces ? /*#__PURE__*/_react.default.createElement(_spaces_list.SpacesList, {
          spacesApi: spaces,
          capabilities: application === null || application === void 0 ? void 0 : application.capabilities,
          spaceIds: dataView.namespaces || [],
          id: dataView.id,
          title: dataView.title,
          refresh: () => {
            dataViews.clearInstanceCache(dataView.id);
            dataViewController.loadDataViews();
          }
        }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);
      }
    });
  }
  if (dataViews.getCanSaveSync()) {
    columns.push(alertColumn);
  }
  const createButton = canSave ? /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    fill: true,
    iconType: "plusInCircle",
    onClick: () => setShowCreateDialog(true),
    "data-test-subj": "createIndexPatternButton"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "indexPatternManagement.dataViewTable.createBtn",
    defaultMessage: "Create data view"
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);
  if (isLoadingIndexPatterns) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);
  }
  const displayIndexPatternEditor = showCreateDialog ? /*#__PURE__*/_react.default.createElement(IndexPatternEditor, {
    onSave: indexPattern => {
      history.push(`patterns/${indexPattern.id}`);
    },
    onCancel: () => setShowCreateDialog(false),
    defaultTypeIsRollup: isRollup
  }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);
  const selection = {
    onSelectionChange: setSelectedItems
  };
  let displayIndexPatternSection = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiPageHeader, {
    pageTitle: title,
    description: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.dataViewTable.indexPatternExplanation",
      defaultMessage: "Create and manage the data views that help you retrieve your data from Elasticsearch."
    }),
    bottomBorder: true,
    rightSideItems: [createButton]
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "l"
  }), /*#__PURE__*/_react.default.createElement(ContextWrapper, null, /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, {
    allowNeutralSort: false,
    itemId: "id",
    isSelectable: dataViews.getCanSaveSync(),
    items: indexPatterns,
    columns: columns,
    pagination: pagination,
    sorting: sorting,
    search: search,
    selection: dataViews.getCanSaveSync() ? selection : undefined
  })));
  if (!hasDataView) displayIndexPatternSection = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xxl"
  }), /*#__PURE__*/_react.default.createElement(_sharedUxPromptNoDataViews.NoDataViewsPromptComponent, {
    onClickCreate: () => setShowCreateDialog(true),
    canCreateNewDataView: application.capabilities.indexPatterns.save,
    dataViewsDocLink: docLinks.links.indexPatterns.introduction,
    emptyPromptColor: 'subdued'
  }));
  if (!hasDataView && !hasESData) displayIndexPatternSection = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "xxl"
  }), /*#__PURE__*/_react.default.createElement(_empty_index_list_prompt.EmptyIndexListPrompt, {
    onRefresh: dataViewController.loadDataViews,
    createAnyway: () => setShowCreateDialog(true),
    canSaveIndexPattern: !!application.capabilities.indexPatterns.save,
    navigateToApp: application.navigateToApp,
    addDataUrl: docLinks.links.indexPatterns.introduction
  }));
  return /*#__PURE__*/_react.default.createElement("div", {
    "data-test-subj": "indexPatternTable",
    role: "region",
    "aria-label": title
  }, isLoadingDataState ? /*#__PURE__*/_react.default.createElement("div", {
    style: {
      display: 'flex',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
    size: "xxl"
  })) : displayIndexPatternSection, displayIndexPatternEditor);
};
exports.IndexPatternTable = IndexPatternTable;
const IndexPatternTableWithRouter = (0, _reactRouterDom.withRouter)(IndexPatternTable);
exports.IndexPatternTableWithRouter = IndexPatternTableWithRouter;