'use strict';

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

var _immutable = require('immutable');

var _presenter = require('./presenter');

var _presenter2 = _interopRequireDefault(_presenter);

var _reactRedux = require('../../../../common/react-redux');

var _SessionItem = require('../../../../common/records/SessionItem');

var _SessionItem2 = _interopRequireDefault(_SessionItem);

var _SessionItemResult = require('../../../../common/records/SessionItemResult');

var _SessionItemResult2 = _interopRequireDefault(_SessionItemResult);

var _QuizSession = require('../../../../common/records/QuizSession');

var _QuizSession2 = _interopRequireDefault(_QuizSession);

var _QuizSessionResult = require('../../../../common/records/QuizSessionResult');

var _QuizSessionResult2 = _interopRequireDefault(_QuizSessionResult);

var _quizSessions = require('../../../../common/actions/quizSessions');

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

function mapStateToProps(state, ownProps) {
  var quizSessionId = ownProps.quizSessionId;
  var quizSession = new _QuizSession2.default(state.getIn(['quizSessions', quizSessionId]));
  var qsrId = quizSession.authoritativeResult;
  var authoritativeResult = new _QuizSessionResult2.default(state.getIn(['quizSessionResults', qsrId]));

  var scope = function scope(record) {
    return record.get('quizSessionId') === quizSessionId;
  };
  var sessionItemResults = state.get('sessionItemResults', (0, _immutable.Map)()).filter(scope).map(function (sir) {
    return _SessionItemResult2.default.create(sir);
  }).sortBy(function (sir) {
    return sir.position;
  }).toList();

  var sessionItems = state.get('sessionItems', (0, _immutable.Map)()).filter(scope).map(function (si) {
    return _SessionItem2.default.create(si);
  }).sortBy(function (si) {
    return si.position;
  }).toList();

  // assume it has questions until loaded
  var hasQuestions = quizSession.isLoaded() ? quizSession.sessionItemsCount > 0 : true;
  // If the quiz has no questions, it will always be loading, so short-circuit it
  var needToLoad = hasQuestions && (!quizSession.isLoaded() || !authoritativeResult.isLoaded() || sessionItems.size === 0 || sessionItemResults.size === 0);

  return {
    appContainer: state.getIn(['ui', 'appContainer']),
    authoritativeResult: authoritativeResult,
    needToLoad: needToLoad,
    quizSession: quizSession,
    sessionItemResults: sessionItemResults,
    sessionItems: sessionItems,
    isAutograding: quizSession.isLoaded() ? quizSession.autoGrading() : quizSession.inProgress()
  };
}

var mapDispatchToProps = {
  getResultInfo: _quizSessions.getResultInfo
};

exports.default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(_presenter2.default);