"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var React = _interopRequireWildcard(require("react"));

var _memoizeOne = _interopRequireDefault(require("memoize-one"));

var _index = require("../button/index.js");

var _index2 = require("../menu/index.js");

var _styledComponents = require("./styled-components.js");

var _icons = require("./icons.js");

var _overrides = require("../helpers/overrides.js");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Pagination =
/*#__PURE__*/
function (_React$PureComponent) {
  _inherits(Pagination, _React$PureComponent);

  function Pagination() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Pagination);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Pagination)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      isMenuOpen: false
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "dropdownContainerRef", React.createRef());

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onPageClick", function (event) {
      var el = _this.dropdownContainerRef.current;
      /* eslint-disable-next-line flowtype/no-weak-types */

      if (el && !el.contains(event.target)) {
        _this.setState({
          isMenuOpen: false
        });
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "getMenuOptions", (0, _memoizeOne.default)(function (numPages) {
      var menuOptions = [];

      for (var i = 1; i <= numPages; i++) {
        menuOptions.push({
          label: i
        });
      }

      return menuOptions;
    }));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onMenuItemSelect", function (_ref) {
      var item = _ref.item;
      var _this$props = _this.props,
          onPageChange = _this$props.onPageChange,
          currentPage = _this$props.currentPage;
      var page = item.label;

      if (page !== currentPage) {
        onPageChange && onPageChange({
          nextPage: page,
          prevPage: currentPage
        });

        _this.onDropdownButtonClick();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onPrevClick", function (event) {
      var _this$props2 = _this.props,
          currentPage = _this$props2.currentPage,
          onPageChange = _this$props2.onPageChange,
          onPrevClick = _this$props2.onPrevClick;
      onPageChange && onPageChange({
        nextPage: currentPage - 1,
        prevPage: currentPage
      });
      onPrevClick && onPrevClick({
        event: event
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onNextClick", function (event) {
      var _this$props3 = _this.props,
          currentPage = _this$props3.currentPage,
          onPageChange = _this$props3.onPageChange,
          onNextClick = _this$props3.onNextClick;
      onPageChange && onPageChange({
        nextPage: currentPage + 1,
        prevPage: currentPage
      });
      onNextClick && onNextClick({
        event: event
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onDropdownButtonClick", function () {
      var isMenuOpen = !_this.state.isMenuOpen; // no __BROWSER__ check because click only happens client-side

      if (isMenuOpen) {
        document.addEventListener('click', _this.onPageClick, {
          capture: true
        });
      } else {
        document.removeEventListener('click', _this.onPageClick, {
          capture: true
        });
      }

      _this.setState({
        isMenuOpen: isMenuOpen
      });
    });

    return _this;
  }

  _createClass(Pagination, [{
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          _this$props4$override = _this$props4.overrides,
          overrides = _this$props4$override === void 0 ? {} : _this$props4$override,
          currentPage = _this$props4.currentPage,
          labels = _this$props4.labels,
          numPages = _this$props4.numPages;
      var isMenuOpen = this.state.isMenuOpen;

      var _getOverrides = (0, _overrides.getOverrides)(overrides.Root, _styledComponents.Root),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          Root = _getOverrides2[0],
          rootProps = _getOverrides2[1];

      var _getOverrides3 = (0, _overrides.getOverrides)(overrides.PrevButton, _index.StyledBaseButton),
          _getOverrides4 = _slicedToArray(_getOverrides3, 2),
          PrevButton = _getOverrides4[0],
          prevButtonProps = _getOverrides4[1];

      var _getOverrides5 = (0, _overrides.getOverrides)(overrides.NextButton, _index.StyledBaseButton),
          _getOverrides6 = _slicedToArray(_getOverrides5, 2),
          NextButton = _getOverrides6[0],
          nextButtonProps = _getOverrides6[1];

      var _getOverrides7 = (0, _overrides.getOverrides)(overrides.MaxLabel, _styledComponents.MaxLabel),
          _getOverrides8 = _slicedToArray(_getOverrides7, 2),
          MaxLabel = _getOverrides8[0],
          maxLabelProps = _getOverrides8[1];

      var _getOverrides9 = (0, _overrides.getOverrides)(overrides.DropdownContainer, _styledComponents.DropdownContainer),
          _getOverrides10 = _slicedToArray(_getOverrides9, 2),
          DropdownContainer = _getOverrides10[0],
          dropdownContainerProps = _getOverrides10[1];

      var _getOverrides11 = (0, _overrides.getOverrides)(overrides.DropdownButton, _styledComponents.DropdownButton),
          _getOverrides12 = _slicedToArray(_getOverrides11, 2),
          DropdownButton = _getOverrides12[0],
          dropdownButtonProps = _getOverrides12[1];

      var _getOverrides13 = (0, _overrides.getOverrides)(overrides.DropdownMenu, _index2.StatefulMenu),
          _getOverrides14 = _slicedToArray(_getOverrides13, 2),
          DropdownMenu = _getOverrides14[0],
          dropdownMenuProps = _getOverrides14[1];

      var options = this.getMenuOptions(numPages);
      return React.createElement(Root, rootProps, React.createElement(_index.Button, _extends({
        onClick: this.onPrevClick,
        startEnhancer: _icons.ArrowLeft,
        kind: _index.KIND.tertiary,
        overrides: {
          BaseButton: PrevButton
        }
      }, prevButtonProps), labels.prevButton), React.createElement(DropdownContainer, _extends({
        $ref: this.dropdownContainerRef
      }, dropdownContainerProps), React.createElement(_index.Button, _extends({
        onClick: this.onDropdownButtonClick,
        endEnhancer: _icons.ArrowDown,
        kind: _index.KIND.tertiary,
        overrides: {
          BaseButton: DropdownButton
        }
      }, dropdownButtonProps), currentPage), isMenuOpen && // $FlowFixMe
      React.createElement(DropdownMenu, _extends({
        items: options,
        onItemSelect: this.onMenuItemSelect,
        initialState: {
          highlightedIndex: Math.max(currentPage - 1, 0)
        },
        overrides: {
          List: {
            component: _styledComponents.DropdownMenu,
            // Access $style manually because it has gone through transformation
            // from the override helper function already
            // $FlowFixMe
            style: dropdownMenuProps.$style
          }
        }
      }, dropdownMenuProps))), React.createElement(MaxLabel, maxLabelProps, "".concat(labels.preposition || '', " ").concat(numPages)), React.createElement(_index.Button, _extends({
        onClick: this.onNextClick,
        endEnhancer: _icons.ArrowRight,
        kind: _index.KIND.tertiary,
        overrides: {
          BaseButton: NextButton
        }
      }, nextButtonProps), labels.nextButton));
    }
  }]);

  return Pagination;
}(React.PureComponent);

exports.default = Pagination;

_defineProperty(Pagination, "defaultProps", {
  labels: {
    prevButton: 'Prev',
    nextButton: 'Next',
    preposition: 'of'
  },
  overrides: {}
});