'use strict';

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

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec, _class, _class2, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _immutable = require('immutable');

var Immutable = _interopRequireWildcard(_immutable);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactImmutableProptypes = require('react-immutable-proptypes');

var _reactImmutableProptypes2 = _interopRequireDefault(_reactImmutableProptypes);

var _lib = require('@instructure/ui-themeable/lib');

var _lib2 = _interopRequireDefault(_lib);

var _Paginator = require('../Paginator');

var _Paginator2 = _interopRequireDefault(_Paginator);

var _Spinner = require('../spinner/Spinner');

var _Spinner2 = _interopRequireDefault(_Spinner);

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

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)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

/**
 * Renders pagination controls and manages state of page contents. `getPage`
 * will be called with the page number and any collection parameters, and should
 * return a promise that resolves to `{ records, totalPages }`, where `records`
 * is an array of arbitrary records, and `totalPages` is the total number of
 * pages. `renderRecords` will be called with `records` as returned from the
 * `getPage` function. It is the responsibility of that function to render the
 * page.
 *
 * This component assumes that changing collection `params` can change the
 * underlying collection that is fetched. It thus resets the page cache when
 * `params` change.
 */

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n._1vW6_BwQV-8R_vBHntA5H5 {\n  padding: ' + theme.emptyPadding + ';\n  font-size: ' + theme.emptyFontSize + ';\n  text-align: center;\n  color: ' + theme.emptyColor + ';\n}\n\n[dir="ltr"] ._1vW6_BwQV-8R_vBHntA5H5 {\n  text-align: center;\n}\n\n[dir="rtl"] ._1vW6_BwQV-8R_vBHntA5H5 {\n  text-align: center;\n}\n';
  },
  'empty': '_1vW6_BwQV-8R_vBHntA5H5'
};

var _ref5 = _react2.default.createElement(_Spinner2.default, null);

var PaginatedCollection = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(PaginatedCollection, _Component);

  function PaginatedCollection() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, PaginatedCollection);

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

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = PaginatedCollection.__proto__ || Object.getPrototypeOf(PaginatedCollection)).call.apply(_ref, [this].concat(args))), _this), _this.onPageChange = function (nextPage) {
      _this.props.merge(_this.props.stateKey, { current: nextPage });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(PaginatedCollection, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.getPage(this.props.stateKey, this.props.currentPage, this.props.params);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(_ref2) {
      var merge = _ref2.merge,
          params = _ref2.params,
          set = _ref2.set,
          stateKey = _ref2.stateKey;

      if (!params.equals(this.props.params)) {
        set(stateKey, Immutable.fromJS({ current: 1 }));
      } else if (stateKey !== this.props.stateKey) {
        merge(stateKey, { current: 1 });
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.getPage(this.props.stateKey, this.props.currentPage, this.props.params);
    }
  }, {
    key: 'getPage',
    value: function () {
      var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(stateKey, page, params) {
        var _ref4, records, totalPages;

        return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!this.recordsLoaded(page)) {
                  _context.next = 2;
                  break;
                }

                return _context.abrupt('return');

              case 2:
                _context.next = 4;
                return this.props.getPage(page, params);

              case 4:
                _ref4 = _context.sent;
                records = _ref4.records;
                totalPages = _ref4.totalPages;


                if (params.equals(this.props.params)) {
                  this.props.merge(stateKey, {
                    contents: (0, _defineProperty3.default)({}, page, records),
                    total: totalPages
                  });
                }

              case 8:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getPage(_x, _x2, _x3) {
        return _ref3.apply(this, arguments);
      }

      return getPage;
    }()
  }, {
    key: 'recordsLoaded',
    value: function recordsLoaded() {
      var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.currentPage;

      return this.props.contents.get(page.toString()) !== void 0;
    }
  }, {
    key: 'renderRecords',
    value: function renderRecords() {
      var records = this.props.contents.get(this.props.currentPage.toString());
      if (records.size === 0 && this.props.empty) {
        return this.renderEmpty();
      }
      return this.props.renderRecords(records.toJS());
    }
  }, {
    key: 'renderEmpty',
    value: function renderEmpty() {
      return _react2.default.createElement(
        'div',
        { className: styles.empty },
        this.props.empty
      );
    }
  }, {
    key: 'renderLoading',
    value: function renderLoading() {
      return _ref5;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          currentPage = _props.currentPage,
          totalPages = _props.totalPages;

      return _react2.default.createElement(
        _Paginator2.default,
        {
          currentPage: currentPage,
          onPageChange: this.onPageChange,
          totalPages: totalPages
        },
        this.recordsLoaded() ? this.renderRecords() : this.renderLoading()
      );
    }
  }]);
  PaginatedCollection.displayName = 'PaginatedCollection'
  ;
  return PaginatedCollection;
}(_react.Component), _class2.propTypes = {
  currentPage: _propTypes2.default.number.isRequired,
  contents: _reactImmutableProptypes2.default.map.isRequired,
  empty: _propTypes2.default.node,
  getPage: _propTypes2.default.func.isRequired,
  merge: _propTypes2.default.func.isRequired,
  params: _reactImmutableProptypes2.default.map,
  renderRecords: _propTypes2.default.func.isRequired,
  set: _propTypes2.default.func.isRequired,
  stateKey: _propTypes2.default.string.isRequired,
  totalPages: _propTypes2.default.number.isRequired
}, _class2.defaultProps = {
  empty: null,
  params: Immutable.Map()
}, _temp2)) || _class);
exports.default = PaginatedCollection;