'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 _OptClass = require('../internal/OptClass');

var _OptClass2 = _interopRequireDefault(_OptClass);

var _ActivityFeedItem = require('./ActivityFeedItem');

var _ActivityFeedItem2 = _interopRequireDefault(_ActivityFeedItem);

var _reactInfinite = require('react-infinite');

var _reactInfinite2 = _interopRequireDefault(_reactInfinite);

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

var _Spinner2 = _interopRequireDefault(_Spinner);

var _style = require('./style.scss');

var _style2 = _interopRequireDefault(_style);

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 ActivityFeed = function (_React$Component) {
  _inherits(ActivityFeed, _React$Component);

  function ActivityFeed(props) {
    _classCallCheck(this, ActivityFeed);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ActivityFeed).call(this, props));

    _this.handleSetHeight = function (i, height) {
      if (_this.state.heights[i] !== height) {
        var heights = _this.state.heights;
        heights[i] = height;
        _this.setState({ heights: heights });
      }
    };

    _this.getHeight = function (i) {
      return _this.state.heights[i] + '-px';
    };

    _this.buildElements = function (start, data) {
      var items = [];
      var heights = [];
      for (var i = start; i < data.length; i++) {
        var item = data[i];
        var stateIndex = start + i;
        heights.push(_this.state && _this.state.heights[stateIndex] || 200);
        items.push(_react2.default.createElement(_ActivityFeedItem2.default, {
          key: stateIndex,
          name: item.name,
          badge: item.badge,
          profileUrl: item.profileUrl,
          profileUrlTarget: item.profileUrlTarget,
          title: item.title,
          actions: item.actions,
          text: item.text,
          time: item.timestamp,
          onSetHeight: _this.handleSetHeight.bind(_this, i)
        }));
      }

      return { items: items, heights: heights };
    };

    _this.state = {
      data: _this.props.data,
      heights: [],
      items: [],
      fetchMoreEnabled: true
    };

    _this.componentWillMount = function () {
      _this.setState(_this.buildElements(0, _this.props.data));
    };

    _this.componentWillReceiveProps = function (nextProps) {
      var _this$buildElements = _this.buildElements(0, nextProps.data);

      var items = _this$buildElements.items;
      var heights = _this$buildElements.heights;


      _this.setState({
        data: nextProps.data,
        items: items,
        heights: heights
      });
    };

    _this.handleInfiniteLoad = function () {
      // If we've already fetched as many items as there are available
      // or no function has been provided to fetch more
      // then there is no need to fetch.
      if (_this.props.totalCount && _this.state.items.length >= _this.props.totalCount || typeof _this.props.onInfiniteLoad !== 'function') {
        _this.setState({ isInfiniteLoading: false });
        return;
      }

      // If we are already loading more items do not keep trying
      if (_this.state.isInfiniteLoading) {
        return;
      }

      // Show loader while fetching
      _this.setState({ isInfiniteLoading: true });
      return _this.props.onInfiniteLoad().then(function () {
        _this.setState({ isInfiniteLoading: false });
      }).catch(function () {
        _this.setState({ isInfiniteLoading: false });
      });
    };

    return _this;
  }

  _createClass(ActivityFeed, [{
    key: 'render',
    value: function render() {
      var feedClasses = (0, _OptClass2.default)(_style2.default, 'activity-feed', this.props.optClass);
      var elementInfiniteLoad = _react2.default.createElement(
        'div',
        { className: _style2.default['loader'] },
        _react2.default.createElement(_Spinner2.default, { loading: true, optClass: _style2.default['spinner'], type: 'spinner-bounce', color: '#3C97D3' })
      );

      return _react2.default.createElement(
        'div',
        { className: feedClasses },
        _react2.default.createElement(
          'ul',
          null,
          _react2.default.createElement(
            _reactInfinite2.default,
            {
              elementHeight: this.state.heights,
              useWindowAsScrollContainer: true,
              infiniteLoadBeginEdgeOffset: 1000,
              onInfiniteLoad: this.handleInfiniteLoad,
              loadingSpinnerDelegate: elementInfiniteLoad,
              preloadAdditionalHeight: window.innerHeight * 2,
              isInfiniteLoading: this.state.isInfiniteLoading },
            this.state.items
          )
        )
      );
    }
  }]);

  return ActivityFeed;
}(_react2.default.Component);

ActivityFeed.propTypes = {
  /**
   * The activity feed data.
   */
  data: _react2.default.PropTypes.array.isRequired,
  /**
   * Callback to fetch more activity feed items.
   * The callack should return a promise that resolves once the data has been fetched.
   * The promise should be rejected if there are no more items to load.
   * The callback should also update props.data with the additional items before resolving the promise.
   */
  onInfiniteLoad: _react2.default.PropTypes.func,
  /**
   * Optional CSS class(es) to be used for local styles (string or array of strings).
   */
  optClass: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.array, _react2.default.PropTypes.string]),
  /**
   * Optional total count to prevent infinite scroll from requesting more items.
   */
  totalCount: _react2.default.PropTypes.number
};
exports.default = ActivityFeed;