"use strict";

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

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

var _keyBy = _interopRequireDefault(require("lodash/keyBy"));

var _uniq = _interopRequireDefault(require("lodash/uniq"));

var _immutable = require("immutable");

var _constants = require("@instructure/quiz-common/lib/constants");

var updateQuizSessionSessionItemReferences = function updateQuizSessionSessionItemReferences(state, sessionItems) {
  var reducer = function reducer(tempState, sessionItem) {
    return tempState.updateIn([sessionItem.quizSessionId, 'sessionItems'], function (items) {
      return (items || (0, _immutable.fromJS)([])).push(sessionItem.id);
    });
  };

  var uniqifySessionItems = function uniqifySessionItems(quizSession) {
    if (!(quizSession instanceof _immutable.Map)) {
      return quizSession;
    }

    return quizSession.updateIn(['sessionItems'], function (items) {
      var jsItems = items ? items.toJS() : [];
      return (0, _immutable.fromJS)((0, _uniq.default)(jsItems));
    });
  };

  return sessionItems.reduce(reducer, state).map(uniqifySessionItems);
};

var addQuizSessions = function addQuizSessions(state, quizSessions) {
  var keyedQuizSessions = (0, _keyBy.default)(quizSessions, 'id');
  return state.mergeWith( // to avoid replacing Lists with null (sessionItems)
  function (oldValue, newValue) {
    return oldValue.merge ? oldValue.merge(newValue) : newValue;
  }, (0, _immutable.fromJS)(keyedQuizSessions));
};

var defaultState = (0, _immutable.fromJS)({});

var _default = function _default() {
  var state = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : defaultState;
  var action = arguments.length > 1 ? arguments[1] : void 0;

  switch (action.type) {
    case _constants.ADD_QUIZ_SESSIONS:
      return addQuizSessions(state, action.payload);

    case _constants.ADD_SESSION_ITEMS:
      return updateQuizSessionSessionItemReferences(state, action.payload);

    case _constants.ACTIVE_QUIZ_SESSION_CHANGE:
      return state.set('activeQuizSessionId', action.payload);

    default:
      return state;
  }
};

exports.default = _default;