function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { EuiPaginationButton } from './pagination_button';
import { EuiButtonIcon } from '../button';
import { EuiI18n } from '../i18n';
import { EuiText } from '../text';
import { EuiHideFor } from '../responsive';
var MAX_VISIBLE_PAGES = 5;
var NUMBER_SURROUNDING_PAGES = Math.floor(MAX_VISIBLE_PAGES * 0.5);
export var EuiPagination = function EuiPagination(_ref) {
  var className = _ref.className,
    _ref$pageCount = _ref.pageCount,
    pageCount = _ref$pageCount === void 0 ? 1 : _ref$pageCount,
    _ref$activePage = _ref.activePage,
    activePage = _ref$activePage === void 0 ? 1 : _ref$activePage,
    _ref$onPageClick = _ref.onPageClick,
    onPageClick = _ref$onPageClick === void 0 ? function () {} : _ref$onPageClick,
    compressed = _ref.compressed,
    ariaControls = _ref['aria-controls'],
    rest = _objectWithoutProperties(_ref, ["className", "pageCount", "activePage", "onPageClick", "compressed", "aria-controls"]);
  var safeClick = function safeClick(e, pageIndex) {
    e.preventDefault();
    if (ariaControls) {
      var controlledElement = document.getElementById(ariaControls);
      if (controlledElement) {
        controlledElement.focus();
      }
    }
    onPageClick(pageIndex);
  };
  var PaginationButton = function PaginationButton(_ref2) {
    var pageIndex = _ref2.pageIndex,
      _ref2$inList = _ref2.inList,
      inList = _ref2$inList === void 0 ? true : _ref2$inList;
    var button = /*#__PURE__*/React.createElement(EuiPaginationButton, _extends({
      isActive: pageIndex === activePage,
      totalPages: pageCount,
      onClick: function onClick(e) {
        return safeClick(e, pageIndex);
      },
      pageIndex: pageIndex
    }, hasControl && {
      'aria-controls': ariaControls
    }, {
      hideOnMobile: true
    }));
    if (inList) {
      return /*#__PURE__*/React.createElement("li", {
        className: "euiPagination__item"
      }, button);
    }
    return button;
  };
  var classes = classNames('euiPagination', className);
  var hasControl = ariaControls !== undefined;
  var pages = [];
  var firstPageInRange = Math.max(0, Math.min(activePage - NUMBER_SURROUNDING_PAGES, pageCount - MAX_VISIBLE_PAGES));
  var lastPageInRange = Math.min(pageCount, firstPageInRange + MAX_VISIBLE_PAGES);
  for (var i = firstPageInRange, index = 0; i < lastPageInRange; i++, index++) {
    pages.push(/*#__PURE__*/React.createElement(PaginationButton, {
      pageIndex: i,
      key: i
    }));
  }
  var prevPageButtonProps = {};
  if (hasControl && activePage !== 0) {
    prevPageButtonProps = {
      'aria-controls': ariaControls,
      href: "#".concat(ariaControls)
    };
  } else {
    prevPageButtonProps = {
      disabled: activePage === 0
    };
  }
  var previousButton = /*#__PURE__*/React.createElement(EuiI18n, {
    token: "euiPagination.previousPage",
    default: "Previous page, {page}",
    values: {
      page: activePage
    }
  }, function (previousPage) {
    return /*#__PURE__*/React.createElement(EuiI18n, {
      token: "euiPagination.disabledPreviousPage",
      default: "Previous page"
    }, function (disabledPreviousPage) {
      return /*#__PURE__*/React.createElement(EuiButtonIcon, _extends({
        onClick: function onClick(e) {
          return safeClick(e, activePage - 1);
        },
        iconType: "arrowLeft",
        color: "text",
        "aria-label": activePage === 0 ? disabledPreviousPage : previousPage,
        "data-test-subj": "pagination-button-previous"
      }, prevPageButtonProps));
    });
  });
  var firstPageButtons = [];
  if (firstPageInRange > 0) {
    firstPageButtons.push(/*#__PURE__*/React.createElement(PaginationButton, {
      pageIndex: 0,
      key: 0
    }));
    if (firstPageInRange > 1 && firstPageInRange !== 2) {
      firstPageButtons.push(/*#__PURE__*/React.createElement(EuiI18n, {
        key: "startingEllipses",
        token: "euiPagination.firstRangeAriaLabel",
        default: "Skipping pages 2 to {lastPage}",
        values: {
          lastPage: firstPageInRange
        }
      }, function (firstRangeAriaLabel) {
        return /*#__PURE__*/React.createElement("li", {
          "aria-label": firstRangeAriaLabel,
          className: "euiPaginationButton-isPlaceholder euiPagination__item"
        }, "\u2026");
      }));
    } else if (firstPageInRange === 2) {
      firstPageButtons.push(/*#__PURE__*/React.createElement(PaginationButton, {
        pageIndex: 1,
        key: 1
      }));
    }
  }
  var lastPageButtons = [];
  if (lastPageInRange < pageCount) {
    if (lastPageInRange + 1 === pageCount - 1) {
      lastPageButtons.push(/*#__PURE__*/React.createElement(PaginationButton, {
        pageIndex: lastPageInRange,
        key: lastPageInRange
      }));
    } else if (lastPageInRange < pageCount - 1) {
      lastPageButtons.push(/*#__PURE__*/React.createElement(EuiI18n, {
        key: "endingEllipses",
        token: "euiPagination.lastRangeAriaLabel",
        default: "Skipping pages {firstPage} to {lastPage}",
        values: {
          firstPage: lastPageInRange + 1,
          lastPage: pageCount - 1
        }
      }, function (lastRangeAriaLabel) {
        return /*#__PURE__*/React.createElement("li", {
          "aria-label": lastRangeAriaLabel,
          className: "euiPaginationButton-isPlaceholder euiPagination__item"
        }, "\u2026");
      }));
    }
    lastPageButtons.push(/*#__PURE__*/React.createElement(PaginationButton, {
      pageIndex: pageCount - 1,
      key: pageCount - 1
    }));
  }
  var nextPageButtonProps = {};
  if (hasControl && activePage !== pageCount - 1) {
    nextPageButtonProps = {
      'aria-controls': ariaControls,
      href: "#".concat(ariaControls)
    };
  } else {
    nextPageButtonProps = {
      disabled: activePage === pageCount - 1
    };
  }
  var nextButton = /*#__PURE__*/React.createElement(EuiI18n, {
    token: "euiPagination.nextPage",
    default: "Next page, {page}",
    values: {
      page: activePage + 2
    }
  }, function (nextPage) {
    return /*#__PURE__*/React.createElement(EuiI18n, {
      token: "euiPagination.disabledNextPage",
      default: "Next page"
    }, function (disabledNextPage) {
      return /*#__PURE__*/React.createElement(EuiButtonIcon, _extends({
        onClick: function onClick(e) {
          return safeClick(e, activePage + 1);
        },
        iconType: "arrowRight",
        "aria-label": activePage === pageCount - 1 ? disabledNextPage : nextPage,
        color: "text",
        "data-test-subj": "pagination-button-next"
      }, nextPageButtonProps));
    });
  });
  var selectablePages = pages;
  if (compressed) {
    var firstPageButtonCompressed = /*#__PURE__*/React.createElement(PaginationButton, {
      pageIndex: activePage,
      inList: false
    });
    var lastPageButtonCompressed = /*#__PURE__*/React.createElement(PaginationButton, {
      pageIndex: pageCount - 1,
      inList: false
    });
    return /*#__PURE__*/React.createElement("nav", _extends({
      className: classes
    }, rest), previousButton, /*#__PURE__*/React.createElement(EuiHideFor, {
      sizes: ['xs', 's']
    }, /*#__PURE__*/React.createElement(EuiText, {
      size: "s",
      className: "euiPagination__compressedText"
    }, /*#__PURE__*/React.createElement(EuiI18n, {
      token: "euiPagination.pageOfTotalCompressed",
      default: "{page} of {total}",
      values: {
        page: firstPageButtonCompressed,
        total: lastPageButtonCompressed
      }
    }))), nextButton);
  }
  var accessibleName = _objectSpread(_objectSpread({}, rest['aria-label'] && {
    'aria-label': rest['aria-label']
  }), rest['aria-labelledby'] && {
    'aria-labelledby': rest['aria-labelledby']
  });
  return /*#__PURE__*/React.createElement("nav", _extends({
    className: classes
  }, rest), previousButton, /*#__PURE__*/React.createElement("ul", _extends({}, accessibleName, {
    className: "euiPagination__list"
  }), firstPageButtons, selectablePages, lastPageButtons), nextButton);
};
EuiPagination.propTypes = {
  className: PropTypes.string,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string,
  /**
     * The total number of pages.
     */
  pageCount: PropTypes.number,
  /**
     * The current page using a zero based index.
     * So if you set the activePage to 1, it will activate the second page.
     */
  activePage: PropTypes.number,
  onPageClick: PropTypes.func,
  /**
     * If true, will only show next/prev arrows instead of page numbers.
     */
  compressed: PropTypes.bool,
  /**
     * If passed in, passes value through to each button to set aria-controls
     */
  "aria-controls": PropTypes.string
};