"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf3 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

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

var Immutable = _interopRequireWildcard(require("immutable"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

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

var _Paginator = _interopRequireDefault(require("../Paginator"));

var _Spinner = _interopRequireDefault(require("../spinner/Spinner"));

var _theme = _interopRequireDefault(require("./theme"));

var _dec, _class, _class2, _temp;

/**
 * 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 = {
  componentId: 'wHCnH',
  template: function template(theme) {
    return "\n\n.wHCnH_eMrv{color:".concat(theme.emptyColor || 'inherit', ";font-size:").concat(theme.emptyFontSize || 'inherit', ";padding:").concat(theme.emptyPadding || 'inherit', ";text-align:center}\n\n[dir=ltr] .wHCnH_eMrv,[dir=rtl] .wHCnH_eMrv{text-align:center}");
  },
  'empty': 'wHCnH_eMrv'
};

var _ref3 =
/*#__PURE__*/
_react.default.createElement(_Spinner.default, null);

var PaginatedCollection = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(PaginatedCollection, _Component);

  function PaginatedCollection() {
    var _getPrototypeOf2;

    var _this;

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

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

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(PaginatedCollection)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _this.onPageChange = function (nextPage) {
      _this.props.merge(_this.props.stateKey, {
        current: nextPage
      });
    };

    return _this;
  }

  (0, _createClass2.default)(PaginatedCollection, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.getPage(this.props.stateKey, this.props.currentPage, this.props.params);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(_ref) {
      var merge = _ref.merge,
          params = _ref.params,
          set = _ref.set,
          stateKey = _ref.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 _getPage = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee(stateKey, page, params) {
        var _ref2, records, totalPages;

        return _regenerator.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:
                _ref2 = _context.sent;
                records = _ref2.records;
                totalPages = _ref2.totalPages;

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

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

      function getPage(_x, _x2, _x3) {
        return _getPage.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 _react.default.createElement("div", {
        className: styles.empty
      }, this.props.empty);
    }
  }, {
    key: "renderLoading",
    value: function renderLoading() {
      return _ref3;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          currentPage = _this$props.currentPage,
          totalPages = _this$props.totalPages;
      return _react.default.createElement(_Paginator.default, {
        currentPage: currentPage,
        onPageChange: this.onPageChange,
        totalPages: totalPages
      }, this.recordsLoaded() ? this.renderRecords() : this.renderLoading());
    }
  }]);
  PaginatedCollection.displayName = "PaginatedCollection";
  return PaginatedCollection;
}(_react.Component), _class2.propTypes = {
  currentPage: _propTypes.default.number.isRequired,
  contents: _reactImmutableProptypes.default.map.isRequired,
  empty: _propTypes.default.node,
  getPage: _propTypes.default.func.isRequired,
  merge: _propTypes.default.func.isRequired,
  params: _reactImmutableProptypes.default.map,
  renderRecords: _propTypes.default.func.isRequired,
  set: _propTypes.default.func.isRequired,
  stateKey: _propTypes.default.string.isRequired,
  totalPages: _propTypes.default.number.isRequired
}, _class2.defaultProps = {
  empty: null,
  params: Immutable.Map()
}, _temp)) || _class);
exports.default = PaginatedCollection;