"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FollowerIndicesTable = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _constants = require("../../../../../constants");
var _components = require("../../../../../components");
var _routing = require("../../../../../services/routing");
var _track_ui_metric = require("../../../../../services/track_ui_metric");
var _context_menu = require("../context_menu");
var _public = require("@kbn/kibana-react-plugin/public");
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 actionI18nTexts = {
  pause: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.actionPauseDescription', {
    defaultMessage: 'Pause replication'
  }),
  resume: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.actionResumeDescription', {
    defaultMessage: 'Resume replication'
  }),
  edit: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.actionEditDescription', {
    defaultMessage: 'Edit follower index'
  }),
  unfollow: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.actionUnfollowDescription', {
    defaultMessage: 'Unfollow leader index'
  })
};
const getFilteredIndices = (followerIndices, queryText) => {
  if (queryText) {
    const normalizedSearchText = queryText.toLowerCase();
    return followerIndices.filter(followerIndex => {
      // default values to avoid undefined errors
      const {
        name = '',
        remoteCluster = '',
        leaderIndex = ''
      } = followerIndex;
      if (name.toLowerCase().includes(normalizedSearchText)) {
        return true;
      }
      if (leaderIndex.toLowerCase().includes(normalizedSearchText)) {
        return true;
      }
      if (remoteCluster.toLowerCase().includes(normalizedSearchText)) {
        return true;
      }
      return false;
    });
  }
  return followerIndices;
};
class FollowerIndicesTable extends _react.PureComponent {
  static getDerivedStateFromProps(props, state) {
    const {
      followerIndices
    } = props;
    const {
      prevFollowerIndices,
      queryText
    } = state;

    // If a follower index gets deleted, we need to recreate the cached filtered follower indices.
    if (prevFollowerIndices !== followerIndices) {
      return {
        prevFollowerIndices: followerIndices,
        filteredIndices: getFilteredIndices(followerIndices, queryText)
      };
    }
    return null;
  }
  constructor(props) {
    super(props);
    (0, _defineProperty2.default)(this, "onSearch", ({
      query
    }) => {
      const {
        followerIndices
      } = this.props;
      const {
        text
      } = query;

      // We cache the filtered indices instead of calculating them inside render() because
      // of https://github.com/elastic/eui/issues/3445.
      this.setState({
        queryText: text,
        filteredIndices: getFilteredIndices(followerIndices, text)
      });
    });
    (0, _defineProperty2.default)(this, "editFollowerIndex", id => {
      const uri = _routing.routing.getFollowerIndexPath(id);
      _routing.routing.navigate(uri);
    });
    (0, _defineProperty2.default)(this, "renderLoading", () => {
      const {
        apiStatusDelete
      } = this.props;
      if (apiStatusDelete === _constants.API_STATUS.DELETING) {
        return /*#__PURE__*/_react.default.createElement(_eui.EuiOverlayMask, null, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingLogo, {
          logo: "logoKibana",
          size: "xl"
        }));
      }
      return null;
    });
    this.state = {
      prevFollowerIndices: props.followerIndices,
      selectedItems: [],
      filteredIndices: props.followerIndices,
      queryText: ''
    };
  }
  getTableColumns(actionHandlers) {
    const {
      selectFollowerIndex
    } = this.props;
    const actions = [/* Pause follower index */
    {
      name: actionI18nTexts.pause,
      description: actionI18nTexts.pause,
      icon: 'pause',
      onClick: item => actionHandlers.pauseFollowerIndex(item),
      available: item => !item.isPaused,
      'data-test-subj': 'pauseButton'
    }, /* Resume follower index */
    {
      name: actionI18nTexts.resume,
      description: actionI18nTexts.resume,
      icon: 'play',
      onClick: item => actionHandlers.resumeFollowerIndex(item.name),
      available: item => item.isPaused,
      'data-test-subj': 'resumeButton'
    }, /* Edit follower index */
    {
      name: actionI18nTexts.edit,
      description: actionI18nTexts.edit,
      onClick: item => this.editFollowerIndex(item.name),
      icon: 'pencil',
      'data-test-subj': 'editButton'
    }, /* Unfollow leader index */
    {
      name: actionI18nTexts.unfollow,
      description: actionI18nTexts.unfollow,
      onClick: item => actionHandlers.unfollowLeaderIndex(item.name),
      icon: 'indexFlush',
      'data-test-subj': 'unfollowButton'
    }];
    return [{
      field: 'name',
      name: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.nameColumnTitle', {
        defaultMessage: 'Name'
      }),
      sortable: true,
      truncateText: false,
      render: name => {
        return /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
          onClick: () => {
            (0, _track_ui_metric.trackUiMetric)('click', _constants.UIM_FOLLOWER_INDEX_SHOW_DETAILS_CLICK);
            selectFollowerIndex(name);
          },
          "data-test-subj": "followerIndexLink"
        }, name);
      }
    }, {
      field: 'isPaused',
      name: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.statusColumnTitle', {
        defaultMessage: 'Status'
      }),
      truncateText: true,
      sortable: true,
      render: isPaused => {
        return isPaused ? /*#__PURE__*/_react.default.createElement(_eui.EuiHealth, {
          color: "subdued"
        }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.crossClusterReplication.followerIndexList.table.statusColumn.pausedLabel",
          defaultMessage: "Paused"
        })) : /*#__PURE__*/_react.default.createElement(_eui.EuiHealth, {
          color: "success"
        }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.crossClusterReplication.followerIndexList.table.statusColumn.activeLabel",
          defaultMessage: "Active"
        }));
      }
    }, {
      field: 'remoteCluster',
      name: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.clusterColumnTitle', {
        defaultMessage: 'Remote cluster'
      }),
      truncateText: true,
      sortable: true
    }, {
      field: 'leaderIndex',
      name: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.leaderIndexColumnTitle', {
        defaultMessage: 'Leader index'
      }),
      truncateText: true,
      sortable: true
    }, {
      name: _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.table.actionsColumnTitle', {
        defaultMessage: 'Actions'
      }),
      actions,
      width: '100px'
    }];
  }
  render() {
    const {
      selectedItems,
      filteredIndices
    } = this.state;
    const sorting = {
      sort: {
        field: 'name',
        direction: 'asc'
      }
    };
    const pagination = {
      initialPageSize: 20,
      pageSizeOptions: [10, 20, 50]
    };
    const selection = {
      onSelectionChange: newSelectedItems => this.setState({
        selectedItems: newSelectedItems
      })
    };
    const search = {
      toolsLeft: selectedItems.length ? /*#__PURE__*/_react.default.createElement(_context_menu.ContextMenu, {
        followerIndices: selectedItems,
        testSubj: "contextMenuButton"
      }) : undefined,
      toolsRight: /*#__PURE__*/_react.default.createElement(_eui.EuiButton, (0, _extends2.default)({}, (0, _public.reactRouterNavigate)(_routing.routing._reactRouter.history, `/follower_indices/add`), {
        fill: true,
        iconType: "plusInCircle",
        "data-test-subj": "createFollowerIndexButton"
      }), /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.crossClusterReplication.followerIndexList.addFollowerButtonLabel",
        defaultMessage: "Create a follower index"
      })),
      onChange: this.onSearch,
      box: {
        incremental: true,
        'data-test-subj': 'followerIndexSearch'
      }
    };
    return /*#__PURE__*/_react.default.createElement(_components.FollowerIndexActionsProvider, null, getActionHandlers => {
      const actionHandlers = getActionHandlers();
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiInMemoryTable, {
        items: filteredIndices,
        itemId: "name",
        columns: this.getTableColumns(actionHandlers),
        search: search,
        pagination: pagination,
        sorting: sorting,
        selection: selection,
        isSelectable: true,
        rowProps: () => ({
          'data-test-subj': 'row'
        }),
        cellProps: (item, column) => ({
          'data-test-subj': `cell-${column.field}`
        }),
        "data-test-subj": "followerIndexListTable"
      }), this.renderLoading());
    });
  }
}
exports.FollowerIndicesTable = FollowerIndicesTable;
(0, _defineProperty2.default)(FollowerIndicesTable, "propTypes", {
  followerIndices: _propTypes.default.array,
  selectFollowerIndex: _propTypes.default.func.isRequired
});