'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactIntl = require('react-intl');

var _cspaceInput = require('cspace-input');

var _PageSizeChooser = require('./PageSizeChooser');

var _PageSizeChooser2 = _interopRequireDefault(_PageSizeChooser);

var _Pager = require('../../../styles/cspace-ui/Pager.css');

var _Pager2 = _interopRequireDefault(_Pager);

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var MiniButton = _cspaceInput.baseComponents.MiniButton;


var messages = (0, _reactIntl.defineMessages)({
  previousLabel: {
    'id': 'pager.previous',
    'defaultMessage': '<'
  },
  nextLabel: {
    'id': 'pager.next',
    'defaultMessage': '>'
  },
  gap: {
    'id': 'pager.gap',
    'defaultMessage': '...'
  }
});

var propTypes = {
  currentPage: _propTypes2.default.number.isRequired,
  lastPage: _propTypes2.default.number.isRequired,
  pageSize: _propTypes2.default.number.isRequired,
  pageSizeOptionListName: _propTypes2.default.string,
  windowSize: _propTypes2.default.number,
  onPageChange: _propTypes2.default.func,
  onPageSizeChange: _propTypes2.default.func
};

var defaultProps = {
  windowSize: 5
};

var Pager = function (_Component) {
  _inherits(Pager, _Component);

  function Pager() {
    _classCallCheck(this, Pager);

    var _this = _possibleConstructorReturn(this, (Pager.__proto__ || Object.getPrototypeOf(Pager)).call(this));

    _this.handleNextButtonClick = _this.handleNextButtonClick.bind(_this);
    _this.handlePageButtonClick = _this.handlePageButtonClick.bind(_this);
    _this.handlePrevButtonClick = _this.handlePrevButtonClick.bind(_this);
    return _this;
  }

  _createClass(Pager, [{
    key: 'handleNextButtonClick',
    value: function handleNextButtonClick() {
      var _props = this.props,
          currentPage = _props.currentPage,
          onPageChange = _props.onPageChange;


      if (onPageChange) {
        onPageChange(currentPage + 1);
      }
    }
  }, {
    key: 'handlePageButtonClick',
    value: function handlePageButtonClick(event) {
      var onPageChange = this.props.onPageChange;


      if (onPageChange) {
        var pageNum = event.currentTarget.dataset.pagenum;


        onPageChange(parseInt(pageNum, 10));
      }
    }
  }, {
    key: 'handlePrevButtonClick',
    value: function handlePrevButtonClick() {
      var _props2 = this.props,
          currentPage = _props2.currentPage,
          onPageChange = _props2.onPageChange;


      if (onPageChange) {
        onPageChange(currentPage - 1);
      }
    }
  }, {
    key: 'renderPages',
    value: function renderPages() {
      var _this2 = this;

      var _props3 = this.props,
          currentPage = _props3.currentPage,
          lastPage = _props3.lastPage,
          windowSize = _props3.windowSize;


      var pageCount = lastPage + 1;

      var windowStart = 0;
      var windowEnd = lastPage;

      if (windowSize < pageCount) {
        var beforeWindowSize = Math.floor((windowSize - 1) / 2);
        var afterWindowSize = windowSize - 1 - beforeWindowSize;

        if (beforeWindowSize > currentPage) {
          var offset = beforeWindowSize - currentPage;

          beforeWindowSize -= offset;
          afterWindowSize += offset;
        } else if (currentPage + afterWindowSize > lastPage) {
          var _offset = currentPage + afterWindowSize - lastPage;

          beforeWindowSize += _offset;
          afterWindowSize -= _offset;
        }

        windowStart = currentPage - beforeWindowSize;
        windowEnd = currentPage + afterWindowSize;
      }

      var pages = [];

      if (windowStart > 0) {
        pages.push({
          pageNum: 0,
          label: _react2.default.createElement(_reactIntl.FormattedNumber, { value: 1 })
        });

        var gap = windowStart;

        if (gap > 2) {
          var gapMiddle = windowStart - Math.floor(windowStart / 2);

          pages.push({
            pageNum: gapMiddle,
            label: _react2.default.createElement(_reactIntl.FormattedMessage, messages.gap)
          });
        } else if (gap > 1) {
          pages.push({
            pageNum: 1,
            label: _react2.default.createElement(_reactIntl.FormattedNumber, { value: 2 })
          });
        }
      }

      for (var pageNum = windowStart; pageNum <= windowEnd; pageNum += 1) {
        pages.push({
          pageNum: pageNum,
          label: _react2.default.createElement(_reactIntl.FormattedNumber, { value: pageNum + 1 })
        });
      }

      if (windowEnd < lastPage) {
        var _gap = lastPage - windowEnd;

        if (_gap > 2) {
          var _gapMiddle = windowEnd + Math.ceil((lastPage - windowEnd) / 2);

          pages.push({
            pageNum: _gapMiddle,
            label: _react2.default.createElement(_reactIntl.FormattedMessage, messages.gap)
          });
        } else if (_gap > 1) {
          pages.push({
            pageNum: lastPage - 1,
            label: _react2.default.createElement(_reactIntl.FormattedNumber, { value: lastPage })
          });
        }

        pages.push({
          pageNum: lastPage,
          label: _react2.default.createElement(_reactIntl.FormattedNumber, { value: lastPage + 1 })
        });
      }

      var items = pages.map(function (page) {
        return _react2.default.createElement(
          'li',
          { key: page.pageNum },
          _react2.default.createElement(
            MiniButton,
            {
              'data-pagenum': page.pageNum,
              disabled: page.pageNum === currentPage,
              onClick: _this2.handlePageButtonClick
            },
            page.label
          )
        );
      });

      return _react2.default.createElement(
        'ul',
        null,
        items
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props,
          currentPage = _props4.currentPage,
          lastPage = _props4.lastPage,
          pageSize = _props4.pageSize,
          pageSizeOptionListName = _props4.pageSizeOptionListName,
          onPageSizeChange = _props4.onPageSizeChange;


      return _react2.default.createElement(
        'div',
        { className: _Pager2.default.common },
        _react2.default.createElement(_PageSizeChooser2.default, {
          embedded: true,
          pageSize: pageSize,
          pageSizeOptionListName: pageSizeOptionListName,
          onPageSizeChange: onPageSizeChange
        }),
        _react2.default.createElement(
          'nav',
          null,
          _react2.default.createElement(
            MiniButton,
            {
              disabled: currentPage === 0,
              onClick: this.handlePrevButtonClick
            },
            _react2.default.createElement(_reactIntl.FormattedMessage, messages.previousLabel)
          ),
          this.renderPages(),
          _react2.default.createElement(
            MiniButton,
            {
              disabled: currentPage === lastPage,
              onClick: this.handleNextButtonClick
            },
            _react2.default.createElement(_reactIntl.FormattedMessage, messages.nextLabel)
          )
        )
      );
    }
  }]);

  return Pager;
}(_react.Component);

exports.default = Pager;


Pager.propTypes = propTypes;
Pager.defaultProps = defaultProps;