'use strict';

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

var _buttonIcon, _list;

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; }; }();

exports.pages = pages;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _radium = require('radium');

var _radium2 = _interopRequireDefault(_radium);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _text = require('kitten/components/typography/text');

var _arrowIcon = require('kitten/components/icons/arrow-icon');

var _screenConfig = require('kitten/constants/screen-config');

var _colorsConfig = require('kitten/constants/colors-config');

var _colorsConfig2 = _interopRequireDefault(_colorsConfig);

var _parser = require('kitten/helpers/utils/parser');

var _mediaQueries = require('kitten/hoc/media-queries');

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

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; }

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; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var Text = (0, _radium2.default)(_text.Text);
var ArrowIcon = (0, _radium2.default)(_arrowIcon.ArrowIcon);

// Returns an array with the given bounds
var range = function range(start, end) {
  return Array(end - start + 1).fill().map(function (_, index) {
    return start + index;
  });
};

// Returns an array of size `availableSlots` with page number integers
// and breaks "…" (represented as nulls).
function pages(min, max, currentPage, availableSlots) {
  // 1, 2, 3
  if (max - min < availableSlots) {
    return range(min, max);
  }

  // 1, 2, 3, …, 42
  if (currentPage - min + 1 < availableSlots - 2) {
    return [].concat(_toConsumableArray(range(min, min - 1 + availableSlots - 2)), [null, max]);
  }

  // 1, …, 40, 41, 42
  if (max - currentPage < availableSlots - 2) {
    return [min, null].concat(_toConsumableArray(range(max + 1 - (availableSlots - 2), max)));
  }

  // 1, …, 21, …, 42
  var sides = Math.floor((availableSlots - 4) / 2);
  return [min, null].concat(_toConsumableArray(range(currentPage - sides, currentPage + sides)), [null, max]);
}

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

  function PaginationBase() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, PaginationBase);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = PaginationBase.__proto__ || Object.getPrototypeOf(PaginationBase)).call.apply(_ref, [this].concat(args))), _this), _this.preventClickDefault = function (e) {
      return e.preventDefault();
    }, _this.pageClickHandler = function (number) {
      return function (event) {
        return _this.props.onPageClick(number, event);
      };
    }, _this.renderPage = function (number, index) {
      if (!number) return _this.renderSpacer(index);

      var isActive = number === _this.props.currentPage;
      var tag = isActive ? 'span' : 'a';
      var href = isActive ? null : _this.props.goToPageHref(number);

      var styleButtonIcon = [styles.group.list.buttonIcon, isActive && styles.group.list.buttonIcon.isActive];

      return _react2.default.createElement(
        'li',
        { style: styles.group.list, key: 'page-' + number },
        _react2.default.createElement(
          Text,
          {
            tag: tag,
            weight: 'regular',
            size: 'tiny',
            href: href,
            key: 'link-' + number,
            style: styleButtonIcon,
            'aria-label': _this.props.goToPageLabel(number),
            onClick: isActive ? null : _this.pageClickHandler(number)
          },
          number
        )
      );
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(PaginationBase, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          totalPages = _props.totalPages,
          currentPage = _props.currentPage;

      var size = this.props.viewportIsTabletOrLess ? 5 : 7;
      var pageNumbers = pages(1, totalPages, currentPage, size);

      return _react2.default.createElement(
        'nav',
        { role: 'navigation', 'aria-label': this.props['aria-label'] },
        _react2.default.createElement(
          'ul',
          { style: styles.group },
          this.renderArrowButton('left'),
          pageNumbers.map(this.renderPage),
          this.renderArrowButton('right')
        )
      );
    }
  }, {
    key: 'renderSpacer',
    value: function renderSpacer(index) {
      return _react2.default.createElement(
        'li',
        { key: 'spacer-' + index, style: styles.group.list.points },
        '…'
      );
    }
  }, {
    key: 'renderArrowButton',
    value: function renderArrowButton(direction) {
      var _props2 = this.props,
          prevButtonLabel = _props2.prevButtonLabel,
          nextButtonLabel = _props2.nextButtonLabel,
          currentPage = _props2.currentPage,
          totalPages = _props2.totalPages;


      var buttonLabel = direction == 'left' ? (0, _parser.parseHtml)(prevButtonLabel) : (0, _parser.parseHtml)(nextButtonLabel);

      var isDisabled = direction == 'left' ? currentPage == 1 : currentPage == totalPages;

      var linkIsHovered = _radium2.default.getState(this.state, 'link-' + direction, ':hover');
      var linkIsFocused = _radium2.default.getState(this.state, 'link-' + direction, ':focus');
      var linkIsActived = _radium2.default.getState(this.state, 'link-' + direction, ':active');

      var styleList = [direction == 'left' && styles.group.list.left, direction == 'right' && styles.group.list.right];

      var styleButtonIcon = [styles.group.list.buttonIcon, isDisabled && styles.group.list.buttonIcon.isDisabled];

      var styleSvg = [styles.group.list.buttonIcon.svg, linkIsHovered && !isDisabled && styles.group.list.buttonIcon.svg.hover, linkIsFocused && !isDisabled && styles.group.list.buttonIcon.svg.focus, linkIsActived && !isDisabled && styles.group.list.buttonIcon.svg.active];

      var number = direction == 'left' ? currentPage == 1 ? 1 : currentPage - 1 : currentPage == totalPages ? totalPages : currentPage + 1;

      return _react2.default.createElement(
        'li',
        { style: styleList },
        _react2.default.createElement(
          'a',
          {
            href: this.props.goToPageHref(number),
            key: 'link-' + direction,
            style: styleButtonIcon,
            'aria-label': buttonLabel,
            title: buttonLabel,
            tabIndex: isDisabled ? -1 : null,
            onClick: isDisabled ? this.preventClickDefault : this.pageClickHandler(number)
          },
          _react2.default.createElement(ArrowIcon, {
            direction: direction,
            disabled: isDisabled,
            style: styleSvg
          })
        )
      );
    }
  }]);

  return PaginationBase;
}(_react.Component);

PaginationBase.propTypes = {
  prevButtonLabel: _propTypes2.default.string,
  nextButtonLabel: _propTypes2.default.string,
  goToPageLabel: _propTypes2.default.func,
  goToPageHref: _propTypes2.default.func,
  onPageClick: _propTypes2.default.func,
  totalPages: _propTypes2.default.number,
  currentPage: _propTypes2.default.number,
  'aria-label': _propTypes2.default.string
};
PaginationBase.defaultProps = {
  prevButtonLabel: 'Previous page',
  nextButtonLabel: 'Next page',
  goToPageLabel: function goToPageLabel(n) {
    return 'Go to page ' + n;
  },
  goToPageHref: function goToPageHref(n) {
    return '#' + n;
  },
  onPageClick: function onPageClick() {},
  currentPage: 1,
  totalPages: 1,
  'aria-label': 'Pagination navigation'
};


var linkHoveredAndFocused = {
  color: _colorsConfig2.default.primary1,
  borderColor: _colorsConfig2.default.primary1,
  backgroundColor: _colorsConfig2.default.background1
};

var disabledPseudoClass = {
  color: _colorsConfig2.default.background1,
  borderColor: _colorsConfig2.default.line2,
  backgroundColor: _colorsConfig2.default.line2
};

var isActivedPseudoClass = {
  color: _colorsConfig2.default.background1,
  borderColor: _colorsConfig2.default.primary1,
  backgroundColor: _colorsConfig2.default.primary1
};

var styles = {
  group: {
    display: 'inline-flex',
    padding: 0,

    list: (_list = {
      listStyle: 'none',
      marginRight: 0
    }, _defineProperty(_list, '@media (min-width: ' + _screenConfig.ScreenConfig['S'].min + 'px)', {
      marginRight: '8px',
      marginLeft: '8px'
    }), _defineProperty(_list, 'lastChild', {
      marginRight: 0
    }), _defineProperty(_list, 'left', _defineProperty({
      marginRight: '30px',
      listStyle: 'none'
    }, '@media (min-width: ' + _screenConfig.ScreenConfig['S'].min + 'px)', {
      marginRight: '22px'
    })), _defineProperty(_list, 'right', _defineProperty({
      marginLeft: '30px',
      listStyle: 'none'
    }, '@media (min-width: ' + _screenConfig.ScreenConfig['S'].min + 'px)', {
      marginLeft: '22px'
    })), _defineProperty(_list, 'points', _defineProperty({
      listStyle: 'none',
      textDecoration: 'none',
      textAlign: 'center',
      alignSelf: 'center',
      width: '40px'
    }, '@media (min-width: ' + _screenConfig.ScreenConfig['S'].min + 'px)', {
      marginLeft: '8px',
      marginRight: '8px',
      width: '50px'
    })), _defineProperty(_list, 'buttonIcon', (_buttonIcon = {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      boxSizing: 'border-box',
      cursor: 'pointer',
      width: '40px',
      height: '40px',
      borderRadius: 0,
      borderWidth: 0,
      borderStyle: 'solid',
      textDecoration: 'none',
      outline: 'none',
      color: _colorsConfig2.default.font1,
      borderColor: _colorsConfig2.default.line1,
      backgroundColor: _colorsConfig2.default.background1,
      ':hover': linkHoveredAndFocused,
      ':focus': linkHoveredAndFocused,
      ':active': isActivedPseudoClass

    }, _defineProperty(_buttonIcon, '@media (min-width: ' + _screenConfig.ScreenConfig['S'].min + 'px)', {
      width: '50px',
      height: '50px',
      borderWidth: '2px'
    }), _defineProperty(_buttonIcon, 'isActive', {
      cursor: 'auto',
      color: _colorsConfig2.default.background1,
      borderColor: _colorsConfig2.default.primary1,
      backgroundColor: _colorsConfig2.default.primary1,
      ':hover': isActivedPseudoClass,
      ':focus': isActivedPseudoClass,
      ':active': isActivedPseudoClass
    }), _defineProperty(_buttonIcon, 'isDisabled', {
      color: _colorsConfig2.default.background1,
      borderColor: _colorsConfig2.default.line2,
      backgroundColor: _colorsConfig2.default.line2,
      cursor: 'not-allowed',
      ':hover': disabledPseudoClass,
      ':focus': disabledPseudoClass,
      ':active': disabledPseudoClass
    }), _defineProperty(_buttonIcon, 'svg', {
      alignSelf: 'center',
      margin: '0',
      padding: '0',
      width: '6px',
      height: '6px',
      pointerEvents: 'none',
      hover: {
        fill: _colorsConfig2.default.primary1
      },
      focus: {
        fill: _colorsConfig2.default.primary1
      },
      active: {
        fill: _colorsConfig2.default.background1
      },
      isDisabled: {
        fill: _colorsConfig2.default.background1
      }
    }), _buttonIcon)), _list)
  }
};

var Pagination = exports.Pagination = (0, _mediaQueries.mediaQueries)((0, _radium2.default)(PaginationBase), {
  viewportIsTabletOrLess: true
});