"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FollowerIndicesList = 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 _public = require("@kbn/kibana-react-plugin/public");
var _shared_imports = require("../../../../shared_imports");
var _track_ui_metric = require("../../../services/track_ui_metric");
var _constants = require("../../../constants");
var _components = require("./components");
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 REFRESH_RATE_MS = 30000;
const getQueryParamName = ({
  location: {
    search
  }
}) => {
  const {
    name
  } = (0, _shared_imports.extractQueryParams)(search);
  return name ? decodeURIComponent(name) : null;
};
class FollowerIndicesList extends _react.PureComponent {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "state", {
      lastFollowerIndexId: null,
      isDetailPanelOpen: false
    });
  }
  static getDerivedStateFromProps({
    followerIndexId
  }, {
    lastFollowerIndexId
  }) {
    if (followerIndexId !== lastFollowerIndexId) {
      return {
        lastFollowerIndexId: followerIndexId,
        isDetailPanelOpen: !!followerIndexId
      };
    }
    return null;
  }
  componentDidMount() {
    const {
      loadFollowerIndices,
      selectFollowerIndex,
      history
    } = this.props;
    (0, _track_ui_metric.trackUiMetric)(_track_ui_metric.METRIC_TYPE.LOADED, _constants.UIM_FOLLOWER_INDEX_LIST_LOAD);
    loadFollowerIndices();

    // Select the pattern in the URL query params
    selectFollowerIndex(getQueryParamName(history));

    // Interval to load follower indices in the background passing "true" to the fetch method
    this.interval = setInterval(() => loadFollowerIndices(true), REFRESH_RATE_MS);
  }
  componentDidUpdate(prevProps, prevState) {
    const {
      history
    } = this.props;
    const {
      lastFollowerIndexId
    } = this.state;

    /**
     * Each time our state is updated (through getDerivedStateFromProps())
     * we persist the follower index id to query params for deep linking
     */
    if (lastFollowerIndexId !== prevState.lastFollowerIndexId) {
      if (!lastFollowerIndexId) {
        history.replace({
          search: ''
        });
      } else {
        history.replace({
          search: `?name=${encodeURIComponent(lastFollowerIndexId)}`
        });
      }
    }
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
  renderEmpty() {
    return /*#__PURE__*/_react.default.createElement(_eui.EuiPageTemplate.EmptyPrompt, {
      iconType: "managementApp",
      "data-test-subj": "emptyPrompt",
      title: /*#__PURE__*/_react.default.createElement("h1", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.crossClusterReplication.followerIndexList.emptyPromptTitle",
        defaultMessage: "Create your first follower index"
      })),
      body: /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.crossClusterReplication.followerIndexList.emptyPromptDescription",
        defaultMessage: "Use a follower index to replicate a leader index on a remote cluster."
      })),
      actions: /*#__PURE__*/_react.default.createElement(_eui.EuiButton, (0, _extends2.default)({}, (0, _public.reactRouterNavigate)(this.props.history, `/follower_indices/add`), {
        fill: true,
        iconType: "plusInCircle",
        "data-test-subj": "createFollowerIndexButton"
      }), /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.crossClusterReplication.addFollowerButtonLabel",
        defaultMessage: "Create a follower index"
      }))
    });
  }
  renderLoading() {
    return /*#__PURE__*/_react.default.createElement(_shared_imports.PageLoading, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.crossClusterReplication.followerIndexList.loadingTitle",
      defaultMessage: "Loading follower indices..."
    }));
  }
  renderList() {
    const {
      selectFollowerIndex,
      followerIndices
    } = this.props;
    const {
      isDetailPanelOpen
    } = this.state;
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.crossClusterReplication.followerIndexList.followerIndicesDescription",
      defaultMessage: "A follower index replicates a leader index on a remote cluster."
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "l"
    }), /*#__PURE__*/_react.default.createElement(_components.FollowerIndicesTable, {
      followerIndices: followerIndices
    }), isDetailPanelOpen && /*#__PURE__*/_react.default.createElement(_components.DetailPanel, {
      closeDetailPanel: () => selectFollowerIndex(null)
    }));
  }
  render() {
    const {
      followerIndices,
      apiError,
      isAuthorized,
      apiStatus
    } = this.props;
    const isEmpty = apiStatus === _constants.API_STATUS.IDLE && !followerIndices.length;
    if (!isAuthorized) {
      return /*#__PURE__*/_react.default.createElement(_shared_imports.PageError, {
        title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
          id: "xpack.crossClusterReplication.followerIndexList.permissionErrorTitle",
          defaultMessage: "Permission error"
        }),
        error: {
          error: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.crossClusterReplication.followerIndexList.noPermissionText",
            defaultMessage: "You do not have permission to view or add follower indices."
          })
        }
      });
    }
    if (apiError) {
      const title = _i18n.i18n.translate('xpack.crossClusterReplication.followerIndexList.loadingErrorTitle', {
        defaultMessage: 'Error loading follower indices'
      });
      return /*#__PURE__*/_react.default.createElement(_shared_imports.PageError, {
        title: title,
        error: apiError.body
      });
    }
    if (isEmpty) {
      return this.renderEmpty();
    }
    if (apiStatus === _constants.API_STATUS.LOADING) {
      return this.renderLoading();
    }
    return this.renderList();
  }
}
exports.FollowerIndicesList = FollowerIndicesList;
(0, _defineProperty2.default)(FollowerIndicesList, "propTypes", {
  loadFollowerIndices: _propTypes.default.func,
  selectFollowerIndex: _propTypes.default.func,
  followerIndices: _propTypes.default.array,
  apiStatus: _propTypes.default.string,
  apiError: _propTypes.default.object
});